Javascript
isNaN( ) vs Number.isNaN( )
isNaN( ) will perform numeric conversion, and then check if it's a number Number.isNaN( ) does not force numeric conversion - just checks if value passed is NaN
null vs. undefined
null = has a value of null, which means empty or does not exist undefined: not assigned
Method to determine whether an object has its own (not inherited) specified property. What does it return?
objNameHere.hasOwnProperty(keyValueHere) returns true if object has specified key value (not inherited)
What happens if you assign a value to the array.length property?
You could truncate or clear it, if the array's length was originally longer than the value you assign it to. You can also clear it by assigning the value of 0 array.length = 0;
How to iterate over characters of a string?
for...of for (let char of "Hello") { alert(char); }
Syntax for the property value shorthand in an key-value pair object?
instead of: let user = { name: name, age: age, }; you can do: let user = { name, age: 30 }; shorthands can be used along with normal properties in same object. Remember, this is when we use existing variables as values for property names
What is the modern mode?
"use strict" enables strict mode, and enables the new features to JS introduced in 2009 w/ ES5. Must be placed at the top of the script, or at the beginning of the function to enable strict mode in that fxn only
What is the unary plus operator and what does it do?
' + ' : precedes a value and attempts to convert it to a number - if it cannot be converted to a number, or is a BigInt, evaluates to NaN
.isFinite( ) vs. Number.isFinite( )
.isFinite( ) : returns false if value passed is undefined, NaN, + or - Infinity; will perform type conversion (so null coerces to 0) Number.isFinite( ) does not perform type conversion, checks if a value passed is a finite number; returns false if not a number, is NaN, undefined or + or - Infinity
Write the function isEmpty(obj) which returns true if the object has no properties, false otherwise.
// if the loop has started, there is a property function isEmpty(obj) { for (let key in obj) { return false; } return true; }
Create an empty object (there are 2 syntaxes - what are they called?)
1) Object constructor syntax: let user = new Object(); 2) Object literal syntax: let user = {}; (this is the usual way)
What method copies all properties from 1 or more source objects to a target object? What happens if the property/key name already exists in the target object? What happens if one of the properties/keys is an object (nested obj)? How would you do a deep copy of nested objects?
1) Object.assign(dest, source,...source); also: let clone = Object.assign({}, user); also also: let clone = {...user}; (uses spread operator) *Object.assign creates a true copy, not copy by reference, unless one of the keys' values is an object, then it will copy that object by reference 2) if property/key name already exists in target, it gets overwritten 3) It is not a true copy, but a reference to the same location in memory; deep vs. shallow copying - shallow copying is done if you use a spread operator or Object.assign 4) Manually assign (this will allow you to copy nested objects but can be tedious): const a = { drinks: { soda: 'Coke' }, foods: { dinner: 'Pasta' } } const b = { drinks: { ...a.drinks}, foods: { ...a.foods} };
How to loop thru values of an array?
Can use for...of loop, which loops thru values of an iterable (array is an iterable, string is an iterable)
Typically, what does the function prefix create, show, get, calc mean?
Create: create & return; Show: show something like a message; Get: return a value; Calc: calculate something; Check: check something and return a value
Define break/continue. How can you break out of all the nested for loops?
break can force exit of the loop, and will pass control to the first line after the loop continue doesn't stop the whole loop, it stops the current iteration and forces the loop to start a new iteration if condition allows (lighter vers of break) *cannot use break/continue with conditional/ternary operator( ? ) By using a label, you could utilize break <labelname> to break out of the outer loop (and therefore all the nested loops within) labelName: for (...) { ... } labelName: for (...) { for (...) { break labelName; } } alert('Done!') ^the break will pass flow to the line with alert()
Pre/Postfix increment operator - explain
prefix increment operator: ++x , will increment x by 1 and return the value after it was incremented postfix increment operator: x++, will increment x by 1 and return the values before it was incremented
Write an example of a switch statement. What happens if you group case statements? What happens if you do not have break? Does it use loosely equal to or strictly equal to?
switch (condition) { case 'value1': //if (x === 'value1') ...code executes here break; case 'value2': ...code executes here break; default: ...code executes here break; } You can group case statements if you want multiple cases to execute the same code. Not having break means JS will continue to the next line and check the next case statement and so on until it reaches break. Uses strictly equal to.
do...while loop? explain it
the code will execute at least once as the condition is checked at the bottom, and will continue to execute if while condition is truthy do { code executes } while (condition);
Differentiate btw rest parameter and spread operator syntax
they're the same in that it's ... but if ... is at the end of function parameters in fxn definition, it's a rest parameter and gathers the rest of the list of arguments into an array. Used to create fxns that accept any number of arguments. but if ... occurs in a function call it's called a spread operator/syntax and expands an array into a list. Used to pass an array to fxns that normally require a list of many arguments
If a function does not return a value, what will the result of the invoked function be?
undefined
Which function... 1) explicitly converts a value to a number? 2) explicitly converts a value to a string? 3) explicitly converts a value to a boolean value?
1) Number() 2) String() 3) Boolean()
How to access the object from within the object (what keyword is used)?
"this" keyword the value of "this" is evaluated during runtime, depending on the context. When a fxn is declared it may use "this", but that "this" has no value until fxn is called. If called within an object, "this" is that object. If it's called without an object, "this" is undefined in strict mode, in non-strict mode "this" is the global object. Arrow fxns do not have "this". When "this" is accessed inside an arrow fxn, "this" will take the value outside of arrow fxn.
1) Method that applies a fxn to every element in an array and returns a new array 2) Method that applies a fxn to every element in an array and returns those elements that return 'true' in a new array 3) Method that applies a fxn to every element in an array, and returns one value. Explain this method further
1) .map() 2) .filter() 3) .reduce() syntax: INPUTARR.reduce(callback fxn, initial value) callback fxn typically takes in 2 arguments: callback (accumulator, array element). accumulator initializes to the initial value you set, if not provided then it will initialize to your first array element. Afterwards, the accumulator will be the returned value of your callback fxn.
Array Methods: 1) add element to end 2) add element to beginning 3) remove element from beginning (and returns it) 4) remove element from end (and returns it) 5) convert to string 6) merge arrays
1) .push(elem, ...[elem]) : can add mult elements 2) .unshift(elem, ...[elem]) : can add mult elements 3) .shift() 4) .pop() 5) String(arr) *Push/Pop are much faster than Shift/Unshift - to shift/unshift, the engine has to remove the element in the beginning (.shift) & reassign the index numbers of all the other values, whereas in a pop/push, it does not need to update the indexes of all the other values 6) arrayBeingAddedTo.concat(elementBeingConcat'd)
1) What are falsy values? 2) What are truthy values?
1) 0, empty string "", null, undefined and NaN 2) all other values are truthy
How do you copy an array? What if the array contains a nested array?
1) Can use spread operator let b = [...a] 2) Can use array methods: map, filter, reduce as these return a new array w/ all or some values of orig array (and can modify the values at the same time) 3) Can use Array.slice method - normally used to return a subset of elements, when using array.slice() or array.slice(0), you will end up w/ copy of orig array - be aware of shallow vs deep copying as all of the above methods will generate a shallow copy
String comparison rules - Go!
1) Compare first character of both strings, first character is compared, and if one is greater or less than, we are done with comparing 2) If both first characters are the same, then we compare the second character the same way, each time done with comparing if they differ 3) If both strings end comparison at the same length, they are equal, otherwise the longer string is greater --> 'Bee' vs 'Be', Bee is greater 4) greater or less than is determined by Unicode order, a lowercase letter is always greater than a Uppercase letter
Reference an object key & value using both ways (what are those ways called?), and with a variable
1) Dot notation: user.name 2) Bracket notation: user['name'] / user["name"] 3) with a variable, can only use bracket notation: let key = "name"; user[key] //same as user["name"] can also declare like so: let fruit = "apple"; let bag = { [fruit]: 5, }; //bag.apple = 5, or bag["apple"] = 5, or bag[fruit] = 5
How to get the numerical code of a character in a string? How to get the character using its numeric code? How to compare strings?
1) INPUTSTR.codePointAt(pos) : pos is the position of the character in the string you want the numerical code for. so if your inputStr is only one character, pos would = 0 *this is how/why you can compare strings (lowercase is higher than capitalcase, but z will be higher than a) 2) String.fromCodePoint(code) : code = the numerical code of the character you want returned 3) str1.localeCompare(str2) : - returns negative number if str1 is less than str2 - returns pos number if str1 is greater than str2 - returns 0 if they are equivalent
String Methods: 1) upper and lower case 2) length of string 3) retrieving string character (syntax) 4) finding substring/existence 5) returning a substring without modifying original string 6) returning a string that modifies a substring with another substring, without modifying original string 7) checks if str contains substr 8) checks if str starts/ends with substr 9) returns a substring from a specified position to get a specified number of characters 10) method converts a string into an integer 11) method converts a string into a point number/decimal #
1) INPUTSTR.toUpperCase() || INPUTSTR.toLowerCase(); *remember str are immutable, orig str is not modified by these methods 2) INPUTSTR.length 3) INPUTSTR[index-of-substr/char-you-are-looking-for] || older vers: INPUTSTR.charAt(index) 4) INPUTSTR.indexOf('SUBSTR') || if === -1, does not exist *can also use the optional 2nd param to specify index of where to start searching 5) INPUTSTR.slice(startingIndex, [index after endingIndex - so up to but not including]) : if no 2nd arg, slice will return thru the end of the string negative indexes are str.length - negIndex counting backwards from end of str 6) INPUTSTR.replace(str-being-replaced, replacement-str) 7) INPUTSTR.includes(substr, [startPosition]) : returns true/false 8) INPUTSTR.startsWith(substr) || INPUTSTR.endsWith(substr) : returns true/false 9) INPUTSTR.substr(starting index, [length]) : returns substring of [length] length from starting index of input string, including starting index's character. Can use negative argument for starting index *note substr is technically a browser-only feature, so non-browser environments may fail to support it (in practice it works everywhere) 10) parseInt(inputStr, radix/base #) : if first character cannot be converted into a number, NaN is returned 11) parseFloat(inputStr) : if first character cannot be converted into a number, NaN is returned parseFloat('3.14random') vs parseFloat('random3.14')
Math methods! 1) round down 2) round up 3) round up or down to nearest int 4) What is an int? 5) square root 6) squared/to the power of (2 ways - what's the difference?) 7) whole numbers (remove anything after a decimal pt) 8) rounding to n digits after decimal 9) random number from 0 to 1 10) max / min
1) Math.floor() 2) Math.ceil() 3) Math.round() 4) an integer is a whole number (no decimals), positive or negative and includes 0 5) Math.sqrt() 6a) Math.pow(base, exponent) --> if base is negative AND exponent is not an integer, returns NaN (but it can be one or the other) 6b) base ** exponent Differences: ** isn't supported in Internet Explorer currently, and Math.pow( ) does not allow BigInt type values, whereas ** does 7) Math.trunc() 8) +NUMBER.toFixed(nDigitsAfterDecimal) : could also call Number instead of using unary plus operator || .toFixed 's result is a string. 9) Math.random() 10) Math.max() / Math.min()
How to create an array? (two methods)
1) Most commonly used: simply using [ ] 2) let arr = new Array( ) - this is rarely used, however it differs slightly from the [ ] method in that if you pass a single argument that is a number, then it creates the array without items, but with the given length - so if you try to call an array element, it will return undefined. With square brackets, it is the same thing (try creating empty array, assigning 5th element to be a value, then trying to call the 4th element - will return undefined)
Numeric conversion rules for: 1) undefined becomes... 2) null becomes... 3) true and false becomes... 4) string becomes...
1) NaN 2) 0 3) 1 and 0 4) whitespaces from start/end are removed; if remaining string is empty, string becomes 0; otherwise, number is read from the string, and if it's not a number it becomes NaN example: 4a: "123z" becomes NaN; 4b: " 123 " becomes 123
What is the spread syntax, what does it do, where does it go syntax-wise?
1) Spread Syntax: ... 2a) It expands an iterable object like an array into a list of arguments. Example: let arr = [3,5,1]; Math.max(arr) does not work because it expects a list of numeric arguments, not an array, and will return NaN Math.max(...arr) will expand arr array into numeric arguments, and now it will work and return 5. 2b) Can also merge arrays: Example: let merged = [0, ...arr1, 2, ...arr2] // merged = [0, all the values in arr1, 2, all the values in arr2] 2c) Can also turn a string into an array of characters (a string is an iterable object) let str = "Hello"; [...str] //str is = [H,e,l,l,o] 3) Spread syntax can be combined with normal values, referenced multiple times, and used wherever. example: (1, ...arr1, 2, ...arr2, 25)
What built-in function will: 1) show a message in the browser and not allow any other action until the message window has been dealt with, 2) Request text-box input from the user? 3) Request input from the user in the form of OK or CANCEL?
1) alert() 2) prompt() 3) confirm()
How do you test if a value is NaN? How do you test if a value is a regular number and not NaN, Infinity or -Infinity?
1) isNaN() converts argument to a number and tests if it's NaN - returns true if it is. *cannot use === NaN because it's a unique value and does not equal anything, including itself 2) isFinite() converts argument to a number and returns true if it's a regular #, returns false if it's NaN/Infinity/-Infinity
Write example of arrow function: 1) named 2) unnamed/anonymous 3) with one parameter 4) with multiple parameters 5) with no parameters
1) named, multiple param, one line: let bob = (x, y) => x+y; 2) anonymous, no param, multi line: () => { code line 1 code line 2 return result; }; 3) named, one param, one line: let bob = x => x*2; 4) anon, multi param, multi line: (x, y) => { code line1 code line 2 return blah; } 5) named, no param, one line: let bob = () => alert("Hello!");
When a constructor function is executed with the "new" keyword, what steps does the function go through?
1) new empty object is created and assigned to "this" 2) function body executes. Usually it modifies "this", adds new properties to it 3) the value of "this" is returned
When prompt() is used, and you try to convert to a number, what happens when: 1) User clicks cancel, what is returned? 2) User inputs a space, what is returned? 3) User inputs text, what is returned? 4) User inputs nothing and clicks OK, what is returned, and what is outputted if converted to a #?
1) null / when converted to number using + or Number( ), null is converted to zero 2) An empty string is returned, which is then converted to 0 3) NaN 4) returns empty string, which is converted to 0
True/False?: 1) null == undefined 2) null > 0 3) null == 0 4) null >= 0 5) what happens when using comparison operators on null/undefined? 6) undefined > 0 7) undefined < 0 8) undefined == 0
1) true (loosely equals to, special rule) 2) false (0 is not greater than 0) 3) false (equality checks do not convert/coerce null into 0) 4) true (null is converted to 0, 0 is > or = 0) 5) <, >, <=, >= used, null becomes 0 and undefined becomes NaN 6 - 8) false (undefined is converted to NaN, and NaN returns false for all comparisons, including NaN ==/= NaN)
What is the syntax of a constructor function, the purpose, and how should it be executed?
1) typically named with a capital letter first : function User(name){ this.name = name; this.isAdmin = false; } let user = new User("Jack"); //user.name = "Jack", user.isAdmin = false 2) constructor fxns are mainly used to implement reusable object creation code 3) Should be executed only with "new" keyword
How do you test for property existence in an object (there is a better test)?
1) use the "in" operator "key" in object : returns true if key exists or false if key does not exist in object use quotes if referencing key's name value; if no quotes JS assumes it's a variable 2) if a key does not exist and you try to read it, it will return undefined, and this test for existence could also work, except in cases when the key's value is undefined, therefore the "key" in object statement is better. Note that undefined should not be explicitly assigned though, as mostly null is used for unknown or empty values.
Boolean conversion rules for: 1) 0 2) empty string 3) null 4) undefined 5) NaN 6) any other values
1-5 = false, all others are true. " " is not an empty string as space is a character and would evaluate to true. "0" would evaluate to true as it's a string
What is the conditional or ternary operator, and its syntax?
? condition ? return something if true : return this if not true
What is the nullish coalescing operator? And what does it do?
?? provides a way to choose a defined value from a list of variables; result of: a ?? b is a, unless a is null/undefined, then b
Method to determine whether an object is an array. What does it return?
Array.isArray(objNameHere) returns true (if obj is an array) or false
Function declaration vs. expression: what are they, and how do they differ in code execution? Which is preferable and why?
Function declaration: a named function, separate statement in code Function expression: created as part of an expression; could be assigned to a variable, an anonymous fxn w/in an if/else or conditional statement. Function declarations are processed before the code block is executed, are visible everywhere in the block, a global function declaration is visible in the whole script because JS first looks for global function declarations and create the functions before running the script - therefore the line that invokes the function can be before the line that declares the function and still execute; function expressions are created when the execution flow reaches them, therefore if it is invoked before the function expression, it will return an error
Are objects ordered?
Kind of. Integer properties, which are strings that can be converted to/from an integer w/o a change, ie "41", "49", but not "1.2" - converted to 1, not same as 1.2 - etc., are sorted, while others are in creation order.
Difference between Object.keys/values/entries vs. for...in?
Object.keys only returns the object's own keys and not inherited keys for...in loop returns both own and inherited *enumerable* keys/properties - it will exclude properties of Object.prototype because they are not enumerable (have the enumerable:false flag) - this would include the .hasOwnProperty( ) method, the .toString( ) method etc.
How to get an array of keys? Values? Key-value pairs? How to reference a nested object's key-value pair?
Object.keys(objNameHere) Object.values(objNameHere) Object.entries(objNameHere) Object.entries(objNameHere)[indexOfKey-ValueYouWant] Example: newObject[ Object.values(otherObj)[0] ] = { Object.keys(otherObj)[1]] : Object.values(otherObj)[1] }
What is the rest parameter, what does it mean, where does it go syntax-wise, and how can it be used? What is the array-like object named arguments?
Rest parameter is just this: ... it means, gather all arguments, or remaining arguments, and store into an array. Example function (first, second, ...myArray) --> first and second arguments are passed in as variables, while the rest of the arguments after are stored in myArray array. Rest parameter must go at the end , always be last. Used when writing a fxn definition but you don't know how many arguments there will be. Allows fxn to be called with any number of arguments no matter how it's defined (and therefore not generate an error for "excessive" arguments) arguments array-like obj : when rest paramters did not exist in JS, arguments was the only way to get all arguments of the fxn. Downside is that arguments is array-like, but not an array, so you can't use array methods like .map.; also, always contains all arguments so you can't capture them partially like you can w/ rest parameters (see example with first, second, ...myArray); arrows fnxs do not have arguments object. Rest parameter is preferred
What is the optional chaining syntax, and what does it do?
Syntax: 1) obj?.prop - returns obj.prop if obj exists, otherwise undefined 2) obj?.[prop] - returns obj[prop] if obj exists, otherwise undefined 3) obj.method?.() - calls obj.method() if obj.method exists, otherwise returns undefined. ?. immediately stops or short-circuits the evaluation if the left part before ?. doesn't exist - so if there are any further fxn calls or side effects, they don't occur
Return from constructors: what do constructors usually do, and what happens if constructor function has a return statement?
Usually, constructors do not have a return statement as their task is to copy to "this" and "this" is the result. If return is called with an object, then object is returned instead of "this"; if return is called with a primitive, it's ignored. function BigUser() { this.name = "John"; return { name: "Godzilla" }; } alert( new BigUser().name ); // returns "Godzilla" b/c the return statement line with object name: Godzilla overrides "this"
What is the dunder proto? How is it used syntactically, and for what purpose?
__proto__ Used to access the internal and hidden [[Prototype]] property within an object. Is a property within an object that's hidden/internal, and contains the object's prototype object. It's a historical getter/setter for [[Prototype]] Example: to set the __proto__ to a specific object, you would do : rabbit.__proto__ = animal //sets rabbit.[[Prototype]] = animal You would say, animal is the prototype of rabbit, or rabbit prototypically inherits from animal. Properties of animal are inherited by rabbit. __proto__ is now deprecated, modern JS uses Object.getPrototypeOf / Object.setPrototypeOf Replaced with usage of .prototype / class and new syntax
What is this called? __proto__
dunder proto
Create a function multiplyNumeric(obj) that multiplies all numeric property values of obj by 2
function multiplyNumeric (obj) { for (let key in obj){ if (typeof obj[key] === "number") { obj[key] *= 2; } } }
.sort( ) method - syntax and how does it work
it applies a function to the array, returning an array that is sorted according to the function. the fxn takes in 2 parameters, the first and 2nd element of the array, running until it gets to the end of the array, however it can be invoked multiple times per element within the array Common example: numbers.sort(function(a,b) { return a-b; }); // this returns an array sorted in assending order comparefxn(a,b) returns values that are either less than 0, equal to 0, or greater than 0. This determines the sort order - if less than o, b is sorted before a. (think of a small array like [4, 2]: a = 4, b = 2, 4-2 = 2, by .sort rules 2 should go before 4. if no fxn is provided, then it will default to sorting the array elements per UTF-16 order