Javascript Flashcards

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
Q

let changeMe = true;

changeMe = false;

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

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

A

let changeMe = true;

changeMe = false;

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

const entree = ‘Enchiladas’;

A

Creating a constant variable syntax

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

Creating a constant variable syntaxconst entree = ‘Enchiladas’;

A

const entree = ‘Enchiladas’;

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

Proper syntax for constant variable console.log

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

Proper syntax for console logging constant

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

Causes error when attempting to change constant variable

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

Causes error when attempting to change constant variable

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

console.log(w); // Output: 5

A

+= Operator

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

+=Operator

A
let w = 4;
w += 1;

console.log(w); // Output: 5

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

let experience = 18;
experience += 16;
console.log(experience); // Output: 34

A

Properly using += to change numeric value of a variable

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

Properly using += to change numeric value of a variable

A

let experience = 18;
experience += 16;
console.log(experience); // Output: 34

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

Increase Incriment

A

let a = 10;
a++;
console.log(a); // Output: 11

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

let a = 10;
a++;
console.log(a); // Output: 11

A

Increase Increment

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

let b = 20;
b–;
console.log(b); // Output: 19

A

Decrease in incriment

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

Decrease in increment

A

let b = 20;
b–;
console.log(b); // Output: 19

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

How to concatenate regular text with string value of variable

A
let favoriteAnimal = 'Phoenix';
console.log('My favorite animal: '+ favoriteAnimal);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q
let favoriteAnimal = 'Phoenix';
console.log('My favorite animal: '+ favoriteAnimal);
A

How to concatenate regular text with string value of variable

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

String Interpolation

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

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.
A

String Interpolation

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

let newVariable = ‘Playing around with typeof.’;

console.log(typeof newVariable);

// Result is string

A

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.

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

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.

A

let newVariable = ‘Playing around with typeof.’;

console.log(typeof newVariable);

// Result is string

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

let newVariable = ‘Playing around with typeof.’;

console.log(typeof newVariable);

newVariable = 1;

console.log(typeof newVariable);

A

Result is
String
Number

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

Proper protocol for adding a set variable to an unset number

A
const kelvin = 293; 
// Setting Kelvin as constant
const celsius = kelvin -273;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q
const kelvin = 293; 
// Setting Kelvin as constant
const celsius = kelvin -273;
A

Proper protocol for adding a set variable to an unset number

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q
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
A

Thermometer Code

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

fahrenheit = Math.floor(fahrenheit);

A

Proper example of using Math.floor object

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

Proper example of using Math.floor

A

fahrenheit = Math.floor(fahrenheit); // Math floor (Math being the object .floor being the method)

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

String Interpolation syntax

A
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.);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q
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.);

A

String interpolation syntax

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q
let myName = 'Leon David'.toLowerCase();
console.log(myName);
A

Proper use of built in method .toLowerCase

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

Proper use of built in method .toLowerCase

A
let myName = 'Leon David'.toLowerCase();
console.log(myName);

//Output leon david

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

What is the outcome of this statement?

console.log(‘hi!’.length);

A

3 is Printed to the console

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

Proper if else syntax based on Boolean value

A

let sale = true;

sale = false;

if(sale) {
console.log(‘Time to buy!’);}

else { console.log(‘Time to wait for a sale.’);

}

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

let sale = true;

sale = false;

if(sale) {
console.log(‘Time to buy!’);}

else { console.log(‘Time to wait for a sale.’);

}

A

Proper if else syntax based on Boolean value

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

Comparison Operators

A

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: !==
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

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: !==
A

Comparison Operators

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

===

A

String comparison

Ex. ‘apples’ === ‘oranges’ // false

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

‘apples’ === ‘oranges’

A

String comparison with false Boolean value

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

let hungerLevel = 7;

if(hungerLevel > 7) {
  console.log('Time to eat!');
  } else {
  console.log('We can eat later!');
};
A

If Else example (No need to specify inverse of if condition in this example)

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

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 (!)

A

Logical Operator

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

Logical Operator

A

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 (!)

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

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 (!)

A

Logical Operator

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

&& Operator

A

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');
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

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');
}
A

&& Operator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q
let mood = 'sleepy';
let tirednessLevel = 6;
if (mood === 'sleepy' && tirednessLevel > 8) {
  console.log('time to sleep');
} else {
  console.log('not bed time yet');
}
A

Proper && Syntax w/ a numerical value

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

Truthy Value

A

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.

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

Falsy Values

A

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

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

Truthy Vs. Falsy Example

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q
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
A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

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.

A

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

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

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:

A

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.’);

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

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.’);

A

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:

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

let isNightTime = true;

if (isNightTime) {
console.log(‘Turn on the lights!’);
} else {
console.log(‘Turn off the lights!’);

Create using Ternary Operator

A

let isNightTime = true;

isNightTime ? console.log(‘Turn on the lights!’) : console.log(‘Turn off the lights!’);

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

let favoritePhrase = ‘Love That!’;

favoritePhrase === ‘Love That!’ ? console.log(‘I love that!’)console.log(“I don’t love that!”);

A

Ternary Operator with Comparison Operator

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

Ternary Operator with Comparison Operator

A

let favoritePhrase = ‘Love That!’;

favoritePhrase === ‘Love That!’ ? console.log(‘I love that!’)console.log(“I don’t love that!”);

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

Else ifs in appropriate Syntax

A

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.’);
}

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

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.’);
}

A

Else if in appropriate Syntax

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

The switch keyword

A

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:

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

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:

A

The switch keyboard

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

Switch Keyword single appropriate syntax

A

let athleteFinalPosition = ‘first place’;

switch(athleteFinalPosition){
case ‘first place’:
console.log(‘You get the gold medal!’);

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

let athleteFinalPosition = ‘first place’;

switch(athleteFinalPosition){
case ‘first place’:
console.log(‘You get the gold medal!’);

A

Switch Keyword single appropriate syntax

87
Q

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;
}
A

Switch appropriate syntax multiple instances

88
Q

Switch keyword appropriate

A

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
Q

userName = ‘’

userName ? console.log(Hello, ${userName}!) : console.log(‘Hello!’);

A

Appropriate Syntax Ternary expression combined with interpolation and a falsy variable

//Output Hello!

90
Q

Appropriate Syntax Ternary expression combined with interpolation and a falsy variable

//Output Hello!

A

userName = ‘’

userName ? console.log(Hello, ${userName}!) : console.log(‘Hello!’);

91
Q

Magic 8 ball code with lots of proper syntax

A

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
Q

raceNumber = Math.floor(Math.random() * 1000);
earlyRegistration = true;
runnersAge = 22;
console.log(raceNumber, earlyRegistration, runnersAge);

A

Can console log multiple inputs

//Output

669 true 22

93
Q

Runners registration program with plenty of examples of a appropriate syntax with if, else, else if and strict comparison equality operator

A
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
Q
function getReminder() {
console.log('Water the plants.');
}
function greetInSpanish()
{console.log('Buenas Tardes.');
}

getReminder()
greetInSpanish()

A

Creating function then calling function

95
Q

Creating function then calling function syntax

A
function getReminder() {
console.log('Water the plants.');
}
function greetInSpanish()
{console.log('Buenas Tardes.');
}

getReminder()
greetInSpanish()

96
Q

function sayThanks() { console.log(‘Thank you for your purchase! We appreciate your business’)

}
sayThanks()
sayThanks()
sayThanks()

A

The ability to call a function multiple times

97
Q

The ability to call a function multiple times

A

function sayThanks() { console.log(‘Thank you for your purchase! We appreciate your business’)

}
sayThanks()
sayThanks()
sayThanks()

98
Q

Calling a function then adding parameters to it

A

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
Q

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.

A

Setting a function with a preset parameter then placing an aspect in it

100
Q
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')
A

Call to function then assigning parameters
Output: remember to buy milk
remember to buy bread
remember to buy eggs

101
Q

Bring function to console

A
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
Q
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}`);
}
A

Bring function to console

103
Q
function monitorCount(rows,columns){
return rows * columns;
}

const numOfMonitors = monitorCount(5,4);

console.log(numOfMonitors);

A

Creating function, calling it’s returns then utilizing function in the creation of a new constant variable (Good Syntax)

104
Q

Creating function, calling it’s returns then utilizing function in the creation of a new constant variable (Good Syntax)

A
function monitorCount(rows,columns){
return rows * columns;
}

const numOfMonitors = monitorCount(5,4);

console.log(numOfMonitors);

105
Q
function monitorCount(rows, columns) {
  return rows * columns;
}
function costOfMonitors(rows, columns) {
 return monitorCount(rows, columns)  * 200;
}

const totalCost = costOfMonitors(5, 4);

console.log(totalCost);

A

Good function syntax

106
Q
const plantNeedsWater= function(day){
  if(day === 'Wednesday'){
    return true; }
else{
  return false;
  }
};
 plantNeedsWater('Tuesday')
console.log(plantNeedsWater('Tuesday'));
A

Function inside a constant with a false boolean value. Good syntax

107
Q

Function inside a constant with a false boolean value. Good syntax

A
const plantNeedsWater= function(day){
  if(day === 'Wednesday'){
    return true; }
else{
  return false;
  }
};
 plantNeedsWater('Tuesday')
console.log(plantNeedsWater('Tuesday'));
108
Q

Arrow Functions

A

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
Q
const plantNeedsWater = (day) => {
  if (day === 'Wednesday') {
    return true;
  } else {
    return false;
  }
};
A

Function created w/ arrow syntax

110
Q
const city ='New York City'
function logCitySkyline() {
let skyscraper = 'Empire State Building'
return 'The stars over the ' + skyscraper + ' in ' +city;
};

console.log(logCitySkyline());

A

Function created w/ arrow syntax

111
Q
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());
A

Three variables declared then 4th constant is turned into a function by arrow function

112
Q
const logVisibleLightWaves = () => {
  const lightWaves = 'Moonlight';
  console.log(lightWaves);
};

logVisibleLightWaves();

// console.log(lightWaves);

A

Function creation through arrow

113
Q

Function creation through arrow

A
const logVisibleLightWaves = () => {
  const lightWaves = 'Moonlight';
  console.log(lightWaves);
};

logVisibleLightWaves();

// console.log(lightWaves);

114
Q

Array Literal

A

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
Q

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.

A

Array Literal

116
Q

const hobbies = [ ‘Stuff’, ‘Hello World!’, ‘Butt’];

A

Constant with 3 strings in an array good syntax

117
Q

Constant with 3 strings inside of an array good syntax

A

const hobbies = [ ‘Stuff’, ‘Hello World!’, ‘Butt’];

118
Q

Creating new var from array good syntax

A

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
Q

const famousSayings = [‘Fortune favors the brave.’, ‘A joke is a very serious thing.’, ‘Where there is love there is life.’];

const listItem = famousSayings[0];

A

Creating new variable out of an array, good syntax

120
Q

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

A

Console logging the third item from an array good syntax

121
Q

Console logging the third item in an array good syntax

A

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
Q

Getting an undefined response from an array due to nothing being in the value place requested

A

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
Q

let seasons = [‘Winter’, ‘Spring’, ‘Summer’, ‘Fall’];

seasons[3] = 'Autumn';
console.log(seasons); 
//Output: ['Winter', 'Spring', 'Summer', 'Autumn']
A

Changing values in an array good syntax

124
Q

Changing values in an array good syntax

A

let seasons = [‘Winter’, ‘Spring’, ‘Summer’, ‘Fall’];

seasons[3] = 'Autumn';
console.log(seasons); 
//Output: ['Winter', 'Spring', 'Summer', 'Autumn']
125
Q

const newYearsResolutions = [‘Keep a journal’, ‘Take a falconry class’];

console.log(newYearsResolutions.length);
// Output: 2
A

. Length as it applies to arrays, good syntax

126
Q

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'];
A

.Push function good syntax

127
Q

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

A

Pop method removing an item from an array

128
Q

const chores = [‘wash dishes’, ‘do laundry’, ‘take out trash’, ‘cook dinner’, ‘mop floor’];

chores. pop();
console. log(chores);

A

.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
Q

.Shift and .Unshift good syntax

A

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
Q

const groceryList = [‘orange juice’, ‘bananas’, ‘coffee beans’, ‘brown rice’, ‘pasta’, ‘coconut oil’, ‘plantains’];

groceryList.shift();

console.log(groceryList);

groceryList.unshift(‘popcorn’);

console.log(groceryList);

A

.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
Q

.shift .unshift and .slice usage good syntax

‘plantains’ ]
[ ‘bananas’, ‘coffee beans’, ‘brown rice’ ]

A

.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
Q

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);

A

Shift, unshift, slice and index of in good syntax

133
Q

Nested Array good syntax

A

const nestedArr = [[1], [2, 3]];

console. log(nestedArr[1]); // Output: [2, 3]
console. log(nestedArr[1][0]); // Output: 2

134
Q

Var with nested array good syntax

A

var numberClusters =[[1, 2] , [3, 4] , [5, 6]];

135
Q

var numberClusters =[[1, 2] , [3, 4] , [5, 6]];

A

Var with nested array good syntax

136
Q

const numberClusters =[[1, 2], [3, 4], [5, 6]];

const target = numberClusters [2][1];

console.log(target);

//Output 6

A

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
Q

// Write your code below

const vacationSpots = [‘Colombia’ , ‘Seoul’, ‘New Orleans’];

console. log(vacationSpots[0]);
console. log(vacationSpots[1]);
console. log(vacationSpots[2]);

A

Console logging all aspects of an array w/out a loop

Output// Colombia Seoul New Orleans

138
Q

Console logging all aspects of an array w/out a loop

Output// Colombia Seoul New Orleans

A

// Write your code below

const vacationSpots = [‘Colombia’ , ‘Seoul’, ‘New Orleans’];

console. log(vacationSpots[0]);
console. log(vacationSpots[1]);
console. log(vacationSpots[2]);

139
Q
// Write your code below
for (let counter = 5; counter < 11; counter++) {
  console.log(counter);
}
A
For loop up to 10 good syntax Output 
5
6
7
8
9
10
11
140
Q
// 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);
}
A

Descend for loop good syntax

141
Q

Descending for loop good syntax

A
// 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
Q

Using a for loop to run through an array

A

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
Q

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]);
}
A

Using a for loop for running through an array

144
Q

// 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)

A

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
Q

While Loop

A
// 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
Q
// 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

While Loop

147
Q

A card array that draws cards until a spade is drawn using a while loop, solid syntax

A

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
Q

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

A card array that draws cards until a spade is drawn using a while loop, solid syntax

149
Q

Do…While Statements

A

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
Q

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);

A

Do… While Statements

151
Q
// Write your code below
let cupsOfSugarNeeded = 5;
let cupsAdded = 0; 

do {
cupsAdded++
console.log(cupsAdded + ‘cup was added’)
} while (cupsAdded

A

Do while example good syntax

152
Q

Rapper array using for loop

A

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
Q

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.”);

A

Rapper loop with break and quote good syntax

154
Q

The .forEach() Method

A

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
Q

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.

A

.forEach()Method

156
Q

.forEach example good syntax

A

const fruits = [‘mango’, ‘papaya’, ‘pineapple’, ‘apple’];

// Iterate over fruits below
fruits.forEach(fruit => console.log(`I want to eat a ${fruit}.`))
157
Q

const fruits = [‘mango’, ‘papaya’, ‘pineapple’, ‘apple’];

// Iterate over fruits below
fruits.forEach(fruit => console.log(`I want to eat a ${fruit}.`))
A

for each example good syntax

158
Q

The .map() Method

A

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
Q

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():

A

The .map() Method

160
Q

The .filter() Method

A

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
Q

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:

A

The filter method

162
Q

. Filter for both numbers and letters good syntax

A

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
Q

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;
})
A

.Filters for both letters and numbers good syntax

164
Q

The .findIndex() Method

A

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
Q

const animals = [‘hippo’, ‘tiger’, ‘lion’, ‘seal’, ‘cheetah’, ‘monkey’, ‘salamander’, ‘elephant’];

const foundAnimal = animals.findIndex (animal => { return animal === 'elephant';
});

console.log(foundAnimal);

A

Find index with function being created in side of function, good syntax

166
Q

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);

A

Finding index elephant, and of animals names that start with s, good syntax

167
Q

The .reduce() Method

A

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
Q

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);

A
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
Q
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
A

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
Q

Array.prototype.some()

A

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
Q

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}));

A

Utilizing different methods inside of constants, creating arrays and

//Output true, true

172
Q

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);
A

Perfect example of several methods

173
Q

Perfect example of several methods

A

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
Q

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);
A
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
Q

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!).

A

Solid review of several methods

176
Q

Object with two properties good syntax

A
let fasterShip = { 
  'Fuel Type': 'Turbo Fuel',
  color: 'silver'
};
177
Q
let fasterShip = { 
  'Fuel Type': 'Turbo Fuel',
  color: 'silver'
};
A

Object with two properties good sytnax

178
Q

Accessing Properties

A

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
Q
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

A

Accessing a property using . Operator then placing it in a new variable

180
Q

Accessing a property using . Operator then placing it in a new variable

A
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
Q
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' ]
A

Accessing two properties through .Operators then console logging them good syntax

182
Q

Accessing two properties through .Operators then console logging them good syntax

A
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
Q

Bracket Notation

A

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
Q

Using bracket notation to get a boolean value good syntax

A
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
Q
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]);

A

Using a bracket notation to get a boolean value good syntax

186
Q

Property Assignment

A

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
Q
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'];
A

Changing property, creating property, and deleting properties good syntax

188
Q

Changing property, creating property, and deleting properties good syntax

A
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
Q

Methods

A

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
Q

Method created that calls a variable, good syntax

A

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
Q

Creation of variables with methods then the calling of those methods (good syntax)

A

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
Q

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();

A

Creation of variables with methods then the calling of those methods (good syntax)

193
Q

Nested Objects

A

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
Q

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

A

Nested Objects

195
Q

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 }
A

Several created objects

196
Q

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 .

A
197
Q
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

A

Using for in loop to go through object in order to print info good syntax

198
Q
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
A

For in loops with good syntax

199
Q
const robot = {
  model: '1E78V2',
  energyLevel: 100,
};
A

1 Object with two variables good syntax

200
Q

1 Object with two variables good syntax

A
const robot = {
  model: '1E78V2',
  energyLevel: 100,
};
201
Q
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.

A

Using ‘this’ keyword good syntax

202
Q

Using ‘this’ keyword good syntax

A
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
Q

Use of get keyword good syntax

A
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
Q
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);

A

Use of get keyword

205
Q
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);

A

Set Keyword

206
Q

Factory functions good syntax

A
const robotFactory = (model, mobile) => {
  return {
    model : model,
		mobile: mobile,
		beep () { 
      console.log('Beep Boop'); 
    }
	};
};
const tinCan = robotFactory('P-500', true);
tinCan.beep();
207
Q
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)
A
208
Q
function squareOrSquareRoot(array) {
  return array.map(item => Math.sqrt(item) == Math.sqrt(item).toFixed(0) ? Math.sqrt(item) : item * item);  
}
A

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
Q

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

A
function squareOrSquareRoot(array) {
  return array.map(item => Math.sqrt(item) == Math.sqrt(item).toFixed(0) ? Math.sqrt(item) : item * item);  
}
210
Q

Several functions solid syntax

A

//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

211
Q

Get function and changes inside of a constructor, good syntax

A
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
Q

Api Fetch good syntax, calls random dog photo from website

A

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
Q

Api Fetch Cocktail search system good Syntax

A
//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>