All topics

JavaScript interview questions

357 questions, 323 with answers. 1,820 open jobs in India ask for JavaScript.

  1. Explain event delegation

    Event delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The listener will fire whenever the event is triggered on the descendant elements due to event bubbling up the DOM. The benefits of this technique are:

    • Memory footprint goes down because only one single handler is needed on the parent element, rather than having to attach event handlers on each descendant.
    • There is no need to unbind the handler from elements that are removed and to bind the event for new elements.

    From Front End Interview Handbook (MIT)

  2. Explain how this works in JavaScript

    There's no simple explanation for this; it is one of the most confusing concepts in JavaScript. A hand-wavey explanation is that the value of this depends on how the function is called. I have read many explanations on this online, and I found Arnav Aggrawal's explanation to be the clearest. The following rules are applied:

    1. If the new keyword is used when calling the function, this inside the function is a brand new object.
    2. If apply, call, or bind are used to call/create a function, this inside the function is the object that is passed in as the argument.
    3. If a function is called as a method, such as obj.method() — this is the object that the function is a property of.
    4. If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, this is the global object. In a browser, it is the window object. If in strict mode ('use strict'), this will be undefined instead of the global object.
    5. If multiple of the above rules apply, the rule that is higher wins and will set the this value.
    6. If the function is an ES2015 arrow function, it ignores all the rules above and receives the this value of its surrounding scope at the time it is created.

    For an in-depth explanation, do check out his article on Medium.

    Can you give an example of one of the ways that working with this has changed in ES6?

    ES6 allows you to use arrow functions which use the enclosing lexical scope. This is usually convenient, but does prevent the caller from controlling context via .call or .apply—the consequences being that a library such as jQuery will not properly bind this in your event handler functions. Thus, it's important to keep this in mind when refactoring large legacy applications.

    From Front End Interview Handbook (MIT)

  3. Explain how prototypal inheritance works

    All JavaScript objects have a __proto__ property with the exception of objects created with Object.create(null), that is a reference to another object, which is called the object's "prototype". When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's __proto__, and the __proto__'s __proto__ and so on, until it finds the property defined on one of the __proto__s or until it reaches the end of the prototype chain. This behavior simulates classical inheritance, but it is really more of delegation than inheritance.

    Example of Prototypal Inheritance

    // Parent object constructor.
    function Animal(name) {
      this.name = name;
    }
    // Add a method to the parent object's prototype.
    Animal.prototype.makeSound = function () {
      console.log('The ' + this.constructor.name + ' makes a sound.');
    };
    // Child object constructor.
    function Dog(name) {
      Animal.call(this, name); // Call the parent constructor.
    }
    // Set the child object's prototype to be the parent's prototype.
    Object.setPrototypeOf(Dog.prototype, Animal.prototype);
    // Add a method to the child object's prototype.
    Dog.prototype.bark = function () {
      console.log('Woof!');
    };
    // Create a new instance of Dog.
    const bolt = new Dog('Bolt');
    // Call methods on the child object.
    console.log(bolt.name); // "Bolt"
    bolt.makeSound(); // "The Dog makes a sound."
    bolt.bark(); // "Woof!"
    

    Things to note are:

    • .makeSound is not defined on Dog, so the engine goes up the prototype chain and finds .makeSound off the inherited Animal.
    • Using Object.create to build the inheritance chain is no longer recommended. Use Object.setPrototypeOf instead.

    From Front End Interview Handbook (MIT)

  4. What do you think of AMD vs CommonJS?

    Both are ways to implement a module system, which was not natively present in JavaScript until ES2015 came along. CommonJS is synchronous while AMD (Asynchronous Module Definition) is obviously asynchronous. CommonJS is designed with server-side development in mind while AMD, with its support for asynchronous loading of modules, is more intended for browsers.

    I find AMD syntax to be quite verbose and CommonJS is closer to the style you would write import statements in other languages. Most of the time, I find AMD unnecessary, because if you served all your JavaScript into one concatenated bundle file, you wouldn't benefit from the async loading properties. Also, CommonJS syntax is closer to Node style of writing modules and there is less context-switching overhead when switching between client side and server side JavaScript development.

    I'm glad that with ES2015 modules, that has support for both synchronous and asynchronous loading, we can finally just stick to one approach. Although it hasn't been fully rolled out in browsers and in Node, we can always use transpilers to convert our code.

    From Front End Interview Handbook (MIT)

  5. Explain why the following doesn't work as an IIFE: function foo(){ }();. What needs to be changed to properly make it an IIFE?

    IIFE stands for Immediately Invoked Function Expressions. The JavaScript parser reads function foo(){ }(); as function foo(){ } and ();, where the former is a function declaration and the latter (a pair of parentheses) is an attempt at calling a function but there is no name specified, hence it throws Uncaught SyntaxError: Unexpected token ).

    Here are two ways to fix it that involve adding more parentheses: (function foo(){ })() and (function foo(){ }()). Statements that begin with function are considered to be function declarations; by wrapping this function within (), it becomes a function expression which can then be executed with the subsequent (). These functions are not exposed in the global scope and you can even omit its name if you do not need to reference itself within the body.

    You might also use void operator: void function foo(){ }();. Unfortunately, there is one issue with such approach. The evaluation of given expression is always undefined, so if your IIFE function returns anything, you can't use it. An example:

    const foo = void (function bar() {
      return 'foo';
    })();
    console.log(foo); // undefined
    

    From Front End Interview Handbook (MIT)

  6. What's the difference between a variable that is: null, undefined or undeclared? How would you go about checking for any of these states?

    Undeclared variables are created when you assign a value to an identifier that is not previously created using var, let or const. Undeclared variables will be defined globally, outside of the current scope. In strict mode, a ReferenceError will be thrown when you try to assign to an undeclared variable. Undeclared variables are bad just like how global variables are bad. Avoid them at all cost! To check for them, wrap its usage in a try/catch block.

    function foo() {
      x = 1; // Throws a ReferenceError in strict mode
    }
    foo();
    console.log(x); // 1
    

    A variable that is undefined is a variable that has been declared, but not assigned a value. It is of type undefined. If a function does not return any value as the result of executing it is assigned to a variable, the variable also has the value of undefined. To check for it, compare using the strict equality (===) operator or typeof which will give the 'undefined' string. Note that you should not be using the abstract equality operator to check, as it will also return true if the value is null.

    var foo;
    console.log(foo); // undefined
    console.log(foo === undefined); // true
    console.log(typeof foo === 'undefined'); // true
    console.log(foo == null); // true. Wrong, don't use this to check!
    function bar() {}
    var baz = bar();
    console.log(baz); // undefined
    

    A variable that is null will have been explicitly assigned to the null value. It represents no value and is different from undefined in the sense that it has been explicitly assigned. To check for null, simply compare using the strict equality operator. Note that like the above, you should not be using the abstract equality operator (==) to check, as it will also return true if the value is undefined.

    var foo = null;
    console.log(foo === null); // true
    console.log(typeof foo === 'object'); // true
    console.log(foo == undefined); // true. Wrong, don't use this to check!
    

    As a personal habit, I never leave my variables undeclared or unassigned. I will explicitly assign null to them after declaring if I don't intend to use it yet. If you use a linter in your workflow, it will usually also be able to check that you are not referencing undeclared variables.

    From Front End Interview Handbook (MIT)

  7. What is a closure, and how/why would you use one?

    A closure is the combination of a function and the lexical environment within which that function was declared. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Closures are functions that have access to the outer (enclosing) function's variables—scope chain even after the outer function has returned.

    Why would you use one?

    From Front End Interview Handbook (MIT)

  8. Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?

    To understand the differences between the two, let's look at what each function does.

    forEach

    • Iterates through the elements in an array.
    • Executes a callback for each element.
    • Does not return a value.
    const a = [1, 2, 3];
    const doubled = a.forEach((num, index) => {
      // Do something with num and/or index.
    });
    // doubled = undefined
    

    map

    • Iterates through the elements in an array.
    • "Maps" each element to a new element by calling the function on each element, creating a new array as a result.
    const a = [1, 2, 3];
    const doubled = a.map((num) => {
      return num * 2;
    });
    // doubled = [2, 4, 6]
    

    The main difference between .forEach and .map() is that .map() returns a new array. If you need the result, but do not wish to mutate the original array, .map() is the clear choice. If you simply need to iterate over an array, forEach is a fine choice.

    From Front End Interview Handbook (MIT)

  9. What's a typical use case for anonymous functions?

    They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.

    (function () {
      // Some code here.
    })();
    

    As a callback that is used once and does not need to be used anywhere else. The code will seem more self-contained and readable when handlers are defined right inside the code calling them, rather than having to search elsewhere to find the function body.

    setTimeout(function () {
      console.log('Hello world!');
    }, 1000);
    

    Arguments to functional programming constructs or Lodash (similar to callbacks).

    const arr = [1, 2, 3];
    const double = arr.map(function (el) {
      return el * 2;
    });
    console.log(double); // [2, 4, 6]
    

    From Front End Interview Handbook (MIT)

  10. How do you organize your code? (module pattern, classical inheritance?)

    In the past, I've used Backbone for my models which encourages a more OOP approach, creating Backbone models and attaching methods to them.

    The module pattern is still great, but these days, I use React/Redux which utilize a single-directional data flow based on Flux architecture. I would represent my app's models using plain objects and write utility pure functions to manipulate these objects. State is manipulated using actions and reducers like in any other Redux application.

    I avoid using classical inheritance where possible. When and if I do, I stick to these rules.

    From Front End Interview Handbook (MIT)

  11. What's the difference between host objects and native objects?

    Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification, such as String, Math, RegExp, Object, Function, etc.

    Host objects are provided by the runtime environment (browser or Node), such as window, XMLHTTPRequest, etc.

    From Front End Interview Handbook (MIT)

  12. Difference between: function Person(){}, var person = Person(), and var person = new Person()?

    This question is pretty vague. My best guess at its intention is that it is asking about constructors in JavaScript. Technically speaking, function Person(){} is just a normal function declaration. The convention is to use PascalCase for functions that are intended to be used as constructors.

    var person = Person() invokes the Person as a function, and not as a constructor. Invoking as such is a common mistake if the function is intended to be used as a constructor. Typically, the constructor does not return anything, hence invoking the constructor like a normal function will return undefined and that gets assigned to the variable intended as the instance.

    var person = new Person() creates an instance of the Person object using the new operator, which inherits from Person.prototype. An alternative would be to use Object.create, such as: Object.create(Person.prototype).

    function Person(name) {
      this.name = name;
    }
    var person = Person('John');
    console.log(person); // undefined
    console.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined
    var person = new Person('John');
    console.log(person); // Person { name: "John" }
    console.log(person.name); // "john"
    

    From Front End Interview Handbook (MIT)

  13. What's the difference between .call and .apply?

    Both .call and .apply are used to invoke functions and the first parameter will be used as the value of this within the function. However, .call takes in comma-separated arguments as the next arguments while .apply takes in an array of arguments as the next argument. An easy way to remember this is C for call and comma-separated and A for apply and an array of arguments.

    function add(a, b) {
      return a + b;
    }
    console.log(add.call(null, 1, 2)); // 3
    console.log(add.apply(null, [1, 2])); // 3
    

    From Front End Interview Handbook (MIT)

  14. Explain Function.prototype.bind.

    Taken word-for-word from MDN:

    The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

    In my experience, it is most useful for binding the value of this in methods of classes that you want to pass into other functions. This is frequently done in React components.

    From Front End Interview Handbook (MIT)

  15. When would you use document.write()?

    document.write() writes a string of text to a document stream opened by document.open(). When document.write() is executed after the page has loaded, it will call document.open which clears the whole document (<head> and <body> removed!) and replaces the contents with the given parameter value. Hence it is usually considered dangerous and prone to misuse.

    There are some answers online that explain document.write() is being used in analytics code or when you want to include styles that should only work if JavaScript is enabled. It is even being used in HTML5 boilerplate to load scripts in parallel and preserve execution order! However, I suspect those reasons might be outdated and in the modern day, they can be achieved without using document.write(). Please do correct me if I'm wrong about this.

    From Front End Interview Handbook (MIT)

  16. What's the difference between feature detection, feature inference, and using the UA string?

    Feature Detection

    Feature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn't), so that the browser can always provide a working experience rather crashing/erroring in some browsers. For example:

    if ('geolocation' in navigator) {
      // Can use navigator.geolocation
    } else {
      // Handle lack of feature
    }
    

    Modernizr is a great library to handle feature detection.

    Feature Inference

    Feature inference checks for a feature just like feature detection, but uses another function because it assumes it will also exist, e.g.:

    if (document.getElementsByTagName) {
      element = document.getElementById(id);
    }
    

    This is not really recommended. Feature detection is more foolproof.

    UA String

    This is a browser-reported string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. It can be accessed via navigator.userAgent. However, the string is tricky to parse and can be spoofed. For example, Chrome reports both as Chrome and Safari. So to detect Safari you have to check for the Safari string and the absence of the Chrome string. Avoid this method.

    From Front End Interview Handbook (MIT)

  17. Explain Ajax in as much detail as possible.

    Ajax (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly use JSON instead of XML, due to the advantages of JSON being native to JavaScript.

    The XMLHttpRequest API is frequently used for the asynchronous communication or these days, the fetch() API.

    From Front End Interview Handbook (MIT)

  18. What are the advantages and disadvantages of using Ajax?

    Advantages

    • Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page.
    • Reduce connections to the server since scripts and stylesheets only have to be requested once.
    • State can be maintained on a page. JavaScript variables and DOM state will persist because the main container page was not reloaded.
    • Basically most of the advantages of an SPA.

    Disadvantages

    • Dynamic webpages are harder to bookmark.
    • Does not work if JavaScript has been disabled in the browser.
    • Some webcrawlers do not execute JavaScript and would not see content that has been loaded by JavaScript.
    • Webpages using Ajax to fetch data will likely have to combine the fetched remote data with client-side templates to update the DOM. For this to happen, JavaScript will have to be parsed and executed on the browser, and low-end mobile devices might struggle with this.
    • Basically most of the disadvantages of an SPA.

    From Front End Interview Handbook (MIT)

  19. Explain how JSONP works (and how it's not really Ajax).

    JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers because Ajax requests from the current page to a cross-origin domain is not allowed.

    JSONP works by making a request to a cross-origin domain via a <script> tag and usually with a callback query parameter, for example: https://example.com?callback=printData. The server will then wrap the data within a function called printData and return it to the client.

    <!-- https://mydomain.com -->
    <script>
      function printData(data) {
        console.log(`My name is ${data.name}!`);
      }
    </script>
    <script src="https://example.com?callback=printData"></script>
    
    // File loaded from https://example.com?callback=printData
    printData({ name: 'Yang Shun' });
    

    The client has to have the printData function in its global scope and the function will be executed by the client when the response from the cross-origin domain is received.

    JSONP can be unsafe and has some security implications. As JSONP is really JavaScript, it can do everything else JavaScript can do, so you need to trust the provider of the JSONP data.

    These days, CORS is the recommended approach and JSONP is seen as a hack.

    From Front End Interview Handbook (MIT)

  20. Have you ever used JavaScript templating? If so, what libraries have you used?

    Yes. Handlebars, Underscore, Lodash, AngularJS, and JSX. I disliked templating in AngularJS because it made heavy use of strings in the directives and typos would go uncaught. JSX is my new favorite as it is closer to JavaScript and there is barely any syntax to learn. Nowadays, you can even use ES2015 template string literals as a quick way for creating templates without relying on third-party code.

    const template = `<div>My name is: ${name}</div>`;
    

    However, do be aware of a potential XSS in the above approach as the contents are not escaped for you, unlike in templating libraries.

    From Front End Interview Handbook (MIT)

  21. Explain "hoisting".

    Hoisting is a term used to explain the behavior of variable declarations in your code. Variables declared or initialized with the var keyword will have their declaration "moved" up to the top of their module/function-level scope, which we refer to as hoisting. However, only the declaration is hoisted, the assignment (if there is one), will stay where it is.

    Note that the declaration is not actually moved - the JavaScript engine parses the declarations during compilation and becomes aware of declarations and their scopes. It is just easier to understand this behavior by visualizing the declarations as being hoisted to the top of their scope. Let's explain with a few examples.

    console.log(foo); // undefined
    var foo = 1;
    console.log(foo); // 1
    

    Function declarations have the body hoisted while the function expressions (written in the form of variable declarations) only has the variable declaration hoisted.

    // Function Declaration
    console.log(foo); // [Function: foo]
    foo(); // 'FOOOOO'
    function foo() {
      console.log('FOOOOO');
    }
    console.log(foo); // [Function: foo]
    // Function Expression
    console.log(bar); // undefined
    bar(); // Uncaught TypeError: bar is not a function
    var bar = function () {
      console.log('BARRRR');
    };
    console.log(bar); // [Function: bar]
    

    Variables declared via let and const are hoisted as well. However, unlike var and function, they are not initialized and accessing them before the declaration will result in a ReferenceError exception. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

    x; // undefined
    y; // Reference error: y is not defined
    var x = 'local';
    let y = 'local';
    

    From Front End Interview Handbook (MIT)

  22. Describe event bubbling.

    When an event triggers on a DOM element, it will attempt to handle the event if there is a listener attached, then the event is bubbled up to its parent and the same thing happens. This bubbling occurs up the element's ancestors all the way to the document. Event bubbling is the mechanism behind event delegation.

    From Front End Interview Handbook (MIT)

  23. What's the difference between an "attribute" and a "property"?

    Attributes are defined on the HTML markup but properties are defined on the DOM. To illustrate the difference, imagine we have this text field in our HTML: <input type="text" value="Hello">.

    const input = document.querySelector('input');
    console.log(input.getAttribute('value')); // Hello
    console.log(input.value); // Hello
    

    But after you change the value of the text field by adding "World!" to it, this becomes:

    console.log(input.getAttribute('value')); // Hello
    console.log(input.value); // Hello World!
    

    From Front End Interview Handbook (MIT)

  24. Why is extending built-in JavaScript objects not a good idea?

    Extending a built-in/native JavaScript object means adding properties/functions to its prototype. While this may seem like a good idea at first, it is dangerous in practice. Imagine your code uses a few libraries that both extend the Array.prototype by adding the same contains method, the implementations will overwrite each other and your code will break if the behavior of these two methods is not the same.

    The only time you may want to extend a native object is when you want to create a polyfill, essentially providing your own implementation for a method that is part of the JavaScript specification but might not exist in the user's browser due to it being an older browser.

    From Front End Interview Handbook (MIT)

  25. Difference between document load event and document DOMContentLoaded event?

    The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

    window's load event is only fired after the DOM and all dependent resources and assets have loaded.

    From Front End Interview Handbook (MIT)

  26. What is the difference between == and ===?

    == is the abstract equality operator while === is the strict equality operator. The == operator will compare for equality after doing any necessary type conversions. The === operator will not do type conversion, so if two values are not the same type === will simply return false. When using ==, funky things can happen, such as:

    1 == '1'; // true
    1 == [1]; // true
    1 == true; // true
    0 == ''; // true
    0 == '0'; // true
    0 == false; // true
    

    My advice is never to use the == operator, except for convenience when comparing against null or undefined, where a == null will return true if a is null or undefined.

    var a = null;
    console.log(a == null); // true
    console.log(a == undefined); // true
    

    From Front End Interview Handbook (MIT)

  27. Explain the same-origin policy with regards to JavaScript.

    The same-origin policy restricts how a document or script from one origin can interact with resources from another origin. Two URLs have the same origin when their URI scheme, hostname, and port number match.

    Browsers generally allow some cross-origin writes and resource embedding, but prevent scripts from reading cross-origin responses or accessing another origin's DOM. A server can selectively allow a script to read a cross-origin response through Cross-Origin Resource Sharing (CORS).

    The same-origin policy does not prevent Cross-Site Request Forgery (CSRF), because a browser can still send cross-origin requests with ambient credentials such as cookies. CSRF defenses include SameSite cookies, CSRF tokens, and origin checks.

    From Front End Interview Handbook (MIT)

  28. Make this work:
    duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5]
    
    function duplicate(arr) {
      return arr.concat(arr);
    }
    duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5]
    

    Or with ES6:

    const duplicate = (arr) => [...arr, ...arr];
    duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5]
    

    From Front End Interview Handbook (MIT)

  29. Why is it called a Ternary expression, what does the word "Ternary" indicate?

    "Ternary" indicates three, and a ternary expression accepts three operands, the test condition, the "then" expression and the "else" expression. Ternary expressions are not specific to JavaScript and I'm not sure why it is even in this list.

    From Front End Interview Handbook (MIT)

  30. What is "use strict";? What are the advantages and disadvantages to using it?

    'use strict' is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.

    Advantages:

    • Makes it impossible to accidentally create global variables.
    • Makes assignments which would otherwise silently fail to throw an exception.
    • Makes attempts to delete undeletable properties throw an exception (where before the attempt would simply have no effect).
    • Requires that function parameter names be unique.
    • this is undefined in the global context.
    • It catches some common coding bloopers, throwing exceptions.
    • It disables features that are confusing or poorly thought out.

    Disadvantages:

    • Many missing features that some developers might be used to.
    • No more access to function.caller and function.arguments.
    • Concatenation of scripts written in different strict modes might cause issues.

    Overall, I think the benefits outweigh the disadvantages, and I never had to rely on the features that strict mode blocks. I would recommend using strict mode.

    From Front End Interview Handbook (MIT)

After the last page: 34 questions more, without answers. Go to the last page

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.