JavaScript Reinforcement Practice
Here are a set of problems designed to help you reinforce and retain some useful JavaScript knowledge. If you are an Anki or Quizlet fan, consider adding some of these questions into a deck. đ
Who created JavaScript and in what year?
Brendan Eich, 1995
What was JavaScript originally called?
Mocha
Why was JavaScript created?
Because Java, the language that was supposed to ârun code in the browser,â turned out to be too heavy and too slow for this purpose
How do you write a line of text to the console?
console.log(sometext)
How do you change the text of an element in a web browser document?
element.textContent = sometext
How do you access the third command line argument of a script, run on the command line, with node?
process.argv[2]
Name the 8 data types of JavaScript (as of ES2020).
Undefined, Null, Boolean, Number, String, Symbol, BigInt, Object
What is the difference between boss === null
and boss === undefined
?
boss === null
means there is in fact no boss. boss === undefined
indicates the boss may or may not exist, is unknown even if it does exist, or itâs no oneâs business whether it exists or not, or who it is if it does.
How can you tell whether a number (a regular number, not a BigInt
) is an integer or not?
Number.isInteger(x)
What are safe integers in JavaScript?
Values of the Number type that are exactly representable and are the (IEEE-754 double) representation of exactly one integer. (Aside: this range is -9007199254740991 to 9007199254740991.)
If x
has the value NaN
, what is the value of the expression x === NaN
? Why? What is the correct way to determine if an expression has the value NaN
?
Itâs false
because ===
by definition produces false
when one of its operands is NaN
. You need to invoke isNaN(x)
What is the best expression for finding the distance between the âpointsâ [x1, y1]
and [x2, y2]
?
Math.hypot(x2 - x1, y2 - y1)
How can you tell whether string s
is a substring of string t
?
t.includes(s)
What are the string methods for padding and trimming?
padStart
, padEnd
, trimStart
, trimEnd
, and trim
What two things can you do with backtick-delimited strings you canât do with strings delimited with apostrophes or quotation marks?
(1) Interpolate and (2) represent multiline strings directly
Why does "đ¤Ł".length
have the value 2?
The length
method counts UTF-16 code units, not characters
Give an example that shows the ==
operator is not transitive.
"0x10" == 16
, 16 == "16"
, "0x10" != "16"
Why is 2 && 3
equal to 3, but 2 & 3
equal to 2?
The former is a short circuit logical AND: since 2 is truthy it produces 3; the latter is just binary AND, and you can see that 0b0010 & 0b0011 === 0b0010
Name all the falsy values in JavaScript.
undefined
, null
, false
, +0
, -0
, 0n
, NaN
, ""
Name all the nullish values in JavaScript.
undefined
, null
What is a more concise way to write x ? x : y
?
x || y
What is a more concise way to write x ? y : x
?
x && y
Why is it better to use ??
than ||
to represent the idea of a âdefault valueâ?
Using myValue || defaultValue
would produce the default value if myValue
were 0, false, or the empty string, but these are very likely acceptable values. myValue ?? defaultValue
only produces the default for null
and undefined
How do you determine the type of an expression at runtime?
typeof(e)
How do you determine the âclassâ of an object?
o.constructor
When should you use let
and when should you use const
?
Bind with let
if you will be changing the value bound to the indentifier; bind with const
when the binding should be permanent
When should you use var
?
Never
What bad things can happen if you forget to use let
, const
, or var
when declaring an identifier?
A non-local variable of the same name will get overwritten (yikes!), or a new (unexpected) global variable will be created
What is the difference between p.x
and p[x]
?
p.x
accesses the property of p
named "x"
; p[x]
accesses the property of p
whose name is the value stored in the variable x
What is the object literal { x, y }
a shorthand for?
{ x: x, y: y}
What happens in the expression player.coach.address.city
if any of the properties are missing or null? How do you write this expression to produce undefined
or null
in this case?
A TypeError
will be thrown. Write player?.coach?.address?.city
instead
If x === 'y'
then what is { x: 3, [x]: 5 }
?
{x: 3, y: 5}
Why is [1,12] < [1,3]
true but [1,42] < [1,3]
false?
The <
operator compares strings unless both operators are numbers. So the first conversion is actually "1,12" < "1,3"
which is true, but the second is "1,42" < "1,3"
and is false because "4"
is larger than "3"
What is the difference between a deep copy and a shallow copy?
A shallow copy produces a new object containing copies of the source objectâs property values, which, if these values are pointers, copy only the pointers themselves. A deep copy is recursively makes copies of objects that are referenced by pointers in the source object structure.
What is the spread operator?
An operator that âspreads outâ, âunpacksâ, or âexplodesâ array values or object properties into multiple entities so they can be inserted into other arrays or others or passed as multiple arguments instead of as one
How do you write an object to the console (beautifully formatted)?
console.table(someobject)
Describe how a prototype-based language (like JavaScript) differs from a class-based language (like Java), in terms of thinking about collections of objects that share the same structure and behavior.
In a class-based OO language, a Point class is not a point, but rather a factory for making points. In a prototype-based language, you start with an actual point object, and derive new points from it (usually by cloning or referring back to the original with a prototype link)
Properties defined directly within an object are called ________________ properties. Properties of an object accessible from the objectâs prototype chain are called ________________ properties.
Own; inherited
If p === {x: 1, y: 8}
what is Object.entries(p)
?
[ [x, 1], [y, 8] ]
If a == ["x", "y"]
what is a.entries()
?
An iterator that produces [0, "x"]
and then [1, "y"]
What do we mean when we say arrays are objects in JavaScript?
All types other than the seven primitive types in JavaScript are objects, hence arrays are objects; in particular, arrays have properties 0, 1, 2, ... (and length
, among others)
Describe how splice
works.
It deletes zero or more elements from a given position in an array and optionally replaces these values with (an arbitrary number of) new elements. It returns the deleted elements in a new array
How is using a spread operator inside [
and ]
different from using it inside {
and }
?
Spreading an array into an array spreads the array values only; Spreading a non-array object into an array cannot be done. Spreading into a non-array object ({ }
) spreads both the property names and values
You might often see the expression a.slice()
, for some array a
. What does this expression do, exactly?
It makes a shallow copy of a
How does one best create an array of size 100 in which every element is 0? (Do not write a loop.)
Array(100).fill(0)
How does one create an array of 50 random numbers with a loop?
const a = []; while (a.length < 50) { a.push(Math.random()) }
How does one create an array of 50 random number without a loop?
Array(50).fill().map(Math.random)
Write an equivalent expression to a.concat(b)
, where a
and b
are arrays, using spreads.
[...a, ...b]
a.push(x)
mutates a
. How do you do a non-mutating âpushâ?
[...a, x]
What does unshift
do? Does it mutate or not? What does it return?
Adds an item to the front of an array; yes it mutates; it returns the new length of the array.
What is the difference between s.split('')
and [...s]
for a string s
?
The split
method splits into code units; the spread operator splits into characters
In many languages, assignment has the form identifier = expression. In JavaScript, the left hand side is not just an identifier. What exactly is the left hand side called?
A pattern
In let {r: c, q: [, y, {p}]} = {q: Array(5).fill({p:5, q:1}), r: 13, s: true}
what variables are being declared and to what values are they being initialized? Or is there an error?
r === 13
y === {p: 5, q: 1}
p === 5
What is the difference between value types and reference types?
Values of value types are actual values and behave as if they are always copied; values of reference types are references to other values, generally resulting in less memory usage and allowing âsharingâ to be utilized
Why do you think the JavaScript designer decided that objects should be reference types?
It is a good default, because for massive objects, copying them can be very expensive, and therefore a programmer would have to go out of their way to say they want an expensive copy
Since strings can be very large, you might think strings would be reference types in JavaScript. After all, they are reference types in Java. But in JavaScript, they are considered primitive (value) types. This might lead you to believe JavaScript is necessarily slow because strings are always copied on assignment. However, this is not the case! Why?
You donât need to copy them because they are immutable! So behind the scenes they are probably implemented as references, but the programmer will never know the difference because they canât change the contents (which is the only way to distinguish copying from sharing).
Write an IIFE that applies, to the argument 100, the anonymous arrow function that squares its argument.
(x => x ** 2)(100)
In the function definition function f(x, y) { return [x, y]; }
, what do we call x
and y
?
Parameters
In the function call f(y, z)
, what do we call y
and z
?
Arguments
A function is called higher-order if it does at least one of two things. What two things?
Accept functions as arguments; Return a function
What do the array methods map
, filter
, every
, some
, find
, and findIndex
do?
Write an expression to compute the product of the cubes of the odd numbers in an array numbers
, using filter
, map
, and reduce
?
numbers.filter(x => x % 2 === 1).map(x => x ** 3).reduce((x, y) => x * y, 1)
Write the function function f(x = 3) { return x * y }
(where y
is some global variable) without using a default parameter.
function f() {
if (x === undefined) {
x = 3
}
return x * y
}
What is a rest parameter?
A parameter that rolls up all the excess arguments into a single array. If there are no excess parameters the parameter value will be an empty array
Can a function definition have multiple rest parameters? Why or why not?
No, you wouldnât know how many excess arguments to give each parameter (unless the language made up a weird rule, but it would be hard to remember and likely not useful in practice)
One could argue that all non-default parameters are really default parameters. Why?
They have a default value of undefined
!
The old-fashioned way to write a function that takes in an array and returns the sum of its first and third elements is: function f(a) {return a[0] + a[2];}
Rewrite this in a modern fashion, where the function parameter is a pattern.
function f([x, ,y]) {
return x + y
}
Write a function that takes in an object and returns the product of its x
and y
properties. If no argument is passed, return 1. Write the function using a pattern for its parameter. Supply defaults so the function body is simply return x * y
.
function product({ x = 1, y = 1 }) {
return x * y
}
Show how to declare the function that is called like this: push({onTheStack: s, theValue: v})
? Use an object pattern in the parameter list.
function push({ onTheStack, theValue })
What are global scope, function scope, and block scope?
How do let-bound and var-bound function-scope variables differ? (Make sure the phrase âtemporal dead zoneâ appears in your answer.)
Accessing var
-bound function scope variables produce undefined
in the temporal dead zone; accessing let
-bound function scope variables throw a ReferenceError
Write a function that takes in a number and returns a function that adds that number to its argument. Is the function you wrote higher-order? Why or why not? Does that function illustrate a closure? Why or why not? Does that function illustrate currying? Why or why not?
What is currying good for, anyway?
Partial application. You can do the computation on the first (few) arguments just once and apply that over and over again in the future
Is JavaScript statically-scoped or dynamically scoped?
Static
Do JavaScript functions exhibit shallow binding or deep binding?
Deep
Given function* f() {yield 1; yield 2; yield 3;}
, what is wrong with writing for (let x of f) {console.log(x)}
?
The function f
is not iterable, but f()
is
What is the receiver of a method call?
The object on which the method is called, for example, in the expression scores.push(99)
, the receiver is scores
.
Why must (pretty much all reasonable) methods be non-arrow functions?
If itâs a method, itâs more than likely using the this
expression which you want to refer to the receiver. An arrow functionâs this
does not refer to the receiver
Why should callbacks generally be arrow functions?
You generally donât want the this
expression to refer to the callback function itself, but rather get its value from the surrounding context
What does the expression this
refer to inside of a function called with the new
operator?
The object being created
Is this
early-bound or late-bound?
Late bound
For function f
and object x
, the expressions f.call(x, 1, 2)
and f.apply(x, [1, 2])
produce the same result. Write the equivalent expression using bind
.
f.bind(x)(1, 2)
JavaScript doesnât have classes, but it does have the keyword class
, which declares a function. How is this âfunctionâ defined? Give a short example.
The function is defined with the pseudo-method named constructor
.
class Box {
constructor(contents) { this.contents = contents }
}
What happens under the hood when you write class A extends B
? In particular what does A.prototype
look like in this case?
The prototype of A.prototype
is set to B.prototype
How do you make a JavaScript object without a prototype?
Object.create(null)
When would you see a TypeError
thrown? A RangeError
? A SyntaxError
? A ReferenceError
?
- TypeError: when an operandâs type is not as expected and JavaScript will not coerce
- RangeError: when numeric operands are too big or too small, e.g.
Array(-5)
- SyntaxError: when interpreting syntactically invalid code, e.g. in
eval
- ReferenceError: when referencing a non-existent variable
What is callback hell?
The ugly and complicated nesting that arises from callbacks within callbacks
What are two advantages of promises over callbacks?
(1) No callback hell, as promises are elegantly âchainedâ. (2) Error handling is much simpler: a single catch will do!
What are the three states a promise can be in?
Pending, Fulfilled, and Rejected
What exactly is a promise?
An object representing a computation that may or may not be completed yet
What does the function async function five() { return 5; }
actually return?
A promise that resolves to 5
Given let f = async x => 1
and let g = async => 2
what do the expressions f()
and g()
return? Why? Why is the definition of g
even acceptable?
f()
returns a promise that fulfills to 1. g()
just returns 2, because async
is not actually a reserved word, so g
is a function with one parameter, werdly named async
. The parameter is ignored and 2 is returned.
What is the sole parameter of the Promise
constructor and what kind of object is it?
Itâs called an executor and it is itself a function of two parameters, called resolve
and reject
, which are themselves functions. The body of the executor performs the asynchronous computation and calls resolve
or reject
as needed.
What is the difference between p.then(f, g)
and p.then(f).catch(g)
for a promise p
?
In the latter, any errors in f
will be âcaughtâ by g
Why do most API invocations, or operating system calls (like reading and writing files), take in callbacks or return promises?
They take an indefinite and possibly long time to complete
Give the expression, in client-side JavaScript using fetch
, that hits the (hypothetical) endpoint https://api.example.com/fortunes?limit=5
and, from its JSON response, places the first result in the DOM into the element with id fortune
.
fetch("https://api.example.com/fortunes?limit=5")
.then(response => response.json())
.then(fortunes => document.getElementById("fortune").textContent = fortunes[0])
Give a client-side function that hits the (hypothetical) endpoint https://api.example.com/fortunes?limit=5
and, from its JSON response, places the first result in the DOM into the element with id fortune
.
async function showFirstFortune() {
const response = await fetch("https://api.example.com/fortunes?limit=5")
const fortunes = await response.json()
document.getElementById("fortune").textContent = fortunes[0]
}
Does await
actually wait (block) for anything? It not, what exactly does it do?
Well, kind of. It definitely pauses the execution flow of the currently executing function, but other computations can run during the pause (it doesnât block the entire script). The function is able to continue after an awaited promise is settled.
How does one âwaitâ for a whole bunch of async functions to all âfinishâ?
Promise.all
or Promise.allSettled
What are the two kinds of property descriptors, and how do they differ?
A data descriptor gives the value of a property, whether the property is writable (or not), enumerable (or not), and configurable (or not). An accessor descriptor gives the propertyâs getter and setter functions, and whether the property is enumerable (or not) and configurable (or not)
How do you make a property read-only?
Set its writable
attribute to false
What is the difference between sealing and freezing an object?
Freezing makes the properties all read-only; you can still overwrite the properties of a sealed object.
How do you get the prototype of an object?
Object.getPrototypeOf(someobject)
How do you set an objectâs prototype after the object has already been created?
Object.setPrototypeOf(someobject, newPrototype)
What is the difference between Object.keys
and Object.getOwnPropertyNames
?
keys
only returns the enumerable own property names, while getOwnPropertyNames
returns all of them, whether enumerable or not.
Given x = { a: 3, [Symbol('y')]: 5 }
, what are the values returned by Object.keys(x)
and by Object.getOwnPropertyNames(x)
? How do you get the own properties that these miss?
They both return [ 'a' ]
. To get the other property, use Object.getOwnPropertySymbols(x)