What is an arrow function?
A function defined as follows:
let myFunc = () => {
console.log("Hello World")
}
What is a parameter?
A parameter are the variables defined in the function declaration.
function addThree(parameter1, parameter2, parameter3) {
return parameter1 + parameter2 + parameter3
}
What is an argument?
An argument passes variables or values to a function in the function call
function addThree(parameter1, parameter2, parameter3) {
return parameter1 + parameter2 + parameter3;
}
let argument1 = 3;
let argument2 = 5;
let argument3 = 9;
addThree(argument1, argument2, argument3); //returns 17
What does the following code return
function addTwo(num1, num2) {
return num1 + num2;
}
console.log(addTwo(5))
Returns NaN - because 1 + undefined is not a number.
What are the 3 expressions in a for loop?
for (let i = 0; ... ) {}
for (let i = 0; i < array.length; ... ) {}
for (let i = 0; i < array.length; i++)
Define a comment
Comments are used in code to further define what the code is doing. They are NOT to be executed.
Which of the following may be used to insert a comment into code:
1 and 3. #1 is for multiple lines of comments. The last '*/' will close the comment area. // may also be a comment, but you must use it at the beginning of each comment line.
Can a comment come after an executable line of code as follows:
function myFunction( a, b) {
if (a < b) { //a must be less than b
return true;
} else {
return false;
}
}
Yes!
Will the following code run?
function myFunc (a, b) {
// This is my comment
it spans multiple lines
and must be closed by another pair of //
return a + b;
}
No! This will return a syntax error because it is trying to evaluate "it". '//' must be used before each line on a comment. To comment out multiple lines of code use the pair: '/* */'
What is a simple way of debugging your code?
Use console.log()
to print out variable values.
What are three ways of console logging values?
console.log("myVar Value: " + myVar)
console.log(`myVar Value: ${myVar}`)
console.log("myVar Value1: ", myVar, " and adding 1 is: ", myVar + 1)
Does this work?
let sum = 'a' + 'b';
Yes, but it may not do what you intended. If, for instance, you have two variables a=1 and b=2, and you run the code above it will not add a and b. Instead, it will concatenate the two characters 'a' and 'b' into another string of 'ab'.
Will the following work?
let a = 1;
a + b
Yes, but again, it may not give you what you intended. Here JavaScript sees a letter and a number. It will attempt to convert the number to a letter, then concatenate. The result will be '1b'
What can a Number datatype represent?
A float or an integer. It can be negative, or positive.
What will the following produce:
let x = 10;
let y = 20;
console.log("The result is: " + x + y)
The result will be 1020. Because you took a string, used the concatenate operator and added x and y. To get the result of 30, you would use:
let x = 10;
let y = 20;
console.log("The result is: ", x + y) ... or
console.log(`The result is: ${x + y}`);
What is a REPL?
REPLS: Read, Evaluate, Print Loops. Invoking node at the command line will provide a REPL.
What can variables NOT begin with?
Numbers
Can a variable begin with an underscore? (_) i.e.: let _myVar = 5;
Yes!
Which of the following are illegal?
Variables cannot begin with Numbers, and "-" is never allowed, nor is "#" ever allowed.
Variables can be any alpha/numeric value, $, or _; and cannot begin with a number
Variables may only begin with (_), (#), (alpha), (numeric), (alpha) characters
False
Variables may only begin with underscore (_), dollar sign($), or alphabetic characters
Which of the following variable names are illegal?
my#Variable: # is neither alphabetic, numeric, nor $ nor _
1Variable: Although numeric, the variable cannot begin with a number
Find the length of a string
"bootcamp".length ==> 8
What index value is the letter 't' at in the string 'bootcamp'?
'bootcamp'[3] ==> 't'
What is the index of the first letter in 'bootcamp'?
'bootcamp'[0] = 'b'
What is the difference between index and length?
Index is a zero based number. Length counts starting at 1.
What is the common problem between index and length?
Overrunning the length of the array or string. 'bootcamp'.length = 8, but 'bootcamp'[8] is undefined
How would you find the index of the letter 't' in 'bootcamp'?
Use the indexOf method: 'bootcamp'.indexOf('t') => 3;
How do you concatenate two strings?
Use the '+' operator: 'Hello' + 'World' = 'HelloWorld'
Define the 5 mathematical operators
+, -, *, /, %
Define the Comparator Operators
What is the order of precedence in evaluating multiplication, division, addition and subtraction?
How do you evaluate !==
NOT equal to
How do you evaluate &&
The expression on the left must be true AND the expression on the right must be true; otherwise the answer is false.
How do you evaluate ||
The expression on the left must be true, and if it is not, the expression on the right is evaluated to see if it is true. If neither are true, the expression is evaluated to false. Otherwise the expression is evaluated to true.
What is short-circuiting?
Only the expression that is required to determine the outcome is evaluated, starting from left to right. For instance, if true && false, both the left 'true' and the right 'false' must be evaluated. However, if 'false' && 'false' then only the left needs to be evaluated, because only one expression must be false for an '&&' operation to evaluate to false.
In the case of ||, if the left expression is true, the expression evaluates to true. So the right expression is never evaluated. If the left expression evaluates to false, then the right must be evaluated to determine if the statement evaluates to false.
What is DeMorgan's law
DeMorgan's law refers to the associativity of && and || expressions. Given a grouped expression, how would you break it apart into individual expressions.
My memory aid is: "NOT of AND is OR, and NOT of OR is AND"
Create a truth table for &&
A | B | A&&B |
false | false | false |
false | true | false |
true | false | false |
true | true | true |
Evaluate the expression: 'a' < 'b'
'a' < 'b' = true
Evaluate the expression: "Apple" < "apple"
"Apple" < "apple" = true
Evaluate the expression: 'A' > 'a'
'A' > 'a'
Evaluate the expression: 1 > 2
1 > 2 = false
What is the pneumonic for order of evaluation?
PEMDAS: Parentheses, Exponents, Multiplication and Division (from left to right), Addition and Subtraction (from left to right)
What is the difference between the expression ==
and ===
==
: Used for comparing two variables, but it ignores the datatype of the variable
===
: Used for comparing two variables, but this operator also checks the datatype when comparing.
Evaluate: 5 == "5"
5 == "5" => true
Because ==
does not compare the datatype.
Evaluate: 5 === "5"
5 === "5" //false
Because ===
evaluates the datatype as well. The number 5 is not equal to the string '5'.
Write a while loop with an empty block
while (condition) {
... code to be executed here
}
Write a for loop:
for (let i = 0; i < 5; i++) {
... do something
}
Define an iteration:
An iteration is each pass through the loop, or each time the loop executes.
What is the traditional word for the variable that keeps track of how many times a loop has been run?
index
>
Write the following loop using a while loop:
function forLoopDoubler(array) {
for (let i = 0; i < array.length; i++) {
array[i] = array[i] * 2;
}
return array;
}
function forLoopDoubler (array) {
let i = 0;
while (i < array.length) {
array[i] = array[i] * 2;
i++;
}
return array;
}
How do you determine the length of an array?
Use the .length method: myArray.length
How would you define an array?
Arrays are always defined with square brackets: let myArray = ['a', 'b', 'c']
What does this return? [4, 7, 9].length
3
How would you find the index of 9?
Either use indexOf, or because 9 is the last element in the array you can use array.length-1;
myArray.indexOf(9)
myArray[myArray.length - 1]
Given an array: let numbersAndLetters = ['b', 'z', 17, 'cat']
, find the index of 17
numbersAndLetters.indexOf(17)
==> 2
Notice that because 17 is a number, it is stored in the array index of 3. It is NOT stored as index of 3 AND 4. Similarly with 'cat', stored at index 3. This element is a string. Arrays can store different data types, and each data type gets its own index.
What do arrays ALWAYS start at (index)?
Arrays are 0-based -- meaning the first element is ALWAYS 0.
What is the most classic problem when accessing array elements?
Using length as an index. Because arrays are zero based, the last index of the array would be length-1, NOT length! myArray.length
What would the result of the following be: console.log([1, 2, 3] + [4, 5, 6]);
1, 2, 34, 5, 6
: Javascript tries to convert your array into a string. :-(
How would you concatenate an array?
console.log([1, 2, 3].concat([4, 5, 6]));
// => [1, 2, 3, 4, 5, 6]
What is the return of this expression:
let myArray = [1, 2, 3]
console.log(myArray.indexOf(4));
The number 4 is not included in the array. So the indexOf method would return -1
How do we combine two different arrays?
Use the .concat method: arrayOne.concat(arrayTwo)
How would you remove the last element on an array?
myArray.pop()
will return the last element of the array. Further, it will remove the last element from the array.
How do you remove the first element from an array?
myArray.shift()
: This will both remove the first element from the array, and return that element to the caller.
How do you add an element to an array?
If you want to add the element to the end of the array, use .push(<element>): myArray.push('newElement')
How would you add an element to the beginning of an array?
Use the unshift method: myArray.unshift('newFirstElement')
Which built-in function allows you to interate through every element in an array and return a new array?
Array.map()
let myArray = [ 1, 2, 3, 4 ]
myArray.map( (elt) => {
return elt * 2
});
//returns: [2, 4, 6, 8 ]
//does NOT mutate original array.
What builtin array function allows you to produce a sub-array matching certain criteria?
Array.filter
let myArray = [ 1, 4, 7, 6, 12, 9]
myArray.filter( (elt) => {
if (elt % 2 === 0) return elt;
});
//returns [4, 6, 12]
With the builtin array function "reduce", what is it's first argument?
accumulator.
What is accumulator set to when Array.reduce is first called?
If accumulator does not have an initial value set, then accumulator is set to the first element of the array
Write a function that will return the sum of the array [3, 7, 5, 9]
Or, in arrow function syntax:
let nums = [3, 7, 5, 9];
let sum = nums.reduce ( (accum, el) => {
return accum + el;
});
//sum is now 24.
Or ...
let sum = nums.reduce ( (accum, el) => return accum + el, 100);
Array.reduce( fn(), accum);
If Array.reduce() defaults the accumulator to the array, what does the code in the answer above add on the first iteration?
accum = 3; elt = 7;
How do you set an initial value for the accumulator?
This would be the 2nd argument to the reduce function:
let nums = [3, 7, 5, 9]
let sum = nums.reduce(function(accum, el) {
return accum + el;
}, 100);
How would you use an Array builtin function to calculate the sum of all integer elements of an array?
let nums = [3, 7, 5, 9]
let product = nums.reduce( (accum, elt) => {
return accum * el;
});
// returns
How would you take the same array as in the answer above, and first double the numbers, then multiply them together?
Because you're doubling each number, you'll need to double the first number. This requires that the accumulator doubles the number - but the accumulator will not automatically do this. So you'll need to pass in an initial value for the accumulator so that it doesn't use the first element of the array as the initial value.
let nums = [3, 7, 5, 9];
let doubleProduct = nums.reduce( (accum, el) => {
return accum * 2 * el
}, 1);
Now on the first pass accumulator will be set to 1, and each element will be doubled before being multiplied -- including the first element. Remember: If there is no initial value given for the accumulator, the initial value will be set to the first value in the array, and the second element in the array will be used in the first iteration of the reducer's function.
What is the return value from the builtin Array.reduce() function?
The accumulator.
Write a function that finds the max value of the array [3, 7, 5, 9, 2]
let nums = [3, 7, 5, 9, 2]
let max = nums.reduce( (accum, el) => {
if (el > accum) {
return el;
} else {
return accum
}});
How what are two ways to iterate through an array?
let nums = [1, 2, 3]
let newArray = []
for (let i = 0, i < nums.length; i++) {
newArray.push(2 * nums[i]);
}
or ...
let nums = [1, 2, 3];
let newArray = nums.forEach( (elt, index) => {
return elt[i] * 2
}
What is "defensive coding"?
When you write code to avoid throwing exceptions. eg:
if (value !== undefined) {}
if (value !== null) {}
The Array#forEach accepts a function as an argument. What arguments can the function that is passed into Array#forEach accept?
The function that is passed into Array#forEach may accept the current element, index, and array
What two arguments does the Array#reduce method accept?
The Array#reduce method accepts a function as it's first argument and a value to be used as the initial accumulator as an optional second argument.
The Array#filter method accepts a function as an argument. What type of data should the function that is passed into Array#filter return?
The function that is passed into Array#filter should return boolean.
The Array#reduce method accepts a function as an argument. What arguments should the function that is passed into Array#reduce accept?
The function that is passed should accept the current accumulator and current element as its arguments.
Describe what the Array#filter does.
The Array#filter method accepts a function as an argument and returns a new array containing elements of the original array that result in `true` when passed into the function.
Describe what the Array#map method does.
The Array#map method accepts a function as an argument returns a new array containing the results of calling that function on each element of the original array.
Name the array method that removes the first element of an array (mutating the array) and returns the removed element.
Array#shift
Describe what the String#split method does.
The String#split method accepts a "separator" string as an argument and returns an array containing the resulting substrings when the string is cut along instances of the "separator".
For example:
let sentence = "follow the yellow brick road";
let words = sentence.split(" ");
console.log(words); // [ 'follow', 'the', 'yellow', 'brick', 'road' ]
Name the array method that removes the last element from an array (mutating the array) and returns that removed element.
Array#pop
What do the Array#slice and String#slice methods accept as arguments?
Both methods accept a start index and end index representing the range of indices to be sliced as a new array or string. The start index is inclusive, while the end index is exclusive.
What does the term "mutability" mean in programming?
"Mutability" refers to an object's ability to undergo changed. Mutable objects can be modified, while immutable objects cannot be changed after they are created.
Describe what the Array#join method does.
The Array#join method accepts a "separator" string as an argument and returns a string where elements of the array are concatenated together with the "separator" between each element.
For example:
let words = ["run", "around", "the", "block"];
console.log(words.join("_")); // 'run_around_the_block'
Identify which of the following JavaScript data types are mutable: number, string, boolean, array
Arrays are mutable.
Numbers, strings, and booleans are all immutable. Don't confuse mutability with the variable types: var, let and const. When you define a variable with let, then yes. You can change the value of the variable. Similarly with var. However, when you change the value of the variable the variable is re-created in a different location in memory. This makes the data types shown immutable. Arrays, on the other hand, you can change the contents of the array without changing where the array points in memory. The variable containing the array will never change its memory address.
Describe what the Array#unshift method does.
The Array#unshift method accepts one or more values as arguments and will add those values to the front of the array, mutating the array. The method returns the new length of the array.
let array = ['a', 'b', 'c', 'd' ]
let arrayLength = array.unshift('e', 'd', 'f', 'g')
arrayLength //=> 8
array //=> :
[
'e', 'd', 'f',
'g', 'a', 'b',
'c', 'd'
]
Describe what the Array#push method does.
The Array#push method accepts one or more values as arguments and adds those values as new elements to the end of the array, mutating the array. The method will return the new length of the array.
let array = [1, 2, 3, 4]
array.push(6, 7, 8, 9, 10) //=> 9
array // => :
[
1, 2, 3, 4, 6,
7, 8, 9, 10
]
What does Array#splice accept as arguments?
Array#splice has two required arguments: a target index and a number of elements to remove
Array#splice can additionally accept any number of additional arguments representing values to be inserted
array // => :
[
1, 2, 3, 4, 6,
7, 8, 9, 10
]
array.splice(-1) //=> [ 10 ] -- removes 10 from the arrray and returns it as an array
array // => array now does not have 10 in it
[
1, 2, 3, 4,
6, 7, 8, 9
]
array.splice(4, 1) // returns [ 6 ] from the array, while removing it from the array
[ 6 ]
array // Array no longer has 6 in it
[
1, 2, 3, 4,
7, 8, 9
]
array.splice(0, 1, 'a', 'b', 'c') //removes 1 from the array and returns [ 1 ], then adds 'a', 'b', 'c', in its place
array // contents of the array has removed 1, and in its place put 'a', 'b', 'c'
[
'a', 'b', 'c', 2, 3,
4, 7, 8, 9
]
What will the following code snippet print out:
let arr = [ 'a', 'b', 'c', 'd', 'e', 'f' ]
arr.splice(2, 3);
console.log(arr);
['a', 'b', 'f'] : Array#splice mutates the input array, removing 3 elements starting at index 2.
When is an object considered mutable?
A mutuble object can be changed. An immutable object cannot be changed.
Which of the following types is mutable?
Arrays are mutable. Booleans, Numbers, and Strings are immutable.
What will the following code snippet print out?
let arr = ['a', 'b', 'c', 'd', 'e' ];
arr.slice(1, 3);
console.log(arr);
['a', 'b', 'c', 'd', 'e'] : Array#slice does not mutate the input array, so arr is unchanged.
Define a primitive datatype in JavaScript.
A primitive (primitive value, primitive data type) is data that is not an object, and has no methods.
How many primitive data types are there in JavaScript?
Six: string, number, bigint, boolean, undefined and symbol.
We haven't learned about symbols yet.
Is NULL a data type?
Null means "the ABSENCE of data". Any data type can be set to null.
How would you check a data type in JavaScript?
Use the built in "typeof" operator
console.log(typeof null); // 'object'
console.log(typeof 'c'); // 'string'
console.log(typeof 1); // 'number'
console.log(typeof true); // 'boolean'
let a;
console.log(typeof a); //'undefined'
Why are objects considered "first-class" in JavaScript?
A first-class object is something that can be stored in a variable.
Is a function a first class object?
Yes! You can store a function in a variable and pass it to another function
let myFunc = (a, b) => { return a + b }
doSomething(f, g, myFunc) {
if (f > g) {
return myFunc(f, g)
}
}
How do you stop your program from throwing ugly exceptions?
Use a try/catch block
What are the parts associated with try/catch blocks
try, catch, finally
What does the try, in a try catch block do?
Provides a mechanism to evalute statements and throw errors if the statements do not conform.
try {
if (array.length === 0) {
do something ...
}
}
if array is undefined, checking the length of an undefined object will throw an exception.What do you use a catch block for?
You use a catch block to gracefully process the error, rather than allowing your code to break and throw an exception to the user.
try {
if (array.length === 0) {
... do something
}
} catch (e) {
if (e === instanceOf ReferenceError) {
console.log("array is not defined");
} else {
console.log("error: ", e)
}
}
Describe the following code:
let sayHello = function() {
console.log('hello')
};
Function Expression Syntax
How can I make my own errors to be caught by try/catch blocks?
throw Error('this error');
throw new Error('this error');
What does the finally block in a try/catch block do?
The finally block runs whether or not an error occurs. It always runs.
function sumArray(array) {
let sum = 0;
try {
for (let i = 0; i < array.length; i += 1) {
sum += array[i];
}
} catch (e) {
console.log(e);
return null;
} finally {
console.log("This wil aways print.");
}
return sum;
}