0% found this document useful (0 votes)
7 views46 pages

Getting Started With JS Part TWO

Uploaded by

AC Chandler
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views46 pages

Getting Started With JS Part TWO

Uploaded by

AC Chandler
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Getting Started with Javascript

Part TWO
HTML

CSS

Javascript

Front-end
By the end of this section, you should:
● Feel comfortable working with more Javascript array functions
● Feel comfortable working with Javascript objects
● Feel comfortable with Javascript variable and function scope
● Feel comfortable working with Javascript Timers
● Feel comfortable working with Javascript Date Object
More array methods (20 min)
1. find(): Returns the first element in the array that satisfies the provided testing
function. const array = [5, 12, 8, 130, 44]; const found = array.find(element
=> element > 10); console.log(found); // Output: 12

Without find(): You would need to loop through the array manually to find the
first element that meets the condition.
2. findIndex(): Returns the index of the first element in the array that satisfies the
provided testing function. Returns -1 if no elements satisfy the testing function.
const array = [5, 12, 8, 130, 44];
const index = array.findIndex(element => element > 10);
console.log(index); // Output: 1
● some() checks conditions
● Tests whether at least one element in the array passes the test implemented by
the provided function. It returns a Boolean value.
● const array = [1, 2, 3, 4];
● const hasEvenNumber = array.some(element => element % 2 === 0);
● console.log(hasEvenNumber); // true
● forEach() forEach(): Executes a provided function once for each array element.
It does not return anything. Iterates elements
● const array = [1, 2, 3, 4];
● array.forEach(element => console.log(element));
● // Output:// 1 // 2 // 3 // 4
● map(): Creates a new array populated with the results of calling a provided
function on every element in the calling array.
const array = [1, 2, 3, 4];
const doubledArray = array.map(element => element * 2);
console.log(doubledArray); // [2, 4, 6, 8]

sort(): Sorts the elements of an array in place and returns the sorted array. The
default sort order is ascending, built upon converting the elements into strings.
const array = [4, 2, 3, 1];
array.sort();
console.log(array); // [1, 2, 3, 4]

map(): Transforms elements.


sort(): Orders elements.
● filter(): Creates a new array with all elements that pass the test implemented
by the provided function.
● const array = [1, 2, 3, 4];
● const evenNumbers = array.filter(element => element % 2 === 0);
● console.log(evenNumbers); // [2, 4]
● some(): Tests condition.
● forEach(): Iterates elements.
● map(): Transforms array.
● sort(): Orders array.
● filter(): Filters elements.
Review: MDN array functions
JS objects are key/value pair data structures
const objectName = {
key1: value1,
key2: value2,
key3: value3
}
● Values can be anything: number, bool,
string, array, function, or another object
● To access the object value we use the
“dot” notation or the bracket notation:
○ .
objectName key1; // value1
○ objectName[“key1”]; // value1
Use the “dot” or bracket notation to manipulate
objects
ACCESSING MODIFYING

● song.name ? ● song.name = “Crooked


const song = { ○ “Dollar and a Dream III Smile”;
name: “Dollar and a Dream ● song[“genre”] ? ○ {name: “Crooked Smile”,
III”, ○ “Hip-Hop/Rap” artist: “J.Cole”,
artist: “J.Cole”,
● song[genre] ? releaseYear: 2011, genre:
releaseYear: 2011,
genre: “Hip-Hop/Rap” ○ Error: genre is not defined “Hip-Hop/Rap”}
}; ● song.type ? ● delete song.releaseYear
○ Undefined ○ {name: “Crooked Smile,
artist: “J.Cole”, genre: “Hip-
● Object.keys(song) ?
Hop/Rap”}
● Object.values(song) ?
You do: Access object items (20 min)
Open the access_object_items.html file and follow the instructions in the file.
Replace the // YOUR CODE GOES HERE comments with your code
You do: Modify object items (20 min)
Open the modify_object_items.html file and follow the instructions in the file.
Replace the // YOUR CODE GOES HERE comments with your code
Review: Modify object items
Code along: shallow & deep copy, …, destructure
Object with a function property (method)
const dog = { const rect = {
noise: “Woof!!!”, width: 4,
makeNoise: function(){ length: 3,
console.log(“Woof!!!”) area : function(){
} return 3 * 4;
} }
● dog.noise or dog[“noise”]? }
○ “Woof”
● rect.width or rect[“width”] ?
● dog.makeNoise() or dog[“makeNoise”] ○ 4
() ? ● rect.length or rect[“length”] ?
○ Console logs “Woof” ○ 3
● var myArea = rect.area() ?
○ myArea = 12
You do (15 min)
1. Create a cat object with a makeNoise method and a noise property with a
value of “Meou!”
a. The makeNoise method should console log “Meou!!”
b. Call the makeNoise method and make sure it console logs the expected string
c. Overwrite the makeNoise implementation and make it console log “Meow Meow!” instead
d. Call the makeNoise method and make sure it console logs the expected string

2. Create a cube object with a area method and an edge property with a value
of 3
a. Make the area method returns 3*3
b. Call the area method and use its return value in a console logs to make sure that i returned
the expected value
c. Add a volume method to the cube object that returns 3*3*3
d. Call the volume method and use its return value in a console logs to make sure that i
returned the expected value
Can you spot the inefficiency?
const dog = {
noise: “Woof!!!”, ● this keyword inside of function refers to the
makeNoise: function(){
console.log(“Woof!!!”)
caller of the function
} ○ In dog.makeNoise(), the dog object is the caller of
} the makeNoise method

○ this.noise refers to the noise property of the dog


const dog = { object
noise: “Woof!!!”,
makeNoise: function(){
console.log(this.noise)
}
}
More of this
const rect = {
width: 4,
● this keyword inside of function refers to
length: 3,
area: function(){ the caller of the function
return 3 * 4; ○ In rect.area(), the rect object is the caller of
}
the area method
}
○ this.width and this.length refer to the width
and length properties of the rect object
const rect = {
width: 4,
length: 3,
area: function(){
return this.width * this.length;
}
}
You do: Creating similar objects
● Pick your 5 favorite countries and create an object for each one
● Each object should have these properties:
○ name

○ capital

○ snows (bool)

○ population

○ getCountryInfo (method that console logs all the properties of this country)

● After each country call its getCountryInfo method


Demo: Constructors
const dog = { function Animal(someNoise){
noise: “woof”, this.noise = someNoise;
makeNoise: function(){ this.makeNoise = function(){

console.log(this.noise); console.log(this.noise);
} }
} }
dog.makeNoise(); // “woof”
const cat = { var dog = new Animal(“woof”);
noise: “meow!”, dog.makeNoise(); // “woof”
makeNoise: function(){
var cat = new Animal(“meow”);
console.log(this.noise); cat.makeNoise(); // “meow”
}
}
Recap: JS objects are key/value pair data structures
const objectName = {
key1: value1,
key2: value2,
key3: value3
}
● Values can be anything: number, bool,
string, array, function, or another object
● To access the object value we use the
“dot” notation or the bracket notation:
○ .
objectName key1; // value1
○ objectName[“key1”]; // value1
Recap: “dot” or bracket notation

ACCESSING MODIFYING

● song.name ? ● song.name = “Crooked


var song = { ○ “Dollar and a Dream III Smile”;
name: “Dollar and a Dream ● song[“genre”] ? ○ {name: “Crooked Smile”,
III”, ○ “Hip-Hop/Rap” artist: “J.Cole”,
artist: “J.Cole”,
● song[genre] ? releaseYear: 2011, genre:
releaseYear: 2011,
genre: “Hip-Hop/Rap” ○ Error: genre is not defined “Hip-Hop/Rap”}
}; ● song.type ? ● delete song.releaseYear
○ Undefined ○ {name: “Crooked Smile,
artist: “J.Cole”, genre: “Hip-
● Object.keys(song) ?
Hop/Rap”}
● Object.values(song) ?
Recap: object functions are called methods

const dog = { ● this keyword inside of function refers to


noise: “Woof!!!”,
makeNoise: function(){
the caller of the function
console.log(this.noise) ○ In dog.makeNoise(), the dog object is the
} caller of the makeNoise method
}
○ this.noise refers to the noise property of the
dog object
Scope is where a variable is visible/accessible
// variables declared outside all functions are in the global Javascript document (.js
scope file)

let name = “Nelly”; // can be accessed and altered from other scopes

// variables declared inside a function are in the local scope of that function Func1
let age = 29; // can only be accessed and altered from this function and its
children functions (lexical scope)
name = “Denzel”; // name is in global scope, so it is accessible here

// variables declared inside a function are in the local scope of that


Func2
function
let gender = “male”; // can only be accessed and altered from this
function and its children functions (lexical scope)
age = 64; // age is in parent scope, so it is accessible here (lexical scope)
name = “Washington”; // name is in global scope, so it is accessible here
Discuss with neighbor to answer following questions

1 let name = “Nelly”; Javascript document (.js file)


● If Func1 calls Func2, which
line(s) throw error after line 9
2 let age = 29; Func1 is executed?
3 name = “Denzel”; ○ 7: gender is local to Func2 and
not accessible to Func1
4 let gender = “male”; Func2 ○ 8: age is local to Func1 and not
5 age = 64; accessible to global scope
6 name = “Kerry Washington”; ● What is the value of each
7 gender = “female”; variable after line 9 is
executed?
8 age = 42; ○ name: “Kerry Washington”
9 Func1(); ○ age: 64
○ gender: “male”
Peer Discussion: More scopes (5 min)
● Demo block scope (let & const)
Recap: Scope is where a variable is
visible/accessible
● global scope: area outside all functions
● local scope: area inside of a function
● lexical scope: children scope have access to variables defined in the parent
scope
● block scope: area inside if/else, switch, for, or while loops
● let declares variables that can’t be re-declared
● const declares variables whose values can’t be changed
○ In block scope, variables declared with let and const are only accessible in that block
You do: setTimeout research (15 min)
● With a partner and figure out what setTimeout is and how it is used
● Make sure to play with it in your console or visual studio code
● Be ready to share your code with the class
Review: setTimeout
1 var userName = prompt(“What’s your name?”); Number of milliseconds to wait
before calling the function in first
argument
2 setTimeout( greet(userName) , 15 * 1000 );

3 function greet(user){

4 alert(`Hello ${user}`);
The function to run ONE TIME
5} after the milliseconds in the
second argument have passed
You do: Practice with setTimeout (10 min)
● Open js_timers_set_timeout.html and follow instructions in the file
Review: js_timers_set_timeout.html
You do: setInterval research (15 min)
● Find a partner and figure out what setInterval is and how it is used
● Make sure to play with it in your console or visual studio code
● Be ready to share your code with the class
Review: setInterval
1 var intervalId = setInterval( genRand , 15 * 1000 ); Number of milliseconds to wait
before calling the function in first
argument
2 function genRand(){

3 var rand = Math.floor(Math.random() * 101);

4 alert(`Random number between 0-100: ${rand}`);


The function to run EVERY TIME
5} after the milliseconds in the
second argument have passed
(unless stopped)
You do: Practice with setInterval (10 min)
● Open js_timers_set_interval.html and follow instructions in the file
You do: clearInterval research (10 min)
● Find a partner and figure out what clearInterval is and how it is used
● Make sure to play with it in your console or visual studio code
● Be ready to share your code with the class
Review: clearInterval
1 var intervalId = setInterval( genRand() , 15 * 1000 );

2 function genRand(){

3 if (confirm(“Click OK to get a random number”)){ The intervalId to clear in order to


stop the function in setInterval
4 var rand = Math.floor(Math.random() * from running every time the
101); frequency time has elapsed

5 alert(`Random number between 0-100: $


{rand}`);

6 } else {

7 clearInterval( intervalId );

8 }
You do: Practice with clearInterval (5 min)
● Open js_timers_clear_interval.html and follow instructions in the file
Demo: JS Date Object
You do: Play with the Date object in your console
Demo: Moment.js
You do: Play with the Moment.js in your console
In Class reading: JS Hoisting

● Go to this link and explore what hoisting (variable


& function hoisting) is
● Get ready to share your findings with the class
Advanced JS (optional with enough time)
● Advanced working with functions
● Prototypes & inheritance
● Classes in JS
Popcorn: What did you retain
● What do sort(), filter(), forEach(), map() do on an array?
● What is an object?
● How do you create an object in JS?
● What is “scope” in Javascript and what the 4 scopes in JS?
● What do let and const allow developers to do?
● What are the 3 ways of defining a Javascript function?
● How do you prevent bugs caused by variable hoisting?
Popcorn: What did you retain (cont)
● What does setTimeout() do?
● What does setInterval() do?
● What does clearInterval() do?
● What does the Date object allow us to do?
● What are some of the Date object methods you remember and what do they
do?
1-5 how comfortable do you feel:
● Working with more Javascript array functions?
● Working with Javascript objects?
● Working with Javascript variable and function scope?
● Working with Javascript Timers?
● Working with Javascript Date Object?

You might also like