53 JavaScript Frontend Interview Questions
Introduction
Job searches are competitive, making continuous learning and skill improvement essential. This guide provides 53 questions in a Q&A format, suitable for Junior to Middle level frontend developers, to aid in interview preparation.
1. What data types exist in JavaScript?
- Number — Numeric values
- String — Textual data
- Boolean —
true
orfalse
- Object — Objects
- null — Represents “nothing”
- undefined — Unassigned value
- Symbol — Unique and immutable
- BigInt — Large integers
const bigInt = 1234567890123456789012345678901234567890n;
2. What is the difference between ==
and ===
?
==
checks for abstract equality, performing type conversions if necessary.===
checks for strict equality without type conversion.
3. What are the ways to declare a variable?
- var — Global or function scope
- let — Block scope
- const — Block scope, immutable
- Object.defineProperty() — Define properties on objects
4. What is the difference between null and undefined?
- null — Manually assigned to represent “nothing.”
- undefined — Automatically assigned to uninitialized variables.
5. Arrow functions and the differences from regular functions
- No
arguments
object - Lexical
this
binding - Cannot be used as constructors
6. What is a closure and why are they needed?
A closure is a function with access to its own scope, the outer function’s scope, and the global scope.
function outer() {
let counter = 0;
function inner() {
counter++;
console.log(counter);
}
return inner;
}
const fn = outer();
fn(); // 1
fn(); // 2
7. What are template literals?
Template literals allow embedded expressions and multiline strings, enclosed in backticks (``).
let name = "World";
console.log(`Hello, ${name}!`);
8. What are Set and Map?
- Map — Key-value pairs, keys of any type.
- Set — Collection of unique values.
9. How to check for the presence of a property in an object?
1. hasOwnProperty()
obj.hasOwnProperty('key');
2. in operator
'key' in obj;
10. How to access an object property?
1. Dot notation
obj.a;
2. Bracket notation
obj['a'];
11. What are the main methods for working with arrays?
- forEach()
- filter()
- map()
- reduce()
12. What are the ways to create an object?
1. Constructor function
function Person(name) {
this.name = name;
}
2. Object literal
const obj = { key: 'value' };
3. Class
class Person {
constructor(name) {
this.name = name;
}
}
4. Object.create()
const obj = Object.create(proto);
13. What is a Promise?
A Promise handles asynchronous operations, with states: pending, fulfilled, rejected.
const promise = new Promise((resolve, reject) => {
if (success) resolve(value);
else reject(error);
});
promise.then(value => console.log(value)).catch(error => console.error(error));
14. What is async/await and how to use it?
async/await
is syntax for working with Promises. async
functions return a Promise. await
pauses execution until the Promise settles.
async function fetchData() {
const response = await fetch(url);
const data = await response.json();
return data;
}
15. How to check if an object is an array?
Array.isArray(obj);
16. What is the purpose of the spread operator?
The spread operator (...
) expands iterable elements.
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
17. How to avoid reference dependency when copying an object?
1. Shallow copy
const shallowCopy = { ...obj };
2. Deep copy
const deepCopy = JSON.parse(JSON.stringify(obj));
18. How to change the context of a function?
1. bind()
const boundFunc = func.bind(context);
2. call()
func.call(context, arg1, arg2);
3. apply()
func.apply(context, [arg1, arg2]);
19. What is a ternary operator?
A shorthand for if-else
.
condition ? expr1 : expr2;
20. What is destructuring?
Destructuring extracts values from arrays or objects.
const { a, b } = obj;
const [x, y] = arr;
21. What is the DOM?
The DOM represents an HTML document as a tree of objects.
22. What is the Event Loop?
The event loop handles asynchronous operations in JavaScript, processing events and tasks in order.
23. What is prototypal inheritance?
Objects inherit properties and methods from their prototypes.
24. What is the Optional Chaining operator?
Optional Chaining (?.
) returns undefined
if the part after ?.
is null or undefined.
let street = user?.address?.street;
25. What is Shadow DOM?
Shadow DOM encapsulates element structure and styles, isolating them from the rest of the page.
26. What is recursion? How to use it?
Recursion is when a function calls itself. It needs a base case to avoid infinite loops.
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
27. What’s the difference between Function Expression and Function Declaration?
- Function Declaration
function foo() {}
- Function Expression
const foo = function() {};
28. What are constructor functions?
Constructor functions create objects using the new
keyword.
function Person(name) {
this.name = name;
}
const john = new Person('John');
29. How can you get a list of keys and a list of values from an object?
- Object.keys()
Object.keys(obj);
- Object.values()
Object.values(obj);
30. Provide an example of new functionality in ES6
- let and **const
** for block-scoped variables
let x = 1;
const y = 2;
31. What is this
in JavaScript?
this
refers to the context in which a function is executed.
function show() {
console.log(this);
}
32. How to prevent object extension?
Use Object.preventExtensions()
to prevent adding new properties.
Object.preventExtensions(obj);
33. How to use Object.freeze()
?
Object.freeze()
makes an object immutable.
Object.freeze(obj);
34. How does Object.seal()
differ from Object.freeze()
?
- Object.seal() — Prevents adding/removing properties, but existing properties can be modified.
- Object.freeze() — Prevents all modifications.
35. What is a Higher-Order Function?
A higher-order function takes another function as an argument or returns a function.
function higherOrder(fn) {
return function() {
fn();
};
}
36. What are call
, apply
, and bind
?
- call() — Calls a function with a given
this
value and arguments. - apply() — Similar to
call()
, but arguments are passed as an array. - bind() — Creates a new function with a specified
this
value.
37. How to create a new object in JavaScript?
1. Using a constructor
const obj = new Object();
2. Using an object literal
const obj = {};
3. Using Object.create()
const obj = Object.create(proto);
38. What are IIFEs (Immediately Invoked Function Expressions)?
IIFEs are functions that run as soon as they are defined.
(function() {
console.log('I am an IIFE');
})();
39. What is the difference between synchronous and asynchronous code?
- Synchronous — Executes in sequence.
- Asynchronous — Executes independently, allowing other code to run.
40. How do you handle errors in JavaScript?
1. try…catch
try {
// Code that may throw an error
} catch (error) {
console.error(error);
}
2. Promise.catch()
promise.catch(error => console.error(error));
41. What are async
functions?
Functions declared with async
always return a Promise.
async function foo() {
return 1;
}
42. What is a JavaScript module
?
Modules are pieces of code that export functions, objects, or primitives from one module to another.
// module.js
export const foo = () => {};
// app.js
import { foo } from './module';
43. What are regular expressions?
Patterns used for matching character combinations in strings.
const regex = /abc/;
44. What are WeakMap
and WeakSet
?
- WeakMap — Maps keys to values, keys are weakly held.
- WeakSet — Stores unique objects, weakly held.
45. How to create a new array from an existing one?
1. Array.slice()
const newArray = arr.slice();
2. Array.concat()
const newArray = arr.concat();
3. Spread syntax
const newArray = [...arr];
46. What is the difference between map()
and forEach()
?
- map() — Creates a new array with the results of calling a function on every element.
- forEach() — Executes a function on each element, returns
undefined
.
47. What is JSON
?
JSON (JavaScript Object Notation) is a lightweight data-interchange format.
const json = JSON.stringify(obj);
const parsed = JSON.parse(json);
48. What are template strings?
Template strings (template literals) allow for embedded expressions.
let name = 'John';
console.log(`Hello, ${name}`);
49. What is a callback function?
A function passed into another function as an argument, to be executed later.
function doSomething(callback) {
callback();
}
50. What is the Array.reduce()
method?
reduce()
executes a reducer function on each element, resulting in a single value.
const sum = arr.reduce((acc, curr) => acc + curr, 0);
51. How to define a class in JavaScript?
class Person {
constructor(name) {
this.name = name;
}
}
52. What are get
and set
?
- get — Accessor method for a property.
- set — Mutator method for a property.
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
}
53. What is localStorage
?
localStorage
provides a way to store data on the client-side.
localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
Ref: Adarsh Rai - Medium