Today we do more JS.
week2-basic-javacript/
|- monday.js
|- tuesday.js
|- wednesday.js
programmers
.'Bill'
.'Mark'
'Elon'
'Mark'
with 'Alan'
.'Bill'
from the it.console.log(programmers)
const programmers = [];
programmers[0] = "Bill";
programmers[1] = "Mark";
programmers[2] = "Elon";
programmers[1] = "Alan";
programmers.shift();
console.log(programmers);
Positive : We've learned how to define arrays, add elements to them, replace items in them, and remove items from them.
myCompanies
& add two companies you wanna work for.theirCompanies
, and add two companies the above programmers have started.techCompanies
.const myCompanies = ["grab", "vingroup"];
const theirCompanies = ["microsoft", "facebook"];
const techCompanies = myCompanies.concat(theirCompanies);
console.log(techCompanies);
Docs
Array methods are built specifically for arrays. They help us change the arrays themselves or get certain information out of them.
Reference: MDN Array
Add an item to the end of an array:
var fruits = ["Apple", "Banana"];
var newLength = fruits.push("Orange");
// newLength will be 3, and fruites becomes ["Apple", "Banana", "Orange"]
Determines whether the array contains a value
var pets = ["cat", "dog", "bat"];
console.log(pets.includes("cat"));
// expected output: true
console.log(pets.includes("at"));
// expected output: false
Remove an item from the end of an array:
var last = fruits.pop(); // remove Orange (from the end)
// last will be "Orange" and fruits becomes ["Apple", "Banana"]
Remove an item from the beginning of an array:
var first = fruits.shift(); // remove Apple from the front
// last will be "Apple" and fruits becomes ["Banana"]
Add an item to the beginning of an array:
newLength = fruits.unshift("Strawberry"); // add to the front
// newLength will be 2, and fruites becomes ["Strawberry", "Banana"]
Copy an array:
The slice()
method returns a shallow copy of a portion of an array into a new array object selected from start
to end
(end
not included) where start
and end
represent the index of items in that array. The original array will not be modified.
fruits.push("Mango");
fruits.push("Apple");
fruits.push("Orange");
// fruits = ["Strawberry", "Banana", "Mango", "Apple", "Orange"]
console.log(fruits.slice(2));
// expected output: Array ["Mango", "Apple", "Orange"]
console.log(fruits.slice(2, 4));
// expected output: Array ["Mango", "Apple"]
console.log(fruits.slice(1, 5));
// expected output: Array ["Banana", "Mango", "Apple", "Orange"]
Remove items from an index position
// fruits = ["Strawberry", "Banana", "Mango", "Apple", "Orange"]
var removedItems = fruits.splice(1, 3); // starting at the index position 1 and remove 3 items
// removedItems will be ["Banana", "Mango", "Apple"], fruits becomes ["Strawberry", "Orange"]
Assignment
reverseArray(arr)
that returns a copy of the input array in reversed order.console.log(reverseArray(["A", "B", "C"]));
// ["C", "B", "A"];
var arr = [1, 2, 3, 4, 5];
console.log(reverseArray(arr));
// [5, 4, 3, 2, 1]
console.log(arr);
// [1, 2, 3, 4, 5]
getRandomInt()
from Assignment 1 to generate an array called evenNumbers
containing 100 random integer numbers in the range 0 to 100 inclusively.(value allow to be duplicated)evenNumbers
array and store them in another array called oddNumbers
.Let's create objects that represent real world concepts.
mark
.fullName
.age
.city
.mark
object.const mark = {};
mark.fullName = "Mark Zuckerberg";
mark.company = "Google";
mark["company"] = "Facebook"; // 2nd way to set property on object
mark.age = 18;
mark.city = "San Francisco";
console.log(mark);
const elon = {
age: 33,
city: "Austin",
fullName: "Elon Musk",
companies: ["Space-X", "Tesla"],
};
console.log(elon);
isAnAdult()
which takes person
as it's argument and logs if the person
is an adult.isAnAdult()
and pass it our variable mark
.function isAnAdult(person) {
if (person.age > 17) {
console.log("Is adult!");
}
}
isAnAdult(mark);
isCoderSchoolStaff()
which takes person
as it's argument and logs if the person works at Coderschool.isCoderSchoolStaff()
and pass it the mark
.function isCoderSchoolStaff(person) {
if (person.company === "CoderSchool") {
console.log("Is working at CoderSchool!");
}
}
isCoderSchoolStaff(mark);
charles
that when passed to isCoderSchoolStaff()
will log "Is working at CoderSchool!".describePerson()
, that takes an argument, person
, and logs the person's fullName
, age
, and company
.logLastName()
, that takes an argument, person
, and logs that person's last name.getInitials()
, that takes an argument, person
, and logs that person's first and last name's initials.ageOneYear()
, that takes an argument, person
, and increased that person's age by one year.getBirthYear()
, that takes an argument, person
, and determines their birth year based on their age and the current year.Given the object below:
var userA = {
id: 123456,
name: "Peter Parker",
email: "peter.parker@gmail.com",
role: "student",
courseId: 112233,
};
use Object methods to log your answer to the console:
Nested Objects
{
id: 123456,
name: "Peter Parker",
email: "peter.parker@gmail.com",
role: "student",
courseId: 112233,
age:15,
tasks: [
{ name: "Task 1", status: "Done"},
{ name: "Task 2", status: "Not Started"},
{ name: "Task 3", status: "In Progress"},
{ name: "Task 4", status: "Not Started"},
{ name: "Task 5", status: "Done"},
{ name: "Task 6", status: "In Progress"},
{ name: "Task 7", status: "Not Started"},
{ name: "Task 8", status: "Done"},
{ name: "Task 9", status: "Done"},
{ name: "Task 10", status: "In Progress"}
]
};
listOfTask()
that takes in a user object like this and print out 3 lists of tasks that are "Not Started", "In Progress", and "Done", respectively.listOfTask(userA);
// Expected output in the console:
// Not Started:
// - Task 2
// - Task 4
// - Task 7
// In Progress:
// - Task 3
// - Task 6
// - Task 10
// Done:
// - Task 1
// - Task 5
// - Task 8
// - Task 9
Test your code
generateFakeTasks()
that RETURN an array of n
number of tasks (n
is the argument).status
is a random choice between "In progress", "Not Started", "Done" (Hint: use the function getRandomItem()
).var task1 = {
name: "Task 1", // The name is "Task " followed by an integer number
status: "pending", // One options between ["In progress", "Not Started", "done"]
};
The array userA.tasks
in the exercise above should be a good example.
var tasks = generateFakeTasks(3);
console.log(tasks);
// Example output:
// [
// { name: "Task 1", status: "Done" },
// { name: "Task 2", status: "Not Started" },
// { name: "Task 3", status: "In Progress" },
// ]
userA
object and test your listOfTask()
function.//your code above
userA.tasks = generateFakeTask(6); //make 6 fake tasks
console.log(userA);
//expected to see userA with new tasks list
listOfTask(userA.tasks);
// Expected output in the console: SAME FORMA
// Not Started:
// - Task x
// - Task x
// In Progress:
// - Task x
// - Task x
// Done:
// - Task x
// - Task x
Docs
As we go through our programming careers, we'll be working a lot with text. To facilitate this, we'll want to get familiar with some common string methods and properties.
Reference: MDN String
length
: the property of a String object contains the length of the stringvar s = "Life, the universe and everything. Answer:";
console.log(`${s} ${s.length}`);
// expected output: "Life, the universe and everything. Answer: 42"
return "cat"[1]; // returns "a"
includes()
method determines whether one string may be found within another string, returning true or false as appropriate.var sentence = "The quick brown fox jumps over the lazy dog.";
var word = "fox";
console.log(sentence.includes(word)); // expected output: true
startsWith()
, endsWith()
method determines whether a string starts/ends with the characters of a specified string, returning true or false as appropriate.var str1 = "Saturday night plans";
console.log(str1.startsWith("Sat")); // expected output: true
var str2 = "Is this a question";
console.log(str2.endsWith("?")); // expected output: false
slice(start [, end])
: Extracts a section of a string and returns a new string.var str = "The quick brown fox jumps over the lazy dog.";
console.log(str.slice(31));
// expected output: "the lazy dog."
console.log(str.slice(4, 19));
// expected output: "quick brown fox"
console.log(str.slice(-4));
// expected output: "dog."
console.log(str.slice(-9, -5));
// expected output: "lazy"
split([sep [, limit] ])
: Returns an array of strings populated by splitting the calling string at occurrences of the substring sep.var str = "The quick brown fox jumps over the lazy dog.";
var words = str.split(" ");
console.log(words);
//expected output: ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
console.log(words[3]);
// expected output: "fox"
toLowerCase()
/toUpperCase()
Returns the calling string value converted to lowercase/uppercase.var str = "The Quick Brown Fox Jumps Over The Lazy Dog.";
console.log(str.toLowerCase());
// expected output: "the quick brown fox jumps over the lazy dog."
console.log(str.toUpperCase());
// expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."
trim()
method removes whitespace from both ends of a string.const greeting = " Hello world! ";
console.log(greeting);
// expected output: " Hello world! ";
console.log(greeting.trim());
// expected output: "Hello world!";
Assignment
var variousThings = [
true, true, true, false,
true, true, 1, true,
true, false, true, false,
true, "hello", false, true,
true, true, true, true,
false, false, "world", true
];
findFirstString(variousThings);
// => 'hello'
normalizeEmails(emails)
that takes an array of emails (string). This function should return an array. All emails in the returned array should be all lowercase, and all whitespaces at both ends of each email should be removed.var emails = [" PETER@gmail.com", "Mia1024@gmail.COM ", " Dorian@gmail.com "];
console.log(normalizeEmails(emails));
// ["peter@gmail.com", "mia1024@gmail.com", "dorian@gmail.com"]
splitNames(fullName)
that takes an full name and return an object that contains firstName
and lastName
as the key.console.log(splitNames("Peter Parker"));
// {firstName: "Peter", lastName: "Parker"}
getRandomString(length)
that takes a number as the length and generates an arbitrary string by picking characters randomly from A-Z, a-z, and 0-9.var characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
function getRandomString(length) {
// Your code here
}
console.log(getRandomString(5));
// example output: B5cgH
Github here