JavaScript Flashcards
What is JavaScript?
JavaScript is a single-threaded, multi-paradigmed (OOP and FP), interpreted, programming language
What is the difference between let
, const
, and var
?
let
and const
are blocked scoped. var
is function scoped no matter how deeply it may be nested inside that function.
What is the difference between a first-class and higher-order function?
A first-class function is a function that can be used just like any other variable. For example, a first-class function can be assigned to a variable, passed as an argument to another function, and even even be returned by a function. A higher-order function is a subset of a first-class function; it can only be passed to and returned by other functions
What is JS’s most popular execution environment?
The browser
What are the 7 primitive types and what are their associated bits?
- number (64 bit double)
- bigInt (arbitrary bit integer)
- boolean
- string (16 bit unicode)
- null
- undefined
What is the result of the following code:
NaN === NaN
The result is false. This is because NaN
is not equal to any other value, including itself. Use Number.isNaN(x)
instead
What is the behavior of ===
for primitives and reference types?
Primitives:
- Test to see if 2 values are the same
Reference Types:
- Test to see if 2 reference variables point to the same object in the heap
Are strings iterable?
Yes
What are the 2 ways to access a character of a string at a given index?
1. str.charAt(index); 2. str[index];
Code an example of a template literal
let name = "Gianmarco"; Console.log(`Hello, ${name}!`)
Which 5 values evaluate to false and which values evaluate to true?
Evaulate to false:
* null
* undefined
* NaN
* 0
* “”
Evaluates to true:
* Everything else
What is the global object for all JS code inside a browser?
Window
What is the default value for uninitialized variables?
undefined
Code an example of a destructuring assignment
let [x, y] = [1, 2]; // variable names do not have to match console.log(x, y); // 1 2 let {x, y} = {x: 0, y:0} // variable names must match, else undefined console.log(x, y) // 0 0
Code an example of the 2 different ways to access an object’s property
let obj = {x:0, y:0}; console.log(obj["x"]); // 0 console.log(obj.x); // 0
What is the behavior of optional chaining?
a?.b;
If a
is not null
or undefined
, access b
. Else, return undefined
All objects are instances of which class?
Object
What do the following expressions return?
1 && 2; 0 && 1; 1 && 0;
1 && 1
returns 2
. This is because if both values are true, the right operand is returned
0 && 1
returns 0
. This is because if the first value is false, the expressions short circuits and returns it
1 && 0
returns 0
. This is because 1
is true so the operator returns the right operand
Code a function using a default parameter value
function f(x = 0) {...}
What is the behavior of the nullish coalescing operator?
a ?? b;
If a
is null
or undefined
, return b
. Else, return a
What does the following code return?
let result = "x" in {x: 0}; console.log(result);
function
What is the behavior of the following code?
let obj = {x:0, y:0}; delete obj.x; console.log(obj);
Deletes the x
property of obj
{y:0}
What is the behavior of the following code?
let arr = [1,2,3]; delete arr[0]; console.log(arr.length); console.log(typeof arr[0]);
Deletes the first element of arr
causing it to become a sparsed array. It’s length will remain at 3 but its first element will be undefined
Code 2 examples using the in
operator. 1 for an array, and the other for an object
let arr = ["a","b"]; console.log(0 in arr); // true let obj = {x:0, y:0}; console.log("x" in obj); //true
What is the difference between the for/of and for/in loop?
The for/of loop iterates over the elements of an iterable and therefore, cannot be used on non-iterable objects. The for/in loop iterates over the properties of both iterables and non-iterable objects
Are ES6 modules automatically strict code?
Yes
What is the behavior of the following code?
"use strict"; function f() {console.log(this);} f();
f()
prints undefined
. That is because in strict mode, f()
is invoked as a regular function and not a method
Summarize the behavior of a hoisted function
A hoisted function is a function that can be called before its definition. This is because function definitions are parsed before function calls
What are the 2 types that are allowed to be object properties?
- Strings
- Symbols
What is the behavior of the following code?
let obj = {x: 0, x:1}; console.log(obj);
The code will pring {x:1}
because later properties with the same name will override earlier ones
What are the 3 different property attributes available?
- writable: can be set
- enumerable: can be iterated
- configurable: can be deleted or changed
Code an example of instantiating an object with the following prototype object: {x: 1, y:2}
let obj = Object.create({x: 1, y:2}); console.log(obj.x, obj.y);
What is the utility method to serialize a JS object into a JSON object and what is the method to deserialize a JSON object into a JS object?
JSON.stringify()
JSON.parse()
What is the behavior of the spread operator?
[..."ab"]; [...{x:1, y:2}]; {...{x:1, y:2}};
[..."abc"]
returns ["a", "b"]
since "ab"
is an iterable
[...{x:1, y:2}]
returns an error since objects are not iterables
{...{x:1, y:2}}
returns {x:1, y:2}
since using the spread operator on an object only works if it’s used inside another object
What is the behavior of the following code?
const arr = new Array(); arr.push(1); arr.push(2); arr.push(3); const squares = Array.from(arr, (e) => e*e); console.log(squares);
Array.from()
copies the elements from arr
after transforming them
Code an example of removing the 2
in the [1,2,3]
array without causing it to become sparse
const arr = [1,2,3]; arr.splice(1,1); console.log(arr);
Does the following code return the same or new array?
let arr = [1,2,3]; arr.map(e => e*e);
arr.map()
returns a new array
What is the behavior of arr.filter()
?
The function defined inside filter
should return true
or false
. If true
, the value is added to a new array. Else, the value is ignored
What is the behavior of the following code?
const obj = { f() { const g = () => console.log(this); g(); } } obj.f();
When obj.f()
is called, the lambda will inherit the this
value of its enclosing scope f()
which evaluates to obj
. Therefore, the lambda inside f()
will print obj
Is the following code valid?
const rectangle = (width, height=width*2) => ({width, height});
Yes. In JS, method parameters can use the values of previous method parameters
What is a set in JS?
A set is an ordered collection of unique elements. Elements are considered equal if they refer to the same object (===
)
What is a Map?
A Map is an ordered collection of key-value pairs. Each key is unique
What is JS’s top error class?
Error
Code an example of a callback function
setTimeout(() => console.log("Hello, world!"), 3000);
What is a promise?
A promise is an object that represents the future result of an asynchronous operation
What is the behavior of the following code?
asyncFunction() .then((result1) => return value/promise) .then((result2) => console.log(result)) .catch((error) => console.log(error));
asyncFunction
immediately returns a promise. If the promise is fulfilled, then()
is invoked. then()
invokes the callback function passing in the result of the fulfilled promise as an argument. If any errors come up in either asyncFunction
or the callback function of then()
, catch()
is invoked. catch()
invokes its callback function passing in the error as an argument
What are the 5 different possible states of a promise?
- Fulfilled
- Rejected
- Pending (neither fulfilled nor rejected, operation still in process)
- Settled (fulfilled or rejected)
- Resolved (callback value or promise is returned to match the state of another promise)
What is the behavior of the following code?
asyncFunction() .then(() => throw new Error();) .catch(e => console.log(e))
When the callback function in then()
throws an error, the promise is rejected and catch()
will be invoked
Is the following code valid?
startAsyncOperation() .then(doStageTwo) .catch(recoverFromStageTwoError) .then(doStageThree) .then(doStageFour) .catch(logStageThreeAndFourErrors);
Yes. Multiple catch()
methods can be used
What is the purpose of promise.all([promise1, promise2])
?
To take in an array of promises and returns a promise. The returned promise will be rejected if any of the input promises are rejected. Otherwise, it will be fulfilled with an array of the fulfillment values of each of the input promises
Study the following code:
// We start with an array of URLs const urls = [ /* zero or more URLs here */ ]; // And convert it to an array of Promise objects promises = urls.map(url => fetch(url).then(r => r.text())); // Now get a Promise to run all those Promises in parallel Promise.all(promises) .then(bodies => { /* do something with the array of strings */ }) .catch(e => console.error(e));
What is the difference between promise.all()
and promise.allSettled()
?
Does the following code block the execution of subsequent code?
let response = await fetch("/api/user/profile"); // subsequent code...
No. await
is used to imply that fetch is an asynchronous operation but it does not block subsequent code.
Where is the await
keyword aloud to be used?
Inside async
functions. For example:
async function() { let res = await fetch(...); return res; }
Does an async
function return a promise?
Yes
Why is it important to write asynchronous front-end applications?
Since JS is single threaded, how is it possible for it to write asynchronous programs?
What is a callback function?
A callback function is a function that is passed to another function with the expectation that the callback function will be called at a later time. Callback functions used to be the primary way of implementing asynchronous programs in JS. However, in modern days, JS now uses promises
Is it possible to add new methods to instances of classes at runtime?
Yes. For example:
Complex.prototype.conj = function() { return new Complex(this.r, -this.i); };
At a high level, how is inheritance implemented in JS?
Inheritance is implemented through prototype objects. Two objects that inherit the properties of the same prototype object are considered instances of the same class
What is the difference between first-class and higher-order functions?
First-class functions are functions that can be used just like any other variable. Higher-order functions are functions that can be passed other functions. All first-class functions are higher-order functions but not all higher-order functions are first-class functions
All objects have a prototype but not all objects have a prototype property. What kind of objects have a prototype property?
Functions. This is why all objects created by the same constructor function inherit from the same prototype object and are considered instances of the same class