Top 5 Simple but Tricky JavaScript Interview Questions and Answers

My top stressing things in software development are:

  1. The coding interview
  2. A toxic manager or teammate

Not JavaScript, this, CSS, Internet Explorer, but the 2 above.

If you’re qualifying as Senior Developer that involves JavaScript, there’s a good chance that you will be asked for tricky questions during the coding interview.

I know it’s unfair. Some unknown people put you on the edge to see what you’re made of. It’s an unpleasant experience.

Top 5 Simple but Tricky JavaScript Interview Questions and Answers

What can you do?

Follow the advice: “Practice makes perfect”. By investing enough time, better regularly, to deeply understand JavaScript will improve your coding, and as a positive side effect, interviewing skills.

In this post, you will find 7 at first sight simple, but tricky JavaScript interview questions.

While at first the questions might seem random, they try to hook into important concepts of JavaScript. So you better practice them before your next interview!

1. Accidental global variable

Question

To what evaluates typeof a and typeof b in the following snippet:

function foo() {
  let a = b = 0;
  a++;
  return a;
}

foo();
typeof a; // => ???typeof b; // => ???

Answer

Let’s take a closer look at the line 2: let a = b = 0. This statement indeed declares a local variable a. However, it does declare a global variable b.

There is no variable b declared neither in the foo() scope or global scope. So JavaScript interprets b = 0 expression as window.b = 0.

Top 5 Simple but Tricky JavaScript Interview Questions and Answers

b is an accidently created global variable.

In a browser, the above code snippet is equivalent to:

function foo() {
  let a;  window.b = 0;  a = window.b;  a++;
  return a;
}

foo();
typeof a;        // => 'undefined'
typeof window.b; // => 'number'

typeof a is 'undefined'. The variable a is declared only within foo() scope and is not available in the outside scope.

typeof b evaluates to 'number'. b is a global variable with the value 0.

2. Array length property

Question

What is the value of clothes[0]:

const clothes = ['jacket', 't-shirt'];
clothes.length = 0;

clothes[0]; // => ???

Answer

length property of the array object has a special behavior:

Reducing the value of the length property has the side-effect of deleting own array elements whose array index is between the old and new length values.

Because of this length behavior, when JavaScript executes clothes.length = 0, all the items of the array clothes are deleted.

clothes[0] is undefined, because clothes array was emptied.

3. Eagle eye test

Question

What is the content of numbers array:

const length = 4;
const numbers = [];
for (var i = 0; i < length; i++);{
  numbers.push(i + 1);
}

numbers; // => ???

Answer

Let’s take a closer look at the semicolon ; that appears right before the opening curly brace {:

Top 5 Simple but Tricky JavaScript Interview Questions and Answers

It’s easy to overlook this semicolon, while it creates a null statement. The null statement is an empty statement that does nothing.

for() iterates 4 times over the null statement (that does nothing), ignoring the block that actually pushes items to array: { numbers.push(i + 1); }.

The above code is equivalent to the following:

const length = 4;
const numbers = [];
var i;
for (i = 0; i < length; i++) {
  // does nothing
}
{ 
  // a simple block
  numbers.push(i + 1);
}

numbers; // => [5]

for() increments i variable until 4. Then JavaScript enters one time the block { numbers.push(i + 1); }, pushing 4 + 1 to numbers array.

Thus numbers is [5].

My story behind this question

Long time ago, when I was interviewing for my first job, I was asked this question.

For the interview I was given 20 coding questions to answer within 1 hour limit. The null statement question was on the list.

When solving the question, being in a rush, I didn’t see the comma _;_ right before the curly brace _{_. So I answered incorrectly _[1, 2, 3, 4]_.

I was slightly disappointed because of such unfair tricks. I asked the interviewer what is the reason behind tricks like that? The interviewer replied:

“Because we need people that put high attention to detail.”

Fortunately, I didn’t end up working for that company.

I’ll leave the conclusion up to you.

4. Automatic semicolon insertion

Question

What value is returned by arrayFromValue()?

function arrayFromValue(item) {
  return
    [items];
}

arrayFromValue(10); // => ???

Answer

It’s easy to miss the new line between the return keyword and [items] expression.

The newline makes the JavaScript automatically insert a semicolon between return and [items] expression.

Here’s an equivalent code with the semicolon inserted after return:

function arrayFromValue(item) {
  return;  [items];
}

arrayFromValue(10); // => undefined

return; inside the function makes it return undefined.

So arrayFromValue(10) evaluates to undefined.

5. The classic question: tricky closure

Question

What will output to console the following script:

let i;
for (i = 0; i < 3; i++) {
  const log = () => {
    console.log(i);  }
  setTimeout(log, 100);
}

Answer

If you didn’t hear about this tricky question before, most likely your answer is 0, 1 and 2, which is incorrect. When I first tried to solve it, this was my answer too!

There are 2 phases behind executing this snippet.

Phase 1

  1. for() iterating 3 times. During each iteration a new function log() is created, which captures the variable i. Then setTimout() schedules an execution of log().
  2. When for() cycle completes, i variable has value 3.

log() is a closure that captures the variable i, which is defined in the outside scope of for() cycle. It’s important to understand that the closure captures i variable lexically.

Phase 2

The second phase happens after 100ms:

  1. The 3 schedulded log() callbacks are called by setTimeout(). log() reads the current value of variable i, which is 3, and logs to console 3.

That’s why the output to the console is 3, 3 and 3.

Do you know how to fix the snippet to log _0_, _1_, and _3_? Please write your solution in a comment below!

Bonus

1. Floating point math

Question

What’s the result of the equality check?

0.1 + 0.2 === 0.3 // => ???

Answer

First, let’s look at the value of 0.1 + 0.2:

0.1 + 0.2; // => 0.30000000000000004

The sum of 0.1 and 0.2 numbers is not exactly 0.3, but slightly above 0.3.

Due to how floating point numbers are encoded in binary, operations like addition of floating point numbers are subject to rounding errors.

Simply put, comparing floats directly is not precise.

Thus 0.1 + 0.2 === 0.3 is false.

Check 0.30000000000000004.com for more information.

2. Hoisting

Question

What happens if you access myVar and myConst before declaration?

myVar;   // => ???myConst; // => ???
var myVar = 'value';
const myConst = 3.14;

Answer

Hoisting and temporal dead zone are 2 important concepts that influence the lifecycle of JavaScript variables.

Top 5 Simple but Tricky JavaScript Interview Questions and Answers

Accessing myVar before declaration evaluates to undefined. A hoisted var variable, before its initialization, has an undefined value.

However, accessing myConst before the declaration line throws a ReferenceError. const variables are in a temporal dead zone until the declaration line const myConst = 3.14.

Anyways, most of these questions can truly assess if you are seasoned in JavaScript. If you had difficulties to answer some while reading the post, it’s a good indicator of what you must study next!

Is it fair to ask tricky questions during the interview? Let me know your opinion.

#javascript #interview-questions

Top 5 Simple but Tricky JavaScript Interview Questions and Answers
35.60 GEEK