Javascript Flashcards

(213 cards)

1
Q

How many data types are there in Javascript?

A

7.

Number, String, Boolean, Null, Undefined, Symbol Object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Operator

A

An operator is a character that performs a task in our code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

String Concatenation

A

Operators aren’t just for numbers! When a + operator is used on two strings, it appends the right string to the left string:

console.log(‘hi’ + ‘ya’); // Prints ‘hiya’
console.log(‘wo’ + ‘ah’); // Prints ‘woah’
console.log(‘I love to ‘ + ‘code.’)
// Prints ‘I love to code.’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

.length

A

Use the .length property to log the number of characters in the following string to the console:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Ways to call methods

A

We call, or use, these methods by appending an instance with:

a period (the dot operator)
the name of the method
opening and closing parentheses

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

.toUpperCase

A

console.log(‘hello’.toUpperCase()); // Prints ‘HELLO’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Math.random

A

Math.random generates a random number between 0 and 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Math.floor()

A

Then, Math.floor() rounds the number down to the nearest whole number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

console.log().

A

Data is printed, or logged, to the console, a panel that displays messages, with console.log()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

var

A

var, short for variable, is a JavaScript keyword that creates, or declares, a new variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

myName

A

myName is the variable’s name. Capitalizing in this way is a standard convention in JavaScript called camel casing. In camel casing you group words into one, the first word is lowercase, then every word that follows will have its first letter uppercased. (e.g. camelCaseEverything).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
const entree = 'Enchiladas';
console.log(entree);
A

Proper syntax for constant variable console.log

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

var favoriteFood = ‘pizza’;

A

Declaring a variable syntax

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Declaring a variable syntax

A

var favoriteFood = ‘pizza’;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

var numofSlices = 8;

A

Syntax for assigning a number to a var (no’ ‘)

Declare a variable named numOfSlices using the var keyword and assign to it the number 8.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Syntax for assigning a number to a var (no’ ‘ marks like text)
Declare a variable named numOfSlices using the var keyword and assign to it the number 8.

A

var numofSlices = 8;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q
var favoriteFood = 'pizza';
console.log(favoriteFood);
A

How to properly console log a variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How to properly console log a variable

A
var favoriteFood = 'pizza';
console.log(favoriteFood);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q
var favoriteFood = 'pizza';
console.log(favoriteFood);
var numOfSlices = 8;
console.log(numOfSlices);
A

Console logging words vs. Console logging a var w/ numerical value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Console logging words vs. Console logging a var w/ numerical value

A
var favoriteFood = 'pizza';
console.log(favoriteFood);
var numOfSlices = 8;
console.log(numOfSlices);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

assign a var a boolean value

A

let changeMe = true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

let changeMe = true

A

How to assign a var a bullian value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How to console.log a variable

A
let changeMe = false;
console.log('changeMe')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q
let changeMe = false;
console.log('changeMe')
A

How to console log a variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
let changeMe = true; changeMe = false;
How to console log boolean value of variable (no need for lets or var considering that there is no need to declare a var before making changes
26
How to console log boolean value of variable (no need for lets or var considering that there is no need to declare a var before making changes
let changeMe = true; changeMe = false;
27
const entree = 'Enchiladas';
Creating a constant variable syntax
28
Creating a constant variable syntaxconst entree = 'Enchiladas';
const entree = 'Enchiladas';
29
Proper syntax for constant variable console.log
``` const entree = 'Enchiladas'; console.log(entree); ```
30
``` const entree = 'Enchiladas'; console.log(entree); ```
Proper syntax for console logging constant
31
``` const entree = 'Enchiladas'; console.log(entree); entree = 'Tacos' ```
Causes error when attempting to change constant variable
32
Causes error when attempting to change constant variable
``` const entree = 'Enchiladas'; console.log(entree); entree = 'Tacos' ```
33
``` let w = 4; w += 1; ``` console.log(w); // Output: 5
+= Operator
34
+=Operator
``` let w = 4; w += 1; ``` console.log(w); // Output: 5
35
let experience = 18; experience += 16; console.log(experience); // Output: 34
Properly using += to change numeric value of a variable
36
Properly using += to change numeric value of a variable
let experience = 18; experience += 16; console.log(experience); // Output: 34
37
Increase Incriment
let a = 10; a++; console.log(a); // Output: 11
38
let a = 10; a++; console.log(a); // Output: 11
Increase Increment
39
let b = 20; b--; console.log(b); // Output: 19
Decrease in incriment
40
Decrease in increment
let b = 20; b--; console.log(b); // Output: 19
41
How to concatenate regular text with string value of variable
``` let favoriteAnimal = 'Phoenix'; console.log('My favorite animal: '+ favoriteAnimal); ```
42
``` let favoriteAnimal = 'Phoenix'; console.log('My favorite animal: '+ favoriteAnimal); ```
How to concatenate regular text with string value of variable
43
String Interpolation
In the ES6 version of JavaScript, we can insert, or interpolate, variables into strings using template literals. Check out the following example where a template literal is used to log strings together: ``` const myPet = 'armadillo'; console.log(`I own a pet ${myPet}.`); // Output: I own a pet armadillo. ```
44
In the ES6 version of JavaScript, we can insert, or interpolate, variables into strings using template literals. Check out the following example where a template literal is used to log strings together: ``` const myPet = 'armadillo'; console.log(`I own a pet ${myPet}.`); // Output: I own a pet armadillo. ```
String Interpolation
45
let newVariable = 'Playing around with typeof.'; console.log(typeof newVariable); // Result is string
typeof operator While writing code, it can be useful to keep track of the data types of the variables in your program. If you need to check the data type of a variable’s value, you can use the typeof operator. The typeof operator checks the value to its right and returns, or passes back, a string of the data type.
46
typeof operator While writing code, it can be useful to keep track of the data types of the variables in your program. If you need to check the data type of a variable’s value, you can use the typeof operator. The typeof operator checks the value to its right and returns, or passes back, a string of the data type.
let newVariable = 'Playing around with typeof.'; console.log(typeof newVariable); // Result is string
47
let newVariable = 'Playing around with typeof.'; console.log(typeof newVariable); newVariable = 1; console.log(typeof newVariable);
Result is String Number
48
Proper protocol for adding a set variable to an unset number
``` const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273; ```
49
``` const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273; ```
Proper protocol for adding a set variable to an unset number
50
``` const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273; // Declaring celsius and converting from kelvin const fahrenheit = celsius * (9 / 5)+32; // Declaring fahrenheit and converting from celsius6 ```
Thermometer Code
51
fahrenheit = Math.floor(fahrenheit);
Proper example of using Math.floor object
52
Proper example of using Math.floor
fahrenheit = Math.floor(fahrenheit); // Math floor (Math being the object .floor being the method)
53
String Interpolation syntax
``` const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273; // Declaring celsius and converting from kelvin let fahrenheit = celsius * (9 / 5) + 32; // Declaring fahrenheit and converting from celsius6 fahrenheit = Math.floor(fahrenheit); ``` // Math floor (Math being the object .floor being the method) console.log(`The temperature is ${fahrenheit} degrees Fahrenheit.`);
54
``` const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273; // Declaring celsius and converting from kelvin let fahrenheit = celsius * (9 / 5) + 32; // Declaring fahrenheit and converting from celsius6 fahrenheit = Math.floor(fahrenheit); ``` // Math floor (Math being the object .floor being the method) console.log(`The temperature is ${fahrenheit} degrees Fahrenheit.`);
String interpolation syntax
55
``` let myName = 'Leon David'.toLowerCase(); console.log(myName); ```
Proper use of built in method .toLowerCase
56
Proper use of built in method .toLowerCase
``` let myName = 'Leon David'.toLowerCase(); console.log(myName); ``` //Output leon david
57
What is the outcome of this statement? console.log('hi!'.length);
3 is Printed to the console
58
Proper if else syntax based on Boolean value
let sale = true; sale = false; if(sale) { console.log('Time to buy!');} else { console.log('Time to wait for a sale.'); }
59
let sale = true; sale = false; if(sale) { console.log('Time to buy!');} else { console.log('Time to wait for a sale.'); }
Proper if else syntax based on Boolean value
60
Comparison Operators
Comparison Operators When writing conditional statements, sometimes we need to use different types of operators to compare values. These operators are called comparison operators. Here is a list of some handy comparison operators and their syntax: ``` Less than: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Is equal to: === Is not equal to: !== ```
61
Comparison Operators When writing conditional statements, sometimes we need to use different types of operators to compare values. These operators are called comparison operators. Here is a list of some handy comparison operators and their syntax: ``` Less than: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Is equal to: === Is not equal to: !== ```
Comparison Operators
62
===
String comparison | Ex. 'apples' === 'oranges' // false
63
'apples' === 'oranges'
String comparison with false Boolean value
64
let hungerLevel = 7; ``` if(hungerLevel > 7) { console.log('Time to eat!'); } else { console.log('We can eat later!'); }; ```
If Else example (No need to specify inverse of if condition in this example)
65
Working with conditionals means that we will be using booleans, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators. We can use logical operators to add more sophisticated logic to our conditionals. There are three logical operators: the and operator (&&) the or operator (||) the not operator, otherwise known as the bang operator (!)
Logical Operator
66
Logical Operator
Working with conditionals means that we will be using booleans, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators. We can use logical operators to add more sophisticated logic to our conditionals. There are three logical operators: the and operator (&&) the or operator (||) the not operator, otherwise known as the bang operator (!)
67
Working with conditionals means that we will be using booleans, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators. We can use logical operators to add more sophisticated logic to our conditionals. There are three logical operators: the and operator (&&) the or operator (||) the not operator, otherwise known as the bang operator (!)
Logical Operator
68
&& Operator
When we use the && operator, we are checking that two things are true: ``` if (stopLight === 'green' && pedestrians === 0) { console.log('Go!'); } else { console.log('Stop'); } ```
69
When we use the && operator, we are checking that two things are true: ``` if (stopLight === 'green' && pedestrians === 0) { console.log('Go!'); } else { console.log('Stop'); } ```
&& Operator
70
``` let mood = 'sleepy'; let tirednessLevel = 6; ``` ``` if (mood === 'sleepy' && tirednessLevel > 8) { console.log('time to sleep'); } else { console.log('not bed time yet'); } ```
Proper && Syntax w/ a numerical value
71
Truthy Value
let myVariable = 'I Exist!'; if (myVariable) { console.log(myVariable) } else { console.log('The variable does not exist.') } The code block in the if statement will run because myVariable has a truthy value; even though the value of myVariable is not explicitly the value true, when used in a boolean or conditional context, it evaluates to true because it has been assigned a non-falsy value.
72
Falsy Values
So which values are falsy— or evaluate to false when checked as a condition? The list of falsy values includes: 0 Empty strings like "" or '' null which represent when there is no value at all undefined which represent when a declared variable lacks a value NaN, or Not a Number
73
Truthy Vs. Falsy Example
``` let wordCount = 0; wordCount = 5 ``` ``` if (wordCount) { console.log("Great! You've started your work!"); } else { console.log('Better get to work!'); } // Truthy ``` let favoritePhrase = ''; ``` if (favoritePhrase) { console.log("This string doesn't seem to be empty."); } else { console.log('This string is definitely empty.'); } //Falsy ```
74
``` let wordCount = 0; wordCount = 5 ``` ``` if (wordCount) { console.log("Great! You've started your work!"); } else { console.log('Better get to work!'); } // Truthy ``` let favoritePhrase = ''; ``` if (favoritePhrase) { console.log("This string doesn't seem to be empty."); } else { console.log('This string is definitely empty.'); } //Falsy ```
Truthy vs. Falsy example ``` let wordCount = 0; wordCount = 5 ``` ``` if (wordCount) { console.log("Great! You've started your work!"); } else { console.log('Better get to work!'); } // Truthy ``` let favoritePhrase = ''; ``` if (favoritePhrase) { console.log("This string doesn't seem to be empty."); } else { console.log('This string is definitely empty.'); } //Falsy ```
75
let tool = ''; ``` // Use short circuit evaluation to assign writingUtensil variable below: let writingUtensil = tool || 'pen' ``` console.log(`The ${writingUtensil} is mightier than the sword.`); // Output The pen is mightier than the sword.
Example of use of the || operator states the var then changes name of var and value. In this instance it turns writing utensil into a string
76
Ternary Operator Syntax In the spirit of using short-hand syntax, we can use a ternary operator to simplify an if...else statement. Take a look at the if...else statement example:
let isLocked = false; isLocked ? console.log('You will need a key to open the door.') : console.log('You will not need a key to open the door.');
77
let isLocked = false; isLocked ? console.log('You will need a key to open the door.') : console.log('You will not need a key to open the door.');
Ternary Operator In the spirit of using short-hand syntax, we can use a ternary operator to simplify an if...else statement. Take a look at the if...else statement example:
78
let isNightTime = true; if (isNightTime) { console.log('Turn on the lights!'); } else { console.log('Turn off the lights!'); Create using Ternary Operator
let isNightTime = true; isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');
79
let favoritePhrase = 'Love That!'; favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");
Ternary Operator with Comparison Operator
80
Ternary Operator with Comparison Operator
let favoritePhrase = 'Love That!'; favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");
81
Else ifs in appropriate Syntax
let season = 'summer'; if (season === 'spring') { console.log('It\'s spring! The trees are budding!'); } ``` else if (season === 'winter') { console.log('It\'s winter! Everything is covered in snow.'); ``` } ``` else if (season === 'fall') { console.log('It\'s fall! Leaves are falling!'); } ``` ``` else if (season === 'summer') { console.log('It\'s sunny and warm because it\'s summer!'); } ``` else { console.log('Invalid season.'); }
82
let season = 'summer'; if (season === 'spring') { console.log('It\'s spring! The trees are budding!'); } ``` else if (season === 'winter') { console.log('It\'s winter! Everything is covered in snow.'); ``` } ``` else if (season === 'fall') { console.log('It\'s fall! Leaves are falling!'); } ``` ``` else if (season === 'summer') { console.log('It\'s sunny and warm because it\'s summer!'); } ``` else { console.log('Invalid season.'); }
Else if in appropriate Syntax
83
The switch keyword
else if statements are a great tool if we need to check multiple conditions. In programming, we often find ourselves needing to check multiple values and handling each of them differently. For example:
84
else if statements are a great tool if we need to check multiple conditions. In programming, we often find ourselves needing to check multiple values and handling each of them differently. For example:
The switch keyboard
85
Switch Keyword single appropriate syntax
let athleteFinalPosition = 'first place'; switch(athleteFinalPosition){ case 'first place': console.log('You get the gold medal!');
86
let athleteFinalPosition = 'first place'; switch(athleteFinalPosition){ case 'first place': console.log('You get the gold medal!');
Switch Keyword single appropriate syntax
87
let athleteFinalPosition = 'first place'; ``` switch(athleteFinalPosition){ case 'first place': console.log('You get the gold medal!'); break; case 'second place': console.log('You get the silver medal!'); break; case 'third place': console.log('You get the bronze medal!'); break; default: console.log('No medal awarded.'); break; } ```
Switch appropriate syntax multiple instances
88
Switch keyword appropriate
let athleteFinalPosition = 'first place'; ``` switch(athleteFinalPosition){ case 'first place': console.log('You get the gold medal!'); break; case 'second place': console.log('You get the silver medal!'); break; case 'third place': console.log('You get the bronze medal!'); break; default: console.log('No medal awarded.'); break; } ```
89
userName = '' userName ? console.log(`Hello, ${userName}!`) : console.log('Hello!');
Appropriate Syntax Ternary expression combined with interpolation and a falsy variable //Output Hello!
90
Appropriate Syntax Ternary expression combined with interpolation and a falsy variable //Output Hello!
userName = '' userName ? console.log(`Hello, ${userName}!`) : console.log('Hello!');
91
Magic 8 ball code with lots of proper syntax
userName = '' userName ? console.log(`Hello, ${userName}!`) : console.log('Hello!'); console. log('Ask of your hearts desire') console. log('(Enter your question here)') userQuestion = '' console.log(userQuestion); ``` randomNumber = Math.floor(Math.random()*8) // console.log(randomNumber) eightBall= randomNumber; ``` ``` switch(eightBall){ case 0: console.log('It is certain'); break; case 1: console.log('It is decidedly so'); break; case 2: console.log('Reply hazy try again'); break; case 3: console.log('Cannot predict now'); break; case 4: console.log('Do not count on it'); break; case 5: console.log('My sources say no'); break; case 6: console.log('Outlook not so good'); break; case 7: console.log('Signs point to yes'); break; ``` default: console.log('The answer is in the clouds, Try again'); break; }
92
raceNumber = Math.floor(Math.random() * 1000); earlyRegistration = true; runnersAge = 22; console.log(raceNumber, earlyRegistration, runnersAge);
Can console log multiple inputs //Output 669 true 22
93
Runners registration program with plenty of examples of a appropriate syntax with if, else, else if and strict comparison equality operator
``` raceNumber = Math.floor(Math.random() * 1000); earlyRegistration = true; runnersAge = 17; ``` if (earlyRegistration === true && runnersAge > 18) { raceNumber += 1000 } if (earlyRegistration === true && runnersAge > 18 && runnersAge === 18) { console.log(`You will race at 9:30 ${raceNumber}.`); } else if (earlyRegistration === false && runnersAge > 18) { console.log('Late adults run at 11:00am'); } else if (runnersAge < 18) { console.log('Youth registrants run at 12:30 pm (regardless of registration'); } else console.log('Please got to registration desk');
94
``` function getReminder() { console.log('Water the plants.'); } function greetInSpanish() {console.log('Buenas Tardes.'); } ``` getReminder() greetInSpanish()
Creating function then calling function
95
Creating function then calling function syntax
``` function getReminder() { console.log('Water the plants.'); } function greetInSpanish() {console.log('Buenas Tardes.'); } ``` getReminder() greetInSpanish()
96
function sayThanks() { console.log('Thank you for your purchase! We appreciate your business') } sayThanks() sayThanks() sayThanks()
The ability to call a function multiple times
97
The ability to call a function multiple times
function sayThanks() { console.log('Thank you for your purchase! We appreciate your business') } sayThanks() sayThanks() sayThanks()
98
Calling a function then adding parameters to it
function sayThanks(name) { console.log('Thank you for your purchase '+ name + '! We appreciate your business.'); } sayThanks('Cole') //Output Thank you for your purchase Cole! We appreciate your business.
99
function sayThanks(name) { console.log('Thank you for your purchase '+ name + '! We appreciate your business.'); } sayThanks('Cole') //Output Thank you for your purchase Cole! We appreciate your business.
Setting a function with a preset parameter then placing an aspect in it
100
``` function makeShoppingList(item1, item2, item3){ console.log(`Remember to buy ${item1}`); console.log(`Remember to buy ${item2}`); console.log(`Remember to buy ${item3}`); } makeShoppingList('milk', 'bread', 'eggs') ```
Call to function then assigning parameters Output: remember to buy milk remember to buy bread remember to buy eggs
101
Bring function to console
``` function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'eggs'){ console.log(`Remember to buy ${item1}`); console.log(`Remember to buy ${item2}`); console.log(`Remember to buy ${item3}`); } ```
102
``` function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'eggs'){ console.log(`Remember to buy ${item1}`); console.log(`Remember to buy ${item2}`); console.log(`Remember to buy ${item3}`); } ```
Bring function to console
103
``` function monitorCount(rows,columns){ return rows * columns; } ``` const numOfMonitors = monitorCount(5,4); console.log(numOfMonitors);
Creating function, calling it's returns then utilizing function in the creation of a new constant variable (Good Syntax)
104
Creating function, calling it's returns then utilizing function in the creation of a new constant variable (Good Syntax)
``` function monitorCount(rows,columns){ return rows * columns; } ``` const numOfMonitors = monitorCount(5,4); console.log(numOfMonitors);
105
``` function monitorCount(rows, columns) { return rows * columns; } ``` ``` function costOfMonitors(rows, columns) { return monitorCount(rows, columns) * 200; } ``` const totalCost = costOfMonitors(5, 4); console.log(totalCost);
Good function syntax
106
``` const plantNeedsWater= function(day){ if(day === 'Wednesday'){ return true; } else{ return false; } }; plantNeedsWater('Tuesday') console.log(plantNeedsWater('Tuesday')); ```
Function inside a constant with a false boolean value. Good syntax
107
Function inside a constant with a false boolean value. Good syntax
``` const plantNeedsWater= function(day){ if(day === 'Wednesday'){ return true; } else{ return false; } }; plantNeedsWater('Tuesday') console.log(plantNeedsWater('Tuesday')); ```
108
Arrow Functions
ES6 introduced arrow function syntax, a shorter way to write functions by using the special “fat arrow” () => notation. Arrow functions remove the need to type out the keyword function every time you need to create a function. Instead, you first include the parameters inside the ( ) and then add an arrow => that points to the function body surrounded in { } like this:
109
``` const plantNeedsWater = (day) => { if (day === 'Wednesday') { return true; } else { return false; } }; ```
Function created w/ arrow syntax
110
``` const city ='New York City' function logCitySkyline() { let skyscraper = 'Empire State Building' return 'The stars over the ' + skyscraper + ' in ' +city; }; ``` console.log(logCitySkyline());
Function created w/ arrow syntax
111
``` const satellite = 'The Moon'; const galaxy = 'The Milky Way'; const stars = 'North Star'; ``` ``` const callMyNightSky = () => { return 'Night Sky: ' +satellite+ ',' +stars+ ', and ' + galaxy; }; console.log(callMyNightSky()); ```
Three variables declared then 4th constant is turned into a function by arrow function
112
``` const logVisibleLightWaves = () => { const lightWaves = 'Moonlight'; console.log(lightWaves); }; ``` logVisibleLightWaves(); // console.log(lightWaves);
Function creation through arrow
113
Function creation through arrow
``` const logVisibleLightWaves = () => { const lightWaves = 'Moonlight'; console.log(lightWaves); }; ``` logVisibleLightWaves(); // console.log(lightWaves);
114
Array Literal
An array literal creates an array by wrapping items in square brackets []. Remember from the previous exercise, arrays can store any data type — we can have an array that holds all the same data types or an array that holds different data types.
115
creates an array by wrapping items in square brackets []. Remember from the previous exercise, arrays can store any data type — we can have an array that holds all the same data types or an array that holds different data types.
Array Literal
116
const hobbies = [ 'Stuff', 'Hello World!', 'Butt'];
Constant with 3 strings in an array good syntax
117
Constant with 3 strings inside of an array good syntax
const hobbies = [ 'Stuff', 'Hello World!', 'Butt'];
118
Creating new var from array good syntax
const famousSayings = ['Fortune favors the brave.', 'A joke is a very serious thing.', 'Where there is love there is life.']; const listItem = famousSayings[0];
119
const famousSayings = ['Fortune favors the brave.', 'A joke is a very serious thing.', 'Where there is love there is life.']; const listItem = famousSayings[0];
Creating new variable out of an array, good syntax
120
const famousSayings = ['Fortune favors the brave.', 'A joke is a very serious thing.', 'Where there is love there is life.']; console.log(famousSayings[2]); //Output Where there is love there is live
Console logging the third item from an array good syntax
121
Console logging the third item in an array good syntax
const famousSayings = ['Fortune favors the brave.', 'A joke is a very serious thing.', 'Where there is love there is life.']; console.log(famousSayings[2]); //Output Where there is love there is live
122
Getting an undefined response from an array due to nothing being in the value place requested
const famousSayings = ['Fortune favors the brave.', 'A joke is a very serious thing.', 'Where there is love there is life.']; const listItem = famousSayings[0]; console.log(famousSayings[2]); console.log(famousSayings[3]); Output// Undefined
123
let seasons = ['Winter', 'Spring', 'Summer', 'Fall']; ``` seasons[3] = 'Autumn'; console.log(seasons); //Output: ['Winter', 'Spring', 'Summer', 'Autumn'] ```
Changing values in an array good syntax
124
Changing values in an array good syntax
let seasons = ['Winter', 'Spring', 'Summer', 'Fall']; ``` seasons[3] = 'Autumn'; console.log(seasons); //Output: ['Winter', 'Spring', 'Summer', 'Autumn'] ```
125
const newYearsResolutions = ['Keep a journal', 'Take a falconry class']; ``` console.log(newYearsResolutions.length); // Output: 2 ```
. Length as it applies to arrays, good syntax
126
const itemTracker = ['item 0', 'item 1', 'item 2']; itemTracker.push('item 3', 'item 4'); ``` console.log(itemTracker); // Output: ['item 0', 'item 1', 'item 2', 'item 3', 'item 4']; ```
.Push function good syntax
127
const newItemTracker = ['item 0', 'item 1', 'item 2']; const removed = newItemTracker.pop(); console.log(newItemTracker); // Output: [ 'item 0', 'item 1' ] console.log(removed); // Output: item 2
Pop method removing an item from an array
128
const chores = ['wash dishes', 'do laundry', 'take out trash', 'cook dinner', 'mop floor']; chores. pop(); console. log(chores);
.pop function with proper syntax and console log removes last portion of array //Output 0: "wash dishes" 1: "do laundry" 2: "take out trash" 3: "cook dinner" length: 4
129
.Shift and .Unshift good syntax
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains']; groceryList.shift(); console.log(groceryList); groceryList.unshift('popcorn'); console.log(groceryList); //Output 2 Arrays (6)  ['bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'] main. js:9 (7) ['popcorn', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains']
130
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains']; groceryList.shift(); console.log(groceryList); groceryList.unshift('popcorn'); console.log(groceryList);
.shift and .unshift //Output two arrays (6)  ['bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'] main. js:9 (7) ['popcorn', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains']
131
.shift .unshift and .slice usage good syntax 'plantains' ] [ 'bananas', 'coffee beans', 'brown rice' ]
.shift .unshift and .slice usage good syntax const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains']; groceryList.shift(); // console.log(groceryList); groceryList.unshift('popcorn'); console. log(groceryList); console. log(groceryList.slice(1, 4)); //Output ``` [ 'popcorn', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains' ] [ 'bananas', 'coffee beans', 'brown rice' ] ```
132
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains']; groceryList.shift(); // console.log(groceryList); groceryList.unshift('popcorn'); console. log(groceryList); console. log(groceryList.slice(1, 4)); console. log(groceryList); const pastaIndex = groceryList.indexOf('pasta') console.log(pastaIndex);
Shift, unshift, slice and index of in good syntax
133
Nested Array good syntax
const nestedArr = [[1], [2, 3]]; console. log(nestedArr[1]); // Output: [2, 3] console. log(nestedArr[1][0]); // Output: 2
134
Var with nested array good syntax
var numberClusters =[[1, 2] , [3, 4] , [5, 6]];
135
var numberClusters =[[1, 2] , [3, 4] , [5, 6]];
Var with nested array good syntax
136
const numberClusters =[[1, 2], [3, 4], [5, 6]]; const target = numberClusters [2][1]; console.log(target); //Output 6
Nested arrays are called by their nest and then their placement in the nest but remember that the first array is always going to be 0 so is the first array placement so two refers to the third placement and one refers to the second placement
137
// Write your code below const vacationSpots = ['Colombia' , 'Seoul', 'New Orleans']; console. log(vacationSpots[0]); console. log(vacationSpots[1]); console. log(vacationSpots[2]);
Console logging all aspects of an array w/out a loop | Output// Colombia Seoul New Orleans
138
Console logging all aspects of an array w/out a loop | Output// Colombia Seoul New Orleans
// Write your code below const vacationSpots = ['Colombia' , 'Seoul', 'New Orleans']; console. log(vacationSpots[0]); console. log(vacationSpots[1]); console. log(vacationSpots[2]);
139
``` // Write your code below for (let counter = 5; counter < 11; counter++) { console.log(counter); } ```
``` For loop up to 10 good syntax Output 5 6 7 8 9 10 11 ```
140
``` // The loop below loops from 0 to 3. Edit it to loop backwards from 3 to 0 for (let counter = 3; counter >= 0; counter--){ console.log(counter); } ```
Descend for loop good syntax
141
Descending for loop good syntax
``` // The loop below loops from 0 to 3. Edit it to loop backwards from 3 to 0 for (let counter = 3; counter >= 0; counter--){ console.log(counter); } ```
142
Using a for loop to run through an array
const vacationSpots = ['Bali', 'Paris', 'Tulum']; ``` // Write your code below for (let i = 0; i < vacationSpots.length; i++ ){ console.log('I would love to visit ' + vacationSpots[i]); } ```
143
const vacationSpots = ['Bali', 'Paris', 'Tulum']; ``` // Write your code below for (let i = 0; i < vacationSpots.length; i++ ){ console.log('I would love to visit ' + vacationSpots[i]); } ```
Using a for loop for running through an array
144
// Write your code below let bobsFollowers = ['Joe', 'Marta', 'Sam', 'Erin']; let tinasFollowers = ['Sam', 'Marta', 'Elle']; let mutualFollowers = []; for (let i = 0; i < bobsFollowers.length; i++) { for (let j = 0; j < tinasFollowers.length; j++) { if (bobsFollowers[i] === tinasFollowers[j]) { mutualFollowers.push(bobsFollowers[i]); } } }; console.log (bobsFollowers) console.log (tinasFollowers) console.log (mutualFollowers)
Sets two arrays then uses two for loops to go through the arrays then after that then creates mutual followers context with loops. //Output [ 'Joe', 'Marta', 'Sam', 'Erin' ] [ 'Sam', 'Marta', 'Elle' ] [ 'Marta', 'Sam' ]
145
While Loop
``` // A for loop that prints 1, 2, and 3 for (let counterOne = 1; counterOne < 4; counterOne++){ console.log(counterOne); } ``` ``` // A while loop that prints 1, 2, and 3 let counterTwo = 1; while (counterTwo < 4) { console.log(counterTwo); counterTwo++; } ```
146
``` // A for loop that prints 1, 2, and 3 for (let counterOne = 1; counterOne < 4; counterOne++){ console.log(counterOne); } ``` ``` // A while loop that prints 1, 2, and 3 let counterTwo = 1; while (counterTwo < 4) { console.log(counterTwo); counterTwo++; } ```
While Loop
147
A card array that draws cards until a spade is drawn using a while loop, solid syntax
const cards = ['diamond', 'spade', 'heart', 'club']; // Write your code below let currentCard; while (currentCard != 'spade') { currentCard = cards[Math.floor(Math.random() * 4)]; console.log(currentCard); }
148
const cards = ['diamond', 'spade', 'heart', 'club']; // Write your code below let currentCard; while (currentCard != 'spade') { currentCard = cards[Math.floor(Math.random() * 4)]; console.log(currentCard); }
A card array that draws cards until a spade is drawn using a while loop, solid syntax
149
Do...While Statements
In some cases, you want a piece of code to run at least once and then loop based on a specific condition after its initial run. This is where the do...while statement comes in. A do...while statement says to do a task once and then keep doing it until a specified condition is no longer met. The syntax for a do...while statement looks like this: ``` let countString = ''; let i = 0; ``` do { countString = countString + i; i++; } while (i < 5); console.log(countString);
150
In some cases, you want a piece of code to run at least once and then loop based on a specific condition after its initial run. This is where the do...while statement comes in. A do...while statement says to do a task once and then keep doing it until a specified condition is no longer met. The syntax for a do...while statement looks like this: ``` let countString = ''; let i = 0; ``` do { countString = countString + i; i++; } while (i < 5); console.log(countString);
Do... While Statements
151
``` // Write your code below let cupsOfSugarNeeded = 5; let cupsAdded = 0; ``` do { cupsAdded++ console.log(cupsAdded + 'cup was added') } while (cupsAdded
Do while example good syntax
152
Rapper array using for loop
const rapperArray = ["Lil' Kim", "Jay-Z", "Notorious B.I.G.", "Tupac"]; ``` // Write your code below for (let i = 0; i < rapperArray.length; i++ ){ console.log(rapperArray[i]); } ```
153
const rapperArray = ["Lil' Kim", "Jay-Z", "Notorious B.I.G.", "Tupac"]; ``` // Write your code below for (let i = 0; i < rapperArray.length; i++){ console.log(rapperArray[i]); if (rapperArray[i] === 'Notorious B.I.G.'){ break; } } ``` console.log("And if you don't know, now you know.");
Rapper loop with break and quote good syntax
154
The .forEach() Method
The first iteration method that we’re going to learn is .forEach(). Aptly named, .forEach() will execute the same code for each element of an array.`
155
The first iteration method that we’re going to learn is .forEach(). Aptly named, .forEach() will execute the same code for each element of an array.
.forEach()Method
156
.forEach example good syntax
const fruits = ['mango', 'papaya', 'pineapple', 'apple']; ``` // Iterate over fruits below fruits.forEach(fruit => console.log(`I want to eat a ${fruit}.`)) ```
157
const fruits = ['mango', 'papaya', 'pineapple', 'apple']; ``` // Iterate over fruits below fruits.forEach(fruit => console.log(`I want to eat a ${fruit}.`)) ```
for each example good syntax
158
The .map() Method
The second iterator we’re going to cover is .map(). When .map() is called on an array, it takes an argument of a callback function and returns a new array! Take a look at an example of calling .map():
159
The second iterator we’re going to cover is .map(). When .map() is called on an array, it takes an argument of a callback function and returns a new array! Take a look at an example of calling .map():
The .map() Method
160
The .filter() Method
Another useful iterator method is .filter(). Like .map(), .filter() returns a new array. However, .filter() returns an array of elements after filtering out certain elements from the original array. The callback function for the .filter() method should return true or false depending on the element that is passed to it. The elements that cause the callback function to return true are added to the new array. Take a look at the following example:
161
Another useful iterator method is .filter(). Like .map(), .filter() returns a new array. However, .filter() returns an array of elements after filtering out certain elements from the original array. The callback function for the .filter() method should return true or false depending on the element that is passed to it. The elements that cause the callback function to return true are added to the new array. Take a look at the following example:
The filter method
162
. Filter for both numbers and letters good syntax
const randomNumbers = [375, 200, 3.14, 7, 13, 852]; ``` // Call .filter() on randomNumbers below const smallNumbers = randomNumbers.filter(num => { return num < 250; }) ``` const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene']; // Call .filter() on favoriteWords below ``` const longFavoriteWords = favoriteWords.filter(word => { return word.length > 7; }) ```
163
const randomNumbers = [375, 200, 3.14, 7, 13, 852]; ``` // Call .filter() on randomNumbers below const smallNumbers = randomNumbers.filter(num => { return num < 250; }) ``` const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene']; // Call .filter() on favoriteWords below ``` const longFavoriteWords = favoriteWords.filter(word => { return word.length > 7; }) ```
.Filters for both letters and numbers good syntax
164
The .findIndex() Method
We sometimes want to find the location of an element in an array. That’s where the .findIndex() method comes in! Calling .findIndex() on an array will return the index of the first element that evaluates to true in the callback function.
165
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant']; ``` const foundAnimal = animals.findIndex (animal => { return animal === 'elephant'; }); ``` console.log(foundAnimal);
Find index with function being created in side of function, good syntax
166
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant']; ``` const foundAnimal = animals.findIndex(animal => { return animal === 'elephant'; }); ``` ``` const startsWithS = animals.findIndex(animal => { return animal[0] === 's' ? true : false; }); ``` console.log(startsWithS);
Finding index elephant, and of animals names that start with s, good syntax
167
The .reduce() Method
Another widely used iteration method is .reduce(). The .reduce() method returns a single value after iterating through the elements of an array, thereby reducing the array. Take a look at the example below:
168
const newNumbers = [1, 3, 5, 7]; const newSum = newNumbers.reduce((accumulator, currentValue) => { console.log('The value of accumulator: ', accumulator); console.log('The value of currentValue: ', currentValue); return accumulator + currentValue; }, 10); console.log(newSum);
``` The value of accumulator: 10 The value of currentValue: 1 The value of accumulator: 11 The value of currentValue: 3 The value of accumulator: 14 The value of currentValue: 5 The value of accumulator: 19 The value of currentValue: 7 26 ```
169
``` The value of accumulator: 10 The value of currentValue: 1 The value of accumulator: 11 The value of currentValue: 3 The value of accumulator: 14 The value of currentValue: 5 The value of accumulator: 19 The value of currentValue: 7 26 ```
const newNumbers = [1, 3, 5, 7]; const newSum = newNumbers.reduce((accumulator, currentValue) => { console.log('The value of accumulator: ', accumulator); console.log('The value of currentValue: ', currentValue); return accumulator + currentValue; }, 10); console.log(newSum);
170
Array.prototype.some()
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
171
const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise']; // Something is missing in the method call below console.log(words.some(word => { return word.length < 6; })); ``` // Use filter to create a new array const interestingWords = words.filter((word) => {return word.length > 5}); ``` // Make sure to uncomment the code below and fix the incorrect code before running it console.log(interestingWords.every((word) => {return word.length > 5}));
Utilizing different methods inside of constants, creating arrays and //Output true, true
172
const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama']; const nums = [1, 50, 75, 200, 350, 525, 1000]; ``` // Choose a method that will return undefined cities.forEach(city => console.log('Have you visited ' + city + '?')); ``` ``` // Choose a method that will return a new array const longCities = cities.filter(city => city.length > 7); ``` ``` // Choose a method that will return a single value const word = cities.reduce((acc, currVal) => { return acc + currVal[0] }, "C"); ``` console.log(word) ``` // Choose a method that will return a new array const smallerNums = nums.map(num => num - 5); ``` ``` // Choose a method that will return a boolean value nums.some(num => num < 0); ```
Perfect example of several methods
173
Perfect example of several methods
const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama']; const nums = [1, 50, 75, 200, 350, 525, 1000]; ``` // Choose a method that will return undefined cities.forEach(city => console.log('Have you visited ' + city + '?')); ``` ``` // Choose a method that will return a new array const longCities = cities.filter(city => city.length > 7); ``` ``` // Choose a method that will return a single value const word = cities.reduce((acc, currVal) => { return acc + currVal[0] }, "C"); ``` console.log(word) ``` // Choose a method that will return a new array const smallerNums = nums.map(num => num - 5); ``` ``` // Choose a method that will return a boolean value nums.some(num => num < 0); ```
174
const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama']; const nums = [1, 50, 75, 200, 350, 525, 1000]; ``` // Choose a method that will return undefined cities.forEach(city => console.log('Have you visited ' + city + '?')); ``` ``` // Choose a method that will return a new array const longCities = cities.filter(city => city.length > 7); ``` ``` // Choose a method that will return a single value const word = cities.reduce((acc, currVal) => { return acc + currVal[0] }, "C"); ``` console.log(word) ``` // Choose a method that will return a new array const smallerNums = nums.map(num => num - 5); ``` ``` // Choose a method that will return a boolean value nums.some(num => num < 0); ```
``` Have you visited Orlando? Have you visited Dubai? Have you visited Edinburgh? Have you visited Chennai? Have you visited Accra? Have you visited Denver? Have you visited Eskisehir? Have you visited Medellin? Have you visited Yokohama? CODECADEMY ```
175
ITERATORS Review Awesome job on clearing the iterators lesson! You have learned a number of useful methods in this lesson as well as how to use the JavaScript documentation from the Mozilla Developer Network to discover and understand additional methods. Let’s review! .forEach() is used to execute the same code on every element in an array but does not change the array and returns undefined. .map() executes the same code on every element in an array and returns a new array with the updated elements. .filter() checks every element in an array to see if it meets certain criteria and returns a new array with the elements that return truthy for the criteria. .findIndex() returns the index of the first element of an array that satisfies a condition in the callback function. It returns -1 if none of the elements in the array satisfies the condition. .reduce() iterates through an array and takes the values of the elements and returns a single value. All iterator methods take a callback function, which can be a pre-defined function, a function expression, or an arrow function. You can visit the Mozilla Developer Network to learn more about iterator methods (and all other parts of JavaScript!).
Solid review of several methods
176
Object with two properties good syntax
``` let fasterShip = { 'Fuel Type': 'Turbo Fuel', color: 'silver' }; ```
177
``` let fasterShip = { 'Fuel Type': 'Turbo Fuel', color: 'silver' }; ```
Object with two properties good sytnax
178
Accessing Properties
There are two ways we can access an object’s property. Let’s explore the first way— dot notation, .. You’ve used dot notation to access the properties and methods of built-in objects and data instances: 'hello'.length; // Returns 5 With property dot notation, we write the object’s name, followed by the dot operator and then the property name (key):
179
``` let spaceship = { homePlanet: 'Earth', color: 'silver', 'Fuel Type': 'Turbo Fuel', numCrew: 5, flightPath: ['Venus', 'Mars', 'Saturn'] }; ``` ``` let crewCount = spaceship.numCrew; console.log(crewCount); ``` // Output 5
Accessing a property using . Operator then placing it in a new variable
180
Accessing a property using . Operator then placing it in a new variable
``` let spaceship = { homePlanet: 'Earth', color: 'silver', 'Fuel Type': 'Turbo Fuel', numCrew: 5, flightPath: ['Venus', 'Mars', 'Saturn'] }; ``` ``` let crewCount = spaceship.numCrew; console.log(crewCount); ``` // Output 5
181
``` let spaceship = { homePlanet: 'Earth', color: 'silver', 'Fuel Type': 'Turbo Fuel', numCrew: 5, flightPath: ['Venus', 'Mars', 'Saturn'] }; ``` ``` // Write your code below let crewCount = spaceship.numCrew; console.log(crewCount); ``` let planetArray = spaceship.flightPath; console.log(planetArray); ``` //Output 5 [ 'Venus', 'Mars', 'Saturn' ] ```
Accessing two properties through .Operators then console logging them good syntax
182
Accessing two properties through .Operators then console logging them good syntax
``` let spaceship = { homePlanet: 'Earth', color: 'silver', 'Fuel Type': 'Turbo Fuel', numCrew: 5, flightPath: ['Venus', 'Mars', 'Saturn'] }; ``` ``` // Write your code below let crewCount = spaceship.numCrew; console.log(crewCount); ``` let planetArray = spaceship.flightPath; console.log(planetArray); ``` //Output 5 [ 'Venus', 'Mars', 'Saturn' ] ```
183
Bracket Notation
The second way to access a key’s value is by using bracket notation, [ ]. You’ve used bracket notation when indexing an array: ['A', 'B', 'C'][0]; // Returns 'A'
184
Using bracket notation to get a boolean value good syntax
``` let spaceship = { 'Fuel Type' : 'Turbo Fuel', 'Active Mission' : true, homePlanet : 'Earth', numCrew: 5 }; ``` let propName = 'Active Mission'; // Write your code below spaceship['Active Mission']; let isActive = spaceship['Active Mission']; console.log(spaceship[propName]);
185
``` let spaceship = { 'Fuel Type' : 'Turbo Fuel', 'Active Mission' : true, homePlanet : 'Earth', numCrew: 5 }; ``` let propName = 'Active Mission'; // Write your code below spaceship['Active Mission']; let isActive = spaceship['Active Mission']; console.log(spaceship[propName]);
Using a bracket notation to get a boolean value good syntax
186
Property Assignment
Once we’ve defined an object, we’re not stuck with all the properties we wrote. Objects are mutable meaning we can update them after we create them! We can use either dot notation, ., or bracket notation, [], and the assignment operator, = to add new key-value pairs to an object or change an existing property.
187
``` let spaceship = { 'Fuel Type' : 'Turbo Fuel', homePlanet : 'Earth', color: 'silver', 'Secret Mission' : 'Discover life outside of Earth.' }; ``` ``` // Write your code below spaceship['color'] ='glorious gold'; spaceship['numEngines'] = 9; delete spaceship['Secret Mission']; ```
Changing property, creating property, and deleting properties good syntax
188
Changing property, creating property, and deleting properties good syntax
``` let spaceship = { 'Fuel Type' : 'Turbo Fuel', homePlanet : 'Earth', color: 'silver', 'Secret Mission' : 'Discover life outside of Earth.' }; ``` ``` // Write your code below spaceship['color'] ='glorious gold'; spaceship['numEngines'] = 9; delete spaceship['Secret Mission']; ```
189
Methods
When the data stored on an object is a function we call that a method. A property is what an object has, while a method is what an object does.
190
Method created that calls a variable, good syntax
let retreatMessage = 'We no longer wish to conquer your planet. It is full of dogs, which we do not care for.'; // Write your code below ``` var alienShip = { retreat() { console.log(retreatMessage) }, ``` }
191
Creation of variables with methods then the calling of those methods (good syntax)
let retreatMessage = 'We no longer wish to conquer your planet. It is full of dogs, which we do not care for.'; // Write your code below ``` var alienShip = { retreat() { console.log(retreatMessage); }, takeOff() { console.log('Spim... Borp... Glix... Blastoff!'); } }; ``` alienShip.retreat(); alienShip.takeOff();
192
let retreatMessage = 'We no longer wish to conquer your planet. It is full of dogs, which we do not care for.'; // Write your code below ``` var alienShip = { retreat() { console.log(retreatMessage); }, takeOff() { console.log('Spim... Borp... Glix... Blastoff!'); } }; ``` alienShip.retreat(); alienShip.takeOff();
Creation of variables with methods then the calling of those methods (good syntax)
193
Nested Objects
In application code, objects are often nested— an object might have another object as a property which in turn could have a property that’s an array of even more objects
194
In application code, objects are often nested— an object might have another object as a property which in turn could have a property that’s an array of even more objects
Nested Objects
195
let spaceship = { 'Fuel Type' : 'Turbo Fuel', homePlanet : 'Earth' }; ``` // Write your code below let greenEnergy= obj =>{ obj['Fuel Type'] = 'avocado oil'; } let remotelyDisable= obj =>{ obj.disabled = true; } console.log(remotelyDisable); ``` greenEnergy(spaceship); remotelyDisable(spaceship); console.log(spaceship); ``` Output: [Function: remotelyDisable] { 'Fuel Type': 'avocado oil', homePlanet: 'Earth', disabled: true } ```
Several created objects
196
Looping Through Objects Loops are programming tools that repeat a block of code until a condition is met. We learned how to iterate through arrays using their numerical indexing, but the key-value pairs in objects aren’t ordered! JavaScript has given us alternative solution for iterating through objects with the for...in syntax .
197
``` let spaceship = { crew: { captain: { name: 'Lily', degree: 'Computer Engineering', cheerTeam() { console.log('You got this!') } }, 'chief officer': { name: 'Dan', degree: 'Aerospace Engineering', agree() { console.log('I agree, captain!') } }, medic: { name: 'Clementine', degree: 'Physics', announce() { console.log(`Jets on!`) } }, translator: { name: 'Shauna', degree: 'Conservation Science', powerFuel() { console.log('The tank is full!') } } } }; ``` // Write your code below for (let crewMember in spaceship.crew) { console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`) }; for (let crewMember in spaceship.crew) { console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`) }; //Output captain: Lily chief officer: Dan medic: Clementine translator: Shauna
Using for in loop to go through object in order to print info good syntax
198
``` let spaceship = { crew: { captain: { name: 'Lily', degree: 'Computer Engineering', cheerTeam() { console.log('You got this!') } }, 'chief officer': { name: 'Dan', degree: 'Aerospace Engineering', agree() { console.log('I agree, captain!') } }, medic: { name: 'Clementine', degree: 'Physics', announce() { console.log(`Jets on!`) } }, translator: { name: 'Shauna', degree: 'Conservation Science', powerFuel() { console.log('The tank is full!') } } } }; ``` // Write your code below for (let crewMember in spaceship.crew) { console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`) }; for (let crewMember in spaceship.crew) { console.log(`${spaceship.crew[crewMember].name}: ${spaceship.crew[crewMember].degree}`) }; ``` //Output captain: Lily chief officer: Dan medic: Clementine translator: Shauna Lily: Computer Engineering Dan: Aerospace Engineering Clementine: Physics Shauna: Conservation Science ```
For in loops with good syntax
199
``` const robot = { model: '1E78V2', energyLevel: 100, }; ```
1 Object with two variables good syntax
200
1 Object with two variables good syntax
``` const robot = { model: '1E78V2', energyLevel: 100, }; ```
201
``` const robot = { model: '1E78V2', energyLevel: 100, provideInfo(){ return `I am ${this.model} and my current energy level is ${this.energyLevel}.` } }; ``` console.log(robot.provideInfo()); //Output I am 1E78V2 and my current energy level is 100.
Using 'this' keyword good syntax
202
Using 'this' keyword good syntax
``` const robot = { model: '1E78V2', energyLevel: 100, provideInfo(){ return `I am ${this.model} and my current energy level is ${this.energyLevel}.` } }; ``` console.log(robot.provideInfo()); //Output I am 1E78V2 and my current energy level is 100.
203
Use of get keyword good syntax
``` const robot = { _model: '1E78V2', _energyLevel: 100, get energyLevel(){ if(typeof this._energyLevel === 'number') { return 'My current energy level is ' + this._energyLevel } else { return "System malfunction: cannot retrieve energy level" } } }; ``` console.log(robot.energyLevel);
204
``` const robot = { _model: '1E78V2', _energyLevel: 100, get energyLevel(){ if(typeof this._energyLevel === 'number') { return 'My current energy level is ' + this._energyLevel } else { return "System malfunction: cannot retrieve energy level" } } }; ``` console.log(robot.energyLevel);
Use of get keyword
205
``` const robot = { _model: '1E78V2', _energyLevel: 100, _numOfSensors: 15, get numOfSensors(){ if(typeof this._numOfSensors === 'number'){ return this._numOfSensors; } else { return 'Sensors are currently down.' } }, set numOfSensors(num) { if (typeof num === 'number' && num >= 0){ this._numOfSensors = num; } else { console.log('Pass in a number that is greater than or equal to 0') } } }; ``` robot. numOfSensors = 100; console. log(robot.numOfSensors);
Set Keyword
206
Factory functions good syntax
``` const robotFactory = (model, mobile) => { return { model : model, mobile: mobile, beep () { console.log('Beep Boop'); } }; }; ``` ``` const tinCan = robotFactory('P-500', true); tinCan.beep(); ```
207
``` function robotFactory(model, mobile){ return { model, mobile, beep() { console.log('Beep Boop'); } } } ``` ``` // To check that the property value shorthand technique worked: const newRobot = robotFactory('P-501', false) console.log(newRobot.model) console.log(newRobot.mobile) ```
208
``` function squareOrSquareRoot(array) { return array.map(item => Math.sqrt(item) == Math.sqrt(item).toFixed(0) ? Math.sqrt(item) : item * item); } ```
Use of square foot function Math.sqrt as well as .toFixed method solution for square rooting number that has a whole number root or squaring it in the event it doesn't
209
Use of square foot function Math.sqrt as well as .toFixed method solution for square rooting number that has a whole number root or squaring it in the event it doesn't
``` function squareOrSquareRoot(array) { return array.map(item => Math.sqrt(item) == Math.sqrt(item).toFixed(0) ? Math.sqrt(item) : item * item); } ```
210
Several functions solid syntax
//Arrays //Your pokemon party order which is a list of pokemon has been leaked to Misty. // Please create a function that reverses your list and prints it to the console. const pokemonRoster = ['Farfetch', 'Missingno', 'Wartortle']; console.log(pokemonRoster); const reverseRoster= pokemonRoster.reverse(); console.log(reverseRoster); ``` //Given two integer arrays a, b, both of length >= 1, create a program that returns true if the sum of the squares of // each element in a is strictly greater than the sum of the cubes of each element in b. ``` ``` const arrayA = [25, 16, 4]; const arrayb = [20, 25, 30]; ``` // .reverse function, good syntax function compareSquareAndCube(a, b){ return a.reduce ((acc,c) => acc + c **2, 0) > b.reduce ((acc,c)=> acc + c**3, 0) } compareSquareAndCube([2,2,2],[2,2,2]) console.log(compareSquareAndCube([2,2,2],[2,2,2])); // .reduce method good syntax ``` //Return a new array consisting of elements which are multiple of their own index in input array (length > 1). // Some cases: // [22, -6, 32, 82, 9, 25] => [-6, 32, 25] ``` ``` function isMultiple(){ return arr.filter((e,i )=> e % i === 0 ) ``` ``` // .filter good syntax also good use of modulus } ``` //Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers.Return your answer as a number. ``` function sumOfValues(arr){ return arr.reduce((acc, c) => + acc + Number(c), 0) ``` } sumOfValues(['5',3,'2',1]) console.log(sumOfValues(['5',3,'2',1])); // Second example of .reduce good syntax
211
Get function and changes inside of a constructor, good syntax
``` class Animal{ constructor(name){ this.name = name } speak(){ console.log(`${this.name} makes a sound`) } } ``` let simba = new Animal('Simba') simba. name // "Simba" simba. name = 'Bob' //nothing happens simba. name // "Bob"
212
Api Fetch good syntax, calls random dog photo from website
const imageRandom = document.getElementById("imageRandom"); ``` function getRandomImage(){ const randomImageApiUrl = "https://dog.ceo/api/breeds/image/random"; ``` ``` // we are using fetch api to make rest api calls. you can use axios use. // we are also using promises here. fetch(randomImageApiUrl) .then(function(response){ // we get raw response. need to first convert it into json format so we can use the data easily return response.json(); }) .then(function(json){ // now we got the json . we can use this to update any data in html console.log(json); var imageUrl = json.message; //update the image with new random url imageRandom.src=imageUrl; ``` ``` }) .catch(function(error){ // if any error occurs like no internet connection then this callback will be called console.log(error); ``` }); } ``` //call the getRandomImage function whenever page loads getRandomImage(); ```
213
Api Fetch Cocktail search system good Syntax
``` //The user will enter a cocktail. Get a cocktail name, photo, and instructions and place them in the DOM document.querySelector('button').addEventListener('click', getDrink) ``` // This creates the button used that says get cocktail ``` function getDrink(){ let drink = document.querySelector('input').value.replaceAll(" ", "%20") // This replaces drink with rendered input ``` let h2 = document.querySelector('h2') // This puts text in place of H2 let current = document.querySelector('#current') ``` let h3 = document.querySelector('h3') let reel = document.querySelector('.reel') ``` fetch(`https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${drink}`) .then(res => res.json()) // parse response as JSON .then(data => { let random = Math.floor(Math.random()*data.drinks.length) console. log(data.drinks) h2. innerText = data.drinks[random].strDrink current. src = data.drinks[random].strDrinkThumb h3. innerText = data.drinks[random].strInstructions reel. innerHTML = "" ``` for(let i = 0; i < data.drinks.length; i++){ const pics = document.createElement('div') pics.innerHTML = `

${data.drinks[i].strDrink}

` reel.appendChild(pics) } let imgs = document.querySelectorAll('.pictures') imgs.forEach(img => img.addEventListener('click', change)) function change(e){ current.src = e.target.src //how can I target the appended

? h2.innerText = e.pics.p.innerText } ``` ``` }) .catch(err => { console.log(`error ${err}`) }); }

```