JavaScript: Predict the Output Questions vol. 2

Elizabeth Westphal
4 min readFeb 7, 2022

Let’s run through some interview style questions that are a bit different from the standard blackboard interview questions you might find on LeetCode or AlgoExpert. Predict-the-output questions show your interviewer your level of understanding of the language — a skill not tested by data structure and algorithms questions.

Below are four problems, their answers, and step-by-step explanations for each. You’ll get the most out of these problems if you try to solve them yourself before scrolling to the answer.

Problem 1:

Take a look at the code below, what is logged to the console after the function call on line 8?

Answer:

The console should read “undefined”, followed by something like “error: Uncaught ReferenceError: Cannot access ‘major’ before initialization”.

Let’s look at what is happening. We declared name with the var keyword, which allows hoisting. What this means for variables is that memory space is set aside for the variable before execution and by default is given the value of undefined, but there’s a catch — the value of “Elizabeth” isn’t assigned until line 4. Name still holds a value of undefined, so this is what is logged to the console.

The major variable is defined using the let keyword. Variables using the let keyword are also hoisted, so why do we get an error? In fact, all variable declarations support hoisting in JavaScript. The key difference is that var supports initialization, while let and const do not. The variable is not accessible before the line we declare, or “initialize” it. This span between the creation and initialization of a variable is known as the “Temporal Dead Zone” and variable cannot be accessed in this space. Since major is not initialized until line 5, an error is logged to the console.

Problem 2:

Run through the code below, what is logged to the console on line 6?

Answer:

If you guessed ‘33’ you’d be correct. The function uses the + operator to add together 3 values and return the result. As we have seen before it is important to remember order of execution. You may have seen the string parameter and thought the output is ‘123’ because numbers get concatenated to strings. The equation will operate from left to right, one parameter at a time. This means 1+2 is treated as a mathematical equation, resulting in 3. The…