DEV Community

loading...
Cover image for 💻 Top 30+ JavaScript interview questions for web developers.

💻 Top 30+ JavaScript interview questions for web developers.

devinterview profile image Devinterview-io ・15 min read

👉 You can check all 142 JavaScript tech interview questions here

🔹 1. What is the object type?

Answer:

The object type refers to a compound value where you can set properties (named locations) that each hold their own values of any type.

var obj = {
  a: "hello world", // property
  b: 42,
  c: true
};

obj.a; // "hello world", accessed with doted notation
obj.b; // 42
obj.c; // true

obj["a"]; // "hello world", accessed with bracket notation
obj["b"]; // 42
obj["c"]; // true
Enter fullscreen mode Exit fullscreen mode

Bracket notation is also useful if you want to access a property/key but the name is stored in another variable, such as:

var obj = {
  a: "hello world",
  b: 42
};

var b = "a";

obj[b]; // "hello world"
obj["b"]; // 42
Enter fullscreen mode Exit fullscreen mode

Source: Stackoverflow.com   

🔹 2. Explain arrays in JavaScript

Answer:

An array is an object that holds values (of any type) not particularly in named properties/keys, but rather in numerically indexed positions:

 var arr = [
        "hello world",
        42,
        true
    ];

    arr[0];         // "hello world"
    arr[1];         // 42
    arr[2];         // true
    arr.length;     // 3

    typeof arr;     // "object"
Enter fullscreen mode Exit fullscreen mode

Source: Stackoverflow.com   

🔹 3. What is typeof operator?

Answer:

JavaScript provides a typeof operator that can examine a value and tell you what type it is:

var a;
typeof a; // "undefined"

a = "hello world";
typeof a; // "string"

a = 42;
typeof a; // "number"

a = true;
typeof a; // "boolean"

a = null;
typeof a; // "object" -- weird, bug

a = undefined;
typeof a; // "undefined"

a = { b: "c" };
typeof a; // "object"
Enter fullscreen mode Exit fullscreen mode

Source: Stackoverflow.com   

🔹 4. Explain equality in JavaScript

Answer:

JavaScript has both strict and type–converting comparisons:

  • Strict comparison (e.g., ===) checks for value equality without allowing coercion
  • Abstract comparison (e.g. ==) checks for value equality with coercion allowed
var a = "42";
var b = 42;

a == b; // true
a === b; // false
Enter fullscreen mode Exit fullscreen mode

Some simple equalityrules:

  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===.
  • In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

Source: Stackoverflow.com   

🔹 5. What is Scope in JavaScript?

Answer:

In JavaScript, each function gets its own scope. Scope is basically a collection of variables as well as the rules for how those variables are accessed by name. Only code inside that function can access that function's scoped variables.

A variable name has to be unique within the same scope. A scope can be nested inside another scope. If one scope is nested inside another, code inside the innermost scope can access variables from either scope.

Source: Stackoverflow.com   

🔹 6. Explain Values and Types in JavaScript

Answer:

JavaScript has typed values, not typed variables. The following built-in types are available:

  • string
  • number
  • boolean
  • null and undefined
  • object
  • symbol (new to ES6)

Source: Stackoverflow.com   

🔹 7. What is let keyword in JavaScript?

Answer:

In addition to creating declarations for variables at the function level, ES6 lets you declare variables to belong to individual blocks (pairs of { .. }), using the let keyword.

Source: github.com/getify   

🔹 8. Explain the same-origin policy with regards to JavaScript.

Answer:

The same-origin policy prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.

Source: github.com/yangshun   

🔹 9. What is the difference between == and ===?

Answer:

== 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Source: github.com/yangshun   

🔹 10. Is there anyway to force using strict mode in Node.js?

Answer:

you can place

"use strict";
Enter fullscreen mode Exit fullscreen mode

at the top of your file in node >= 0.10.7, but if you want your whole app to run in strict (including external modules) you can do this

node --use_strict
Enter fullscreen mode Exit fullscreen mode

Source: stackoverflow.com   

🔹 11. Why would you use something like the load event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?

Answer:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

The DOM event DOMContentLoaded will fire after the DOM for the page has been constructed, but do not wait for other resources to finish loading. This is preferred in certain cases when you do not need the full page to be loaded before initializing.

Source: github.com/yangshun   

🔹 12. What is strict mode?

Answer:

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.

// Non-strict code...

(function() {
  "use strict";

  // Define your library strictly...

})();

// Non-strict code...
Enter fullscreen mode Exit fullscreen mode

Source: Stackoverflow.com   

🔹 13. What's the difference between Host objects and Native objects?

Answer:

  • 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.

Source: github.com/yangshun   

🔹 14. What language constructions do you use for iterating over object properties and array items?

Answer:

For objects:

  • for loops - for (var property in obj) { console.log(property); }. However, this will also iterate through its inherited properties, and you will add an obj.hasOwnProperty(property) check before using it.
  • Object.keys() - Object.keys(obj).forEach(function (property) { ... }). Object.keys() is a static method that will lists all enumerable properties of the object that you pass it.
  • Object.getOwnPropertyNames() - Object.getOwnPropertyNames(obj).forEach(function (property) { ... }). Object.getOwnPropertyNames() is a static method that will lists all enumerable and non-enumerable properties of the object that you pass it.

For arrays:

  • for loops - for (var i = 0; i < arr.length; i++). The common pitfall here is that var is in the function scope and not the block scope and most of the time you would want block scoped iterator variable. ES2015 introduces let which has block scope and it is recommended to use that instead. So this becomes: for (let i = 0; i < arr.length; i++).
  • forEach - arr.forEach(function (el, index) { ... }). This construct can be more convenient at times because you do not have to use the index if all you need is the array elements. There are also the every and some methods which will allow you to terminate the iteration early.

Most of the time, I would prefer the .forEach method, but it really depends on what you are trying to do. for loops allow more flexibility, such as prematurely terminate the loop using break or incrementing the iterator more than once per loop.

Source: github.com/yangshun   

🔹 15. What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?

Answer:

Some examples of languages that compile to JavaScript include CoffeeScript, Elm, ClojureScript, PureScript, and TypeScript.

Advantages:

  • Fixes some of the longstanding problems in JavaScript and discourages JavaScript anti-patterns.
  • Enables you to write shorter code, by providing some syntactic sugar on top of JavaScript, which I think ES5 lacks, but ES2015 is awesome.
  • Static types are awesome (in the case of TypeScript) for large projects that need to be maintained over time.

Disadvantages:

  • Require a build/compile process as browsers only run JavaScript and your code will need to be compiled into JavaScript before being served to browsers.
  • Debugging can be a pain if your source maps do not map nicely to your pre-compiled source.
  • Most developers are not familiar with these languages and will need to learn it. There's a ramp up cost involved for your team if you use it for your projects.
  • Smaller community (depends on the language), which means resources, tutorials, libraries, and tooling would be harder to find.
  • IDE/editor support might be lacking.
  • These languages will always be behind the latest JavaScript standard.
  • Developers should be cognizant of what their code is being compiled to — because that is what would actually be running, and that is what matters in the end.

Practically, ES2015 has vastly improved JavaScript and made it much nicer to write. I don't really see the need for CoffeeScript these days.

Source: github.com/yangshun   

🔹 16. Explain event bubbling and how one may prevent it

Answer:

Event bubbling is the concept in which an event triggers at the deepest possible element, and triggers on parent elements in nesting order. As a result, when clicking on a child element one may exhibit the handler of the parent activating.

One way to prevent event bubbling is using event.stopPropagation() or event.cancelBubble on IE < 9.

Source: https://github.com/kennymkchan   

🔹 17. What does use strict do?

Answer:

The use strict literal is entered at the top of a JavaScript program or at the top of a function and it helps you write safer JavaScript code by throwing an error if a global variable is created by mistake. For example, the following program will throw an error:

function doSomething(val) {
  "use strict"; 
  x = val + 10;
}`
Enter fullscreen mode Exit fullscreen mode

It will throw an error because x was not defined and it is being set to some value in the global scope, which isn't allowed with use strict The small change below fixes the error being thrown:

function doSomething(val) {
  "use strict";
  var x = val + 10;
}
Enter fullscreen mode Exit fullscreen mode

Source: coderbyte.com   

🔹 18. Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

Answer:

Every script has access to the global scope, and if everyone uses the global namespace to define their variables, collisions will likely occur. Use the module pattern (IIFEs) to encapsulate your variables within a local namespace.

Source: github.com/yangshun   

🔹 19. What is a Polyfill?

Answer:

A polyfill is essentially the specific code (or plugin) that would allow you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in.

  • Polyfills are not part of the HTML5 standard
  • Polyfilling is not limited to Javascript

Source: programmerinterview.com   

🔹 20. Explain Null and Undefined in JavaScript

Answer:

JavaScript (and by extension TypeScript) has two bottom types: null and undefined. They are intended to mean different things:

  • Something hasn't been initialized : undefined.
  • Something is currently unavailable: null.

Source: Stackoverflow.com   

🔹 21. What's the difference between throw Error('msg') vs throw new Error('msg')?

Answer:

Problem

var err1 = Error('message');
var err2 = new Error('message');
Enter fullscreen mode Exit fullscreen mode

Which one is correct and why?

Both are fine; the function call Error(…) is equivalent to the object creation expression new Error(…) with the same arguments.

Source: stackoverflow.com   

🔹 22. Lucky sevens

Answer:

Problem

Write a function called lucky_sevens which takes an array of integers and returns true if any three consecutive elements sum to 7.

To solve this challenge we'll simply loop through the array starting at the 3rd position, and checking if the number at this index plus the two previous elements sums to 7. We continue doing this as we loop through the entire array. Once we find three elements that sum to 7, we simply return true. If we reach the end of the array without finding elements that sum to 7, we return false.

function lucky_sevens(arr) {
  // if less than 3 elements then this challenge is not possible
  if (arr.length < 3) {
    return "not possible";
  }

  // because we know there are at least 3 elements we can
  // start the loop at the 3rd element in the array (i=2)
  // and check it along with the two previous elements (i-1) and (i-2)
  for (var i = 2; i < arr.length; i++) {
    if (arr[i] + arr[i - 1] + arr[i - 2] === 7) {
      return true;
    }
  }

  // if loop is finished and no elements summed to 7
  return false;
}

lucky_sevens([2, 1, 5, 1, 0]);
Enter fullscreen mode Exit fullscreen mode

Source: coderbyte.com   

🔹 23. Simple clock angle

Answer:

Problem

You will be given a number N that represents where the minute hand currently is on a clock. Your program should return the angle that is formed by the minute hand and the 12 o'clock mark on the clock.

If the input is 15 then your program should return 90 because a 90-degree angle is formed by the minute hand and the 12 o'clock mark on the clock. We'll solve this challenge by first calculating what angle is created by each minute passing on a clock. Once we calculate this number, we multiply it by the input to determine the final angle.

A method to solve such problems is to consider the rate of change of the angle in degrees per minute. The hour hand of a normal 12-hour analogue clock turns 360° in 12 hours (720 minutes) or 0.5° per minute. The minute hand rotates through 360° in 60 minutes or per minute.

function simpleClockAngle(num) {
  // we got 6 because 360/60 = 6
  // 360 represents the full number of a degrees in a circle and
  // 60 is the number of minutes on a clock, so dividing these two numbers
  // gives us the number of degrees for one minute
  return 6 * num;
}

simpleClockAngle(15);
Enter fullscreen mode Exit fullscreen mode

Source: coderbyte.com   

🔹 24. Sum of several arrays

Answer:

Problem

You will be given an array of several arrays that each contain integers and your goal is to write a function that will sum up all the numbers in all the arrays. For example, if the input is [[3, 2], [1], [4, 12]] then your program should output 22 because 3 + 2 + 1 + 4 + 12 = 22. Solve without and with reduce.

We will solve this challenge by looping through the entire array, and then looping through each inner array adding up all the numbers.

function sum_array(arr) {
  // store our final answer
  var sum = 0;
  // loop through entire array
  for (var i = 0; i < arr.length; i++) {
    // loop through each inner array
    for (var j = 0; j < arr[i].length; j++) {
      // add this number to the current final sum
      sum += arr[i][j];
    }
  }

  return sum;
}

sum_array([[3, 2], [1], [4, 12]]);
Enter fullscreen mode Exit fullscreen mode

With reduce:

function sumArray(arr) {
  return arr.reduce((t, e) => t.concat(e)).reduce((t, e) => t + e);
}
Enter fullscreen mode Exit fullscreen mode

Source: coderbyte.com   

🔹 25. Test divisors of three

Answer:

Problem

You will be given 2 parameters: a low and high number. Your goal is to print all numbers between low and high, and for each of these numbers print whether or not the number is divisible by 3. If the number is divisible by 3, print the word "div3" directly after the number.

We'll solve this problem by first creating a loop that will print each number from low to high. Once we have the code for that written, we'll add a conditional that will check if the number is evenly divisible by 3 by using the mod operator.

function test_divisors(low, high) {
  // we'll store all numbers and strings within an array
  // instead of printing directly to the console
  var output = [];

  for (var i = low; i <= high; i++) {
    // simply store the current number in the output array
    output.push(i);

    // check if the current number is evenly divisible by 3
    if (i % 3 === 0) {
      output.push("div3");
    }
  }

  // return all numbers and strings
  return output;
}

test_divisors(2, 10);
Enter fullscreen mode Exit fullscreen mode

Source: coderbyte.com   

🔹 26. Oddball sum

Answer:

Problem

Write a function called oddball_sum which takes in a list of numbers and returns the sum of all the odd elements. Try to solve with and without reduce function.

To solve this challenge we'll simply loop through the array while maintaining a final count, and every time an odd number is encountered we'll add it to the count.

Without reduce:

function oddball_sum(nums) {
  // final count of all odd numbers added up
  var final_count = 0;

  // loop through entire list
  for (var i = 0; i < nums.length; i++) {
    // we divide by 2, and if there is a remainder then
    // the number must be odd so we add it to final_count
    if (nums[i] % 2 === 1) {
      final_count += nums[i];
    }
  }

  return final_count;
}

oddball_sum([1, 2, 3, 4, 5]);
Enter fullscreen mode Exit fullscreen mode

With reduce:

function oddball_sum(nums) {
  return nums.reduce(function(total, item) {
    if (item % 2 === 1) {
      return (total += item);
    }
    return total;
  });
}
Enter fullscreen mode Exit fullscreen mode

Source: prepwork.appacademy.io   

🔹 27. Sum of Array Plus One

Answer:

Problem

Write a function that takes an array of integers and returns the sum of the integers after adding 1 to each.

// ES5 method is nice and clean
exports.es5 = function(array) {
  return array.reduce(function(memo, num) {
    return memo + num;
  }, array.length);
};

// Without array.reduce method isn't much different
exports.iterative = function(array) {
  var result = array.length;

  for (var i = 0; i < array.length; i++) {
    result += array[i];
  }

  return result;
};
Enter fullscreen mode Exit fullscreen mode

Source: github.com/blakeembrey   

🔹 28. String Rotation

Answer:

Problem

Find out if a string is a rotation of another string. E.g. ABCD is a rotation of BCDA but not ACBD.

First make sure a and b are of the same length. Then check to see if b is a substring of a concatenated with a:

module.exports = function(a, b) {
  return a.length === b.length && (a + a).indexOf(b) > -1;
};
Enter fullscreen mode Exit fullscreen mode

Source: github.com/blakeembrey   

🔹 29. Make this work

Answer:

Problem

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]
Enter fullscreen mode Exit fullscreen mode

Source: github.com/yangshun   

🔹 30. Given a string, reverse each word in the sentence

Answer:

Problem

For example Welcome to this Javascript Guide! should be become emocleW ot siht tpircsavaJ !ediuG

var string = "Welcome to this Javascript Guide!";

// Output becomes !ediuG tpircsavaJ siht ot emocleW
var reverseEntireSentence = reverseBySeparator(string, "");

// Output becomes emocleW ot siht tpircsavaJ !ediuG
var reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");

function reverseBySeparator(string, separator) {
  return string
    .split(separator)
    .reverse()
    .join(separator);
}
Enter fullscreen mode Exit fullscreen mode

Source: https://github.com/kennymkchan   


Thanks 🙌 for reading and good luck on your next tech interview!

> Explore 3800+ dev interview question here 👉 Devinterview.io

Discussion

pic
Editor guide
Collapse
afsharm profile image
Afshar Mohebi

4 and 9 were duplicated. Another duplication exist too.

Collapse
hanco profile image
Hanco

Thank you for writing the good post:)