in

Frequently Asked JavaScript Interview Questions and Answers

JavaScript is one of the most popular programming languages in the world. It is used to build dynamic, interactive web applications and sites. With the rise of front-end frameworks like React, Angular, and Vue, knowledge of JavaScript is a must for any front-end developer role.

Let‘s take a look at some of the most frequently asked JavaScript interview questions and answers to help you prepare for your next coding interview.

1. What are the advantages of using JavaScript?

Some key advantages of using JavaScript include:

  • It‘s a lightweight, interpreted programming language that is easy to learn and implement. You don‘t need to compile JavaScript code before running it.

  • It‘s the core scripting language of the web that can manipulate DOM elements to create dynamic web pages. Most modern websites use JavaScript extensively.

  • It has a large and active developer community, so you can easily find solutions to problems or get help with debugging.

  • There are tons of libraries and frameworks built on top of JavaScript like jQuery, React, Angular, and Node.js. This allows you to develop apps faster.

  • JavaScript is versatile and can be used for front-end, back-end, mobile, game, VR/AR development, etc. It powers full-stack development.

  • It has great community support and is continuously evolving with new standards and features like ES6, ES7, etc.

2. What are the differences between var, let, and const?

  • var declarations are globally scoped or function scoped while let and const are block scoped.

  • var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.

  • They are all hoisted to the top of their scope. But while var variables are initialized with undefined, let and const variables are not initialized. They remain in a "temporal dead zone" until the initialization is reached.

  • While var and let can be declared without being initialized, const must be initialized during declaration.

So in summary:

  • var – globally/function scoped, can be updated and re-declared, hoisted
  • let – block scoped, can be updated, not re-declared, hoisted but not initialized
  • const – block scoped, cannot be updated or re-declared, must be initialized, hoisted but not initialized

3. What are JavaScript data types?

The latest ECMAScript standard defines 8 data types in JavaScript:

  • Primitive data types:

    • Boolean – true or false
    • Null – Intentional absence of a value
    • Undefined – Variables declared but not initialized
    • Number – Integers, floats, etc.
    • BigInt – Larger integers than the Number type
    • String – Sequence of characters
    • Symbol – Unique and immutable values
  • Non-primitive data type:

    • Object – key-value pairs of properties and methods

Primitive data types are immutable while objects are mutable.

4. What is the difference between == and === operators?

  • The == operator checks for value equality only while === checks for both value and type equality.

  • The == operator coerces variable types while comparing if the values have different types. The === doesn‘t coerce and only returns true if both value and type match.

For example:

0 == false   // true
0 === false  // false

1 == "1"     // true
1 === "1"    // false

So in summary, use === for strict equality comparisons and == when type coercion is acceptable.

5. What are JavaScript events? Name some commonly used events.

JavaScript events allow you to execute code when something happens on a web page like a user click, page load, form submit, etc.

Some commonly used events are:

  • onclick – When an element is clicked
  • onload – When the page is done loading
  • onfocus – When an element gets focus
  • onsubmit – When a form is submitted
  • onscroll – When the document is scrolled
  • onkeydown – When a key is pressed
  • onmouseover – When the mouse pointer moves over an element

These events can trigger JavaScript functions to execute. For example:

document.getElementById("button").onclick = function(){
  //do something
}

6. Explain event bubbling and capturing in JavaScript.

Event propagation refers to the order in which events are handled in the DOM tree. There are two ways events propagate in the DOM:

Bubbling – The default propagation mode. The event is first captured and handled by the innermost element and then propagated to outer elements.

Capturing – The event is first captured by the outermost element and propagated to the inner elements.

Capturing is rarely used. To use capturing, you have to set the third parameter of addEventListener() to true:

element.addEventListener(event, function, true); 

Bubbling is more common and the default propagation mode.

7. What are callbacks in JavaScript?

Callbacks are functions passed as arguments to other functions that are expected to call back (invoke) the callback function at some point.

Callbacks allow you to defer the execution of a code until the response from a previous function call is received. This allows asynchronous execution of code.

For example, making an AJAX request:

ajaxRequest(‘https://example.com‘, function(response) {
  // this anonymous function is the callback  
  console.log(response)
});

Here the anonymous function passed as the second argument is the callback. It will be invoked once the response is received from ajaxRequest.

8. What is a promise in JavaScript?

A promise represents an asynchronous operation that will complete at some point in the future either successfully or unsuccessfully.

Some key characteristics of promises:

  • A promise can have only 3 possible states – pending, fulfilled, and rejected

  • then() and catch() methods are used to handle successful or failed promises respectively

  • Multiple then() handlers can be chained together to transform values or run additional async operations

  • Promises help avoid callback hell which can occur when heavily nesting callbacks

Here is a simple promise example:

let promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    let num = Math.random();
    if (num < 0.5 ){
      resolve(num);
    } else {
      reject(‘Error: Num is greater than 0.5‘);
    }
  }, 1000);
});

promise.then((num) => {
  console.log(num);
}).catch((err) => {
  console.log(err); 
})

This performs some async operation using setTimeout then either resolves or rejects the promise based on a condition.

9. How is JavaScript asynchronous programming different from synchronous?

Synchronous Code

  • Each operation must wait for the previous one to complete before executing.
  • Code executes in sequence, blocking execution until responses return.

Asynchronous Code

  • Allows multiple operations to happen independently without blocking execution.
  • Callbacks, promises, async/await provide mechanisms to handle async responses.
  • Non-blocking execution improves application performance and responsiveness.

For example:

// Synchronous
getData(url1); 
getData(url2);

// Asynchronous
getData(url1);
getData(url2); 

function getData(url) {
  // send async request
  // ...
}

The synchronous version has to wait for each getData call to finish before calling the next. The async version calls them concurrently.

10. What are closures in JavaScript? Give an example.

A closure is the combination of a function bundled together with its lexical environment. The function can access its lexical scope even when it is invoked outside its lexical scope.

Here is an example of a closure:

function outer() {
  const x = ‘hello‘;

  function inner() {
    console.log(x); // accesses x from outer scope
  }

  return inner;
}

const closureFn = outer();
closureFn(); // logs ‘hello‘ 

Even when called later outside outer(), inner() still maintains access to the x variable through its closure scope.

Closures are useful because they allow data encapsulation and emulating private methods.

11. What is the output of the following code? Explain closures.

for (var i = 0; i < 3; i++) {
  setTimeout(function() { console.log(i); }, 1000);
}

The output will be 3, 3, 3 logged to the console every second.

This is because each function executed within setTimeout forms a closure with the surrounding scope which is the global scope. So all functions reference the same i from the global scope whose value ends up being 3 after the loop terminates.

If we expect 0, 1, 2, we have to use a closure to encapsulate each iteration:

for (var i = 0; i < 3; i++) {
  (function(x) {
    setTimeout(function() { console.log(x); }, 1000);  
  })(i); 
}

Now each function passed to setTimeout forms a closure with the immediately invoked function, preserving each iteration‘s i value.

So this prints 0, 1, 2 as expected.

12. What are DOM methods for inserting, removing, and altering HTML elements?

Some common DOM methods for manipulating HTML elements are:

  • document.createElement() – Create a new element
  • document.appendChild() – Insert element as last child
  • document.insertBefore() – Insert element before specified element
  • document.removeChild() – Remove element
  • element.innerHTML – Get/set inner HTML of element
  • element.style – Get/set style properties
  • element.setAttribute() – Set attribute value
  • element.classList – Get/set class names

For example:

// Create new element
const div = document.createElement(‘div‘);

// Insert before first child 
document.body.insertBefore(div, document.body.firstChild);  

// Alter property
div.style.color = ‘blue‘;

// Remove element
document.body.removeChild(div);

There are many more DOM methods and properties you should get familiar with for manipulating the DOM.

13. What is the difference between localStorage and sessionStorage?

localStorage and sessionStorage both allow you to save key-value pairs in the browser. The main differences are:

  • Lifetime: Data in localStorage has no expiration time while sessionStorage data gets cleared when the browsing session ends (tab or window is closed).

  • Scope: localStorage is scoped to the browser while sessionStorage is scoped to a tab/window within a browser.

  • Shared State: localStorage data is shared across all tabs and windows within a browser while sessionStorage data is isolated to a tab/window.

So in summary:

  • localStorage – Persists data after browsing session, shared across tabs/windows
  • sessionStorage – Cleared after browsing session ends, isolated to tab/window

14. What is the difference between synchronous and asynchronous JavaScript functions?

Synchronous functions execute in sequence, blocking further execution until they return.

Asynchronous functions execute out of sequence without blocking main execution because their result will be returned via a callback function later.

An example of a synchronous function:

function printHello() {
  console.log(‘Hello‘);
}

printHello();
console.log(‘Hi‘); 

Here Hi will be logged after Hello because printHello() blocks further execution.

An async example:

function printHello(callback) {
  setTimeout(() => {
    console.log(‘Hello‘);
    callback();
  }, 1000);
}

printHello(() => {
  console.log(‘Hi‘); 
});

Now Hi will be logged before Hello because printHello() doesn‘t block execution thanks to the callback.

15. What is JSON and its common operations?

JSON (JavaScript Object Notation) is a lightweight data interchange format. It provides a human-readable way to represent data that can be transmitted between browsers and servers.

Some common JSON operations are:

  • Convert to JSON – Use JSON.stringify() to convert a JS object to JSON

  • Parse from JSON – Use JSON.parse() to parse JSON string to a JS object

  • Read/Write – Use AJAX and HTTP requests to read or write JSON data to server

For example:

const obj = {name: ‘John‘, age: 20}; 

// converts obj to JSON string
const json = JSON.stringify(obj);  

// converts json back to object
const parsed = JSON.parse(json);

JSON is useful for exchanging data between browsers and servers through REST API calls.

16. What is the purpose of this keyword in JavaScript?

The this keyword refers to the object that the current function is a property of. Some key notes on this:

  • In global and functional scope, this refers to the global object (window in browsers)
  • In method scope, this refers to the object calling the method.
  • The value of this is determined at call time and can vary based on context.
  • Arrow functions do not have their own this binding. this in arrows will be inherited from enclosing scope.
  • call(), apply(), bind() can all be used to explicitly bind this.

So this provides an implicit binding that makes methods contextually reference their object.

17. Explain prototypal inheritance in JavaScript.

All JavaScript objects have a prototype property that allows them to inherit features from other objects.

When a property is accessed on an object:

  1. If the property exists on that object, use it
  2. Else check if it exists on object‘s prototype
  3. Still not found, go up the prototype chain till you hit Object.prototype

This chained lookup of properties is prototypal inheritance.

For example:

const User = {
  calcAge() {
    //...
  }
};

const John = {
  name: ‘John‘
};

// Set John‘s prototype to User 
John.__proto__ = User; 

// This will check for calcAge() on John, 
// then its prototype which is User
John.calcAge(); 

So John inherits calcAge() via the prototype chain without copying the method.

18. What are JavaScript design patterns?

Some common JavaScript design patterns are:

  • Constructor – Initialize objects based on a template blueprint
  • Module – Encapsulate functionality and expose it via an interface
  • Singleton – Restrict instantiation to one object instance
  • Observer – Provide a callback mechanism when events occur
  • Prototype – Create objects based on a template of an existing object through cloning
  • Factory – Create objects without specifying the exact class/prototype
  • Mixin – Add functionality to a class by applying mixins

These patterns provide proven development strategies for common scenarios like organizing code and object creation.

Understanding design patterns is an important part of JavaScript mastery.

19. What is a potential pitfall with using typeof operator?

While typeof can determine the type of most values accurately, one pitfall is that it will return "object" for arrays and null values.

For example:

typeof [] // "object" 
typeof null // "object"

So you cannot reliably use typeof to differentiate between object, array, and null values.

Instead, you can use:

Array.isArray(arr) // true
Object.prototype.toString.call(arr) // "[object Array]" 

obj === null

So remember – typeof can lie about arrays and null! Use the above techniques for better type checking.

20. What is a potential pitfall with using == operator?

The main pitfall with == is unintended type coercion. Due to implicit type coercion, values that are expected to be unequal may return true with the == operator.

For example:

‘‘ == 0 // true
0 == [] // true
null == undefined // true 

This can introduce weird bugs in your program.

Instead, you should use the strict equality operator === which does not perform type coercion. This will give you the expected comparisons without surprise coercions.

Summary

We‘ve covered a broad range of frequently asked JavaScript interview questions – from its core features to asynchronous programming to patterns and pitfalls.

Understanding these JavaScript concepts will prepare you well for most interviews. Keep practicing these questions and writing code until you feel confident about tackling anything that comes your way!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.