DEV Community

Cover image for JavaScript Tricky Interview Questions 2023
Mainul Hasan
Mainul Hasan

Posted on • Edited on • Originally published at medium.datadriveninvestor.com

JavaScript Tricky Interview Questions 2023

A developer interview without JavaScript questions? That’s hard to believe 😃 And it’s not surprising tricky questions are asked from a few common categories in multiple interviews.

But why do interviewers ask these questions? Because they often arise in real-world situations! Here’s how:

1. Type Coercion in Web Development

Understanding type coercion is pivotal while building web applications, especially during string manipulations and URL formations.

What output would you expect?



console.log([] + []);
console.log([] + {});
console.log({} + []);
console.log({} + {});


Enter fullscreen mode Exit fullscreen mode

Answer:

  • "" (Empty string)

  • "[object Object]"

  • 0 (In browsers, due to peculiarities of the unary + operator)

  • NaN

JavaScript type coercion can give unexpected results, especially with complex types like arrays and objects.

2. Precision Dilemma in Financial Apps

Even a slight discrepancy can lead to significant issues when working on finance-based applications.

Is 0.1 + 0.2 equal to 0.3?



console.log(0.1 + 0.2 === 0.3);


Enter fullscreen mode Exit fullscreen mode

Answer: false

Precision issues with floating-point arithmetic means 0.1 + 0.2 results in a number slightly more than 0.3.

3. JavaScript’s Automatic Semicolon Insertion

Have you ever thought why a function that seemed to work correctly gave you unexpected results? The behavior of semicolons in JavaScript might be the culprit.

What does the following function return?



function getNumber() {
  return 
  {
    value: 23
  };
}
console.log(getNumber());


Enter fullscreen mode Exit fullscreen mode

Answer: undefined

Automatic Semicolon Insertion causes the return to be treated as a standalone statement, so the function returns undefined.

4. Variable Hoisting Mysteries

A deep grasp of hoisting is vital, especially when initializations don’t behave as expected.

Can you figure out what’s wrong?



var x = 21;
var girl = function () {
    console.log(x);
    var x = 20;
};
girl();


Enter fullscreen mode Exit fullscreen mode

Answer: undefined

Due to variable hoisting, the variable x inside the function is declared but not initialized when console.log is executed. Therefore, its value is undefined.

5. Tricky Increment Operations

Simple arithmetic can sometimes confound developers.

Can you predict the output?



var num = 8;
function fun() {
    num += 7;
    num--;
    console.log(num);
}
fun();


Enter fullscreen mode Exit fullscreen mode

Answer: 14

The function first adds 7 to num (resulting in 15) and then decrements it by 1.

6. Elusive Comma

When writing a script for sequential data processing, it is sometimes important to know how to do more than one thing on a single line.

Do you know how it evaluates its operands?



var val = (1, 2, 3, 4);
console.log(val);


Enter fullscreen mode Exit fullscreen mode

Answer: 4

The comma operator evaluates each of its operands and returns the value of the last one.

7. Scope in Large-Scale Applications

When dealing with large applications using multiple libraries, correctly scoping variables becomes crucial.

Consider the following code:



var b = 5;
(function foo() {
    var b = 6;
    console.log(b);
})();
console.log(b);


Enter fullscreen mode Exit fullscreen mode

Answer:

  • 6

  • 5

The IIFE (Immediately Invoked Function Expression) has its own scope, and the variable b inside foo does not affect the outer variable b.

8. Context Handling in Modern Web Frameworks

In modern web app development, especially with frameworks like React, maintaining context for callbacks is essential.

Why might this callback lose its context?



let obj = {
  value: 'hello',
  print: function(callback) {
    callback();
  }
};

function sayValue() {
  console.log(this.value);
}

obj.print(sayValue);


Enter fullscreen mode Exit fullscreen mode

Answer: undefined

The sayValue function is called without context, so this.value doesn't refer to obj.value.

9. Order Matters in Script Loading

When building with a plugin-based architecture, the way in which scripts are loaded becomes very important.

Can you figure out what the problem is with this code?



function bar() {
    return foo;
    foo = 10;
    function foo() {}
    var foo = '11';
}
console.log(typeof bar());


Enter fullscreen mode Exit fullscreen mode

Answer: function

Due to hoisting, the function declaration of foo is moved to the top, above the return statement, making it the value that gets returned.

10. Handling Sparse Arrays in Reservation Systems

Sparse arrays may be a concern when designing systems such as theater seat reservations.

How does JavaScript handle sparse arrays in this example?



var a = [1, 2, 3];
a[10] = 10;
console.log(a[6]);


Enter fullscreen mode Exit fullscreen mode

Answer: undefined

The array a now has a length of 11, but only indices 0-2 and 10 have values. All others are undefined.

11. Parsing Operations in Dynamic Forms

In dynamic survey forms, data operations based on user input can become tricky.

Can you explain the output?



let arr = [1, 2, 3];
let res = arr.map(parseInt);
console.log(res);


Enter fullscreen mode Exit fullscreen mode

Answer: [1, NaN, NaN]

map passes three arguments to the callback: (currentValue, index, array). parseInt can take two arguments: string and radix, which causes unexpected results.

12. CMS and Variable Assignments

Working within a CMS may require on-the-fly variable definitions based on user inputs.

What’s the output of this code?



let a = (b = 3) - 3; 
console.log(a, typeof b);


Enter fullscreen mode Exit fullscreen mode

Answer: 0, "number"

The value of b is set to 3, and then subtracted, leaving a as 0 and b as a number.

13. Temporal Dead Zones

Frameworks like React and Vue require a clear understanding of block-scoping.

What would this code output and why?



console.log(typeof undeclaredVariable);
console.log(typeof y);
let y = 1;


Enter fullscreen mode Exit fullscreen mode

Answer:

  • "undefined"

  • Throws a ReferenceError

Even though let and const declarations are hoisted, they're not initialized, causing a temporal dead zone.

14. Shared State in UI Components

While creating UI libraries, ensuring individual components don’t share unintended state is critical.

What will the following code log?



let arr = new Array(3).fill([]);
arr[0].push(10);
console.log(arr);


Enter fullscreen mode Exit fullscreen mode

Answer: [[10], [10], [10]]

The same reference to the array is filled in all positions. Modifying one modifies all.

15. Destructuring in API Responses

Destructuring can simplify data extraction when working with API responses.

Can you explain the result of this destructuring operation?



let {x, x: y} = {x: 23};
console.log(y);


Enter fullscreen mode Exit fullscreen mode

Answer: 23

Here, x is matched with a property in the object and then y is assigned the value of x.

JavaScript remains a cornerstone in the developer’s toolkit, with its nuances often serving as gateways to deeper understanding.

As you prepare for interviews, remember that these tricky questions are not just about memorization but about grasping the essence of the language.

By diving deep into such challenges, you not only prepare for potential interviews but also enrich your JavaScript proficiency.

Best of luck, and keep coding!

Top comments (0)