Javascript Flashcards
How many data types are there in Javascript?
7.
Number, String, Boolean, Null, Undefined, Symbol Object
Operator
An operator is a character that performs a task in our code.
String Concatenation
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.’
.length
Use the .length property to log the number of characters in the following string to the console:
Ways to call methods
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
.toUpperCase
console.log(‘hello’.toUpperCase()); // Prints ‘HELLO’
Math.random
Math.random generates a random number between 0 and 1.
Math.floor()
Then, Math.floor() rounds the number down to the nearest whole number.
console.log().
Data is printed, or logged, to the console, a panel that displays messages, with console.log()
var
var, short for variable, is a JavaScript keyword that creates, or declares, a new variable.
myName
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).
const entree = 'Enchiladas'; console.log(entree);
Proper syntax for constant variable console.log
var favoriteFood = ‘pizza’;
Declaring a variable syntax
Declaring a variable syntax
var favoriteFood = ‘pizza’;
var numofSlices = 8;
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.
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.
var numofSlices = 8;
var favoriteFood = 'pizza'; console.log(favoriteFood);
How to properly console log a variable
How to properly console log a variable
var favoriteFood = 'pizza'; console.log(favoriteFood);
var favoriteFood = 'pizza'; console.log(favoriteFood);
var numOfSlices = 8; console.log(numOfSlices);
Console logging words vs. Console logging a var w/ numerical value
Console logging words vs. Console logging a var w/ numerical value
var favoriteFood = 'pizza'; console.log(favoriteFood);
var numOfSlices = 8; console.log(numOfSlices);
assign a var a boolean value
let changeMe = true
let changeMe = true
How to assign a var a bullian value
How to console.log a variable
let changeMe = false; console.log('changeMe')
let changeMe = false; console.log('changeMe')
How to console log a variable
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
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;
const entree = ‘Enchiladas’;
Creating a constant variable syntax
Creating a constant variable syntaxconst entree = ‘Enchiladas’;
const entree = ‘Enchiladas’;
Proper syntax for constant variable console.log
const entree = 'Enchiladas'; console.log(entree);
const entree = 'Enchiladas'; console.log(entree);
Proper syntax for console logging constant
const entree = 'Enchiladas'; console.log(entree); entree = 'Tacos'
Causes error when attempting to change constant variable
Causes error when attempting to change constant variable
const entree = 'Enchiladas'; console.log(entree); entree = 'Tacos'
let w = 4; w += 1;
console.log(w); // Output: 5
+= Operator
+=Operator
let w = 4; w += 1;
console.log(w); // Output: 5
let experience = 18;
experience += 16;
console.log(experience); // Output: 34
Properly using += to change numeric value of a variable
Properly using += to change numeric value of a variable
let experience = 18;
experience += 16;
console.log(experience); // Output: 34
Increase Incriment
let a = 10;
a++;
console.log(a); // Output: 11
let a = 10;
a++;
console.log(a); // Output: 11
Increase Increment
let b = 20;
b–;
console.log(b); // Output: 19
Decrease in incriment
Decrease in increment
let b = 20;
b–;
console.log(b); // Output: 19
How to concatenate regular text with string value of variable
let favoriteAnimal = 'Phoenix'; console.log('My favorite animal: '+ favoriteAnimal);
let favoriteAnimal = 'Phoenix'; console.log('My favorite animal: '+ favoriteAnimal);
How to concatenate regular text with string value of variable
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.
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
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.
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
let newVariable = ‘Playing around with typeof.’;
console.log(typeof newVariable);
newVariable = 1;
console.log(typeof newVariable);
Result is
String
Number
Proper protocol for adding a set variable to an unset number
const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273;
const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273;
Proper protocol for adding a set variable to an unset number
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
fahrenheit = Math.floor(fahrenheit);
Proper example of using Math.floor object
Proper example of using Math.floor
fahrenheit = Math.floor(fahrenheit); // Math floor (Math being the object .floor being the method)
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.
);
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
let myName = 'Leon David'.toLowerCase(); console.log(myName);
Proper use of built in method .toLowerCase
Proper use of built in method .toLowerCase
let myName = 'Leon David'.toLowerCase(); console.log(myName);
//Output leon david
What is the outcome of this statement?
console.log(‘hi!’.length);
3 is Printed to the console
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.’);
}
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
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: !==
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
===
String comparison
Ex. ‘apples’ === ‘oranges’ // false
‘apples’ === ‘oranges’
String comparison with false Boolean value
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)
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
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 (!)
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
&& 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'); }
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
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
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.
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
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
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
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
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.’);
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:
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!’);
let favoritePhrase = ‘Love That!’;
favoritePhrase === ‘Love That!’ ? console.log(‘I love that!’)console.log(“I don’t love that!”);
Ternary Operator with Comparison Operator
Ternary Operator with Comparison Operator
let favoritePhrase = ‘Love That!’;
favoritePhrase === ‘Love That!’ ? console.log(‘I love that!’)console.log(“I don’t love that!”);
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.’);
}
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
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:
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
Switch Keyword single appropriate syntax
let athleteFinalPosition = ‘first place’;
switch(athleteFinalPosition){
case ‘first place’:
console.log(‘You get the gold medal!’);
let athleteFinalPosition = ‘first place’;
switch(athleteFinalPosition){
case ‘first place’:
console.log(‘You get the gold medal!’);
Switch Keyword single appropriate syntax
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
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; }
userName = ‘’
userName ? console.log(Hello, ${userName}!
) : console.log(‘Hello!’);
Appropriate Syntax Ternary expression combined with interpolation and a falsy variable
//Output Hello!
Appropriate Syntax Ternary expression combined with interpolation and a falsy variable
//Output Hello!
userName = ‘’
userName ? console.log(Hello, ${userName}!
) : console.log(‘Hello!’);
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;
}
raceNumber = Math.floor(Math.random() * 1000);
earlyRegistration = true;
runnersAge = 22;
console.log(raceNumber, earlyRegistration, runnersAge);
Can console log multiple inputs
//Output
669 true 22
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’);
function getReminder() { console.log('Water the plants.'); } function greetInSpanish() {console.log('Buenas Tardes.'); }
getReminder()
greetInSpanish()
Creating function then calling function
Creating function then calling function syntax
function getReminder() { console.log('Water the plants.'); } function greetInSpanish() {console.log('Buenas Tardes.'); }
getReminder()
greetInSpanish()
function sayThanks() { console.log(‘Thank you for your purchase! We appreciate your business’)
}
sayThanks()
sayThanks()
sayThanks()
The ability to call a function multiple times
The ability to call a function multiple times
function sayThanks() { console.log(‘Thank you for your purchase! We appreciate your business’)
}
sayThanks()
sayThanks()
sayThanks()
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.
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
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
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}`); }
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
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)
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);
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
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
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'));
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:
const plantNeedsWater = (day) => { if (day === 'Wednesday') { return true; } else { return false; } };
Function created w/ arrow syntax
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
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
const logVisibleLightWaves = () => { const lightWaves = 'Moonlight'; console.log(lightWaves); };
logVisibleLightWaves();
// console.log(lightWaves);
Function creation through arrow
Function creation through arrow
const logVisibleLightWaves = () => { const lightWaves = 'Moonlight'; console.log(lightWaves); };
logVisibleLightWaves();
// console.log(lightWaves);
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.
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
const hobbies = [ ‘Stuff’, ‘Hello World!’, ‘Butt’];
Constant with 3 strings in an array good syntax
Constant with 3 strings inside of an array good syntax
const hobbies = [ ‘Stuff’, ‘Hello World!’, ‘Butt’];
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];
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
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
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
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
let seasons = [‘Winter’, ‘Spring’, ‘Summer’, ‘Fall’];
seasons[3] = 'Autumn'; console.log(seasons); //Output: ['Winter', 'Spring', 'Summer', 'Autumn']
Changing values in an array good syntax
Changing values in an array good syntax
let seasons = [‘Winter’, ‘Spring’, ‘Summer’, ‘Fall’];
seasons[3] = 'Autumn'; console.log(seasons); //Output: ['Winter', 'Spring', 'Summer', 'Autumn']
const newYearsResolutions = [‘Keep a journal’, ‘Take a falconry class’];
console.log(newYearsResolutions.length); // Output: 2
. Length as it applies to arrays, good syntax
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
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
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
.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’]
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’]
.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' ]
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
Nested Array good syntax
const nestedArr = [[1], [2, 3]];
console. log(nestedArr[1]); // Output: [2, 3]
console. log(nestedArr[1][0]); // Output: 2
Var with nested array good syntax
var numberClusters =[[1, 2] , [3, 4] , [5, 6]];
var numberClusters =[[1, 2] , [3, 4] , [5, 6]];
Var with nested array good syntax
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
// 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
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]);
// 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
// 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
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); }
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]); }
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
// 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’ ]
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++; }
// 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
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);
}
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
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);
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
// 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
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]); }
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
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.`
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
.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}.`))
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
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():
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
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:
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
. 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; })
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
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.
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
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
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:
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
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);
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.
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
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
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);
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
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
Object with two properties good syntax
let fasterShip = { 'Fuel Type': 'Turbo Fuel', color: 'silver' };
let fasterShip = { 'Fuel Type': 'Turbo Fuel', color: 'silver' };
Object with two properties good sytnax
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):
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
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
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
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' ]
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’
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]);
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
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.
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
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'];
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.
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) },
}
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();
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)
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
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
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
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 .
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
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
const robot = { model: '1E78V2', energyLevel: 100, };
1 Object with two variables good syntax
1 Object with two variables good syntax
const robot = { model: '1E78V2', energyLevel: 100, };
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
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.
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);
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
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
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();
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)
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
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); }
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 + c3, 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
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”
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();
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 = `<p>${data.drinks[i].strDrink}</p> <img class="pictures">` 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<p>? h2.innerText = e.pics.p.innerText }
}) .catch(err => { console.log(`error ${err}`) }); }</p>