![Koda School](/_next/image?url=%2Fimages%2Flogo.png&w=96&q=75)
KodaSchool
Learn To Code
50 Javascript interview questions and Answers
This guide will provide you with a list of comprehensive frequently asked JavaScript questions that you will need to ace any interview on JavaScript.
topics
Introduction
JavaScript is one of the building blocks of the web, it’s an open-source programming language and It’s widely used for creating interactive web applications, from simple websites to complex web services.
In this guide to help you prepare for your next interview, we've compiled a list of 50+ JavaScript interview questions and answers.
JavaScript fundamentals
1. What is JavaScript?
JavaScript is a lightweight, interpreted programming language used primarily for adding interactivity to web pages e.g. clicking on a button and seeing a pop up all is the work of JS.
There’s a lot more in JavaScript and it opens the door to being a frontend and backend developer.
2. What are the different data types available in JavaScript?
There are two types of JavaScript - primitive and non-primitive.
JavaScript has the following data types:
- String - For characters and alphanumeric values,
- Number - For integer and floating-point numbers,
- Boolean - For true and false values,
- Object - For collections or complex values,
- Null - For empty or unknown values,
- Undefined - For variables that are only declared and not defined or initialized,
- Symbol - For unique identifiers for objects, and
- BigInt - allows you to work with arbitrarily large integers.
3. Explain the concept of variables in JavaScript. What are var, let, and const?
var
is function-scoped, let
and const
are block-scoped. const
is used for variables that shouldn’t change.
var x = 10; // function-scoped
let y = 20; // block-scoped
const z = 30; // block-scoped and constant
4. How do you create a function in JavaScript? Provide an example.
You can create a function using the function
keyword.
function greet(name) {
return `Hello, ${name}!`;
}
5. What is the difference between == and ===?
==
checks for value equality with type coercion, ===
checks for both value and type equality.
==
console.log('0' == 0); // true
console.log(false == 0); // true
console.log(null == undefined); // true
===
console.log('0' === 0); // false
console.log(false === 0); // false
console.log(null === undefined); // false
6. What are the different types of operators in JavaScript?
There are different arithmetic operators including:
Arithmetic Operators
. Arithmetic operators are used to perform mathematical operations on numbers.
let sum = 10 + 5; // Addition
let difference = 10 - 5; // Subtraction
let product = 10 * 5; // Multiplication
let quotient = 10 / 5; // Division
let remainder = 10 % 3; // Modulus
let increment = ++sum; // Increment
let decrement = --difference; // Decrement
Comparison Operators.
Comparison operators are used to compare two values and return a boolean result.
let isEqual = (10 == '10'); // true (equal to, type coercion)
let isStrictEqual = (10 === '10'); // false (strictly equal to, no type coercion)
let isNotEqual = (10 != '10'); // false (not equal to, type coercion)
let isGreater = (10 > 5); // true (greater than)
let isLessOrEqual = (10 <= 10); // true (less than or equal to)
Logical Operators.
Logical operators are used to perform logical operations, typically with boolean values.
let and = (true && false); // false (logical AND)
let or = (true || false); // true (logical OR)
let not = !true; // false (logical NOT)
Assignment Operators.
Assignment operators are used to assign values to variables.
let x = 10; // Assignment
x += 5; // Addition assignment (x = x + 5)
x -= 3; // Subtraction assignment (x = x - 3)
x *= 2; // Multiplication assignment (x = x * 2)
x /= 2; // Division assignment (x = x / 2)
x %= 3; // Modulus assignment (x = x % 3)
Conditional (Ternary) Operator.
The conditional (ternary) operator assigns a value to a variable based on a condition.
let age = 18;
let canVote = (age >= 18) ? 'Yes' : 'No'; // If age is 18 or older, canVote is 'Yes', otherwise 'No'
7. What is the difference between null and undefined?
null
is an assignment value indicating no value, while undefined means a variable has been declared but not assigned a value.
8. Explain the concept of scope in JavaScript.
Scope determines the visibility of variables. JavaScript has function scope
and block scope.
9. What are template literals in JavaScript and how are they used?
Template literals allow embedding expressions within string literals using backticks.
let name = "John";
console.log(`Hello, ${name}!`);
10. What are arrow functions, and how do they differ from regular functions?
Arrow functions are a shorthand for writing functions and do not have their own this context.
const add = (a, b) => a + b;
Object-Oriented Programming
11. What is an object in JavaScript and how do you create one?
An object is a collection of properties, where a property is an association between a name (or key) and a value. You can create an object using object literal syntax or the new Object()
syntax.
// Using object literal syntax
let person = {
name: "Alice",
age: 25,
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
// Using new Object() syntax
let person2 = new Object();
person2.name = "Bob";
person2.age = 30;
person2.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
12. Explain the concept of prototypes in JavaScript.
Every JavaScript object has a prototype. A prototype is also an object. All JavaScript objects inherit their properties and methods from their prototype.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
let alice = new Person("Alice");
alice.greet(); // Output: Hello, my name is Alice
13. What is inheritance in JavaScript? How do you implement it?
Inheritance is a feature that allows one class to inherit the properties and methods of another class. In JavaScript, you can implement inheritance using prototypes or the class syntax.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hello, ${this.name}!`;
};
let person = new Person("Alice");
14. What are classes in JavaScript? How do you define a class?
Classes are templates for creating objects.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old`);
}
}
let alice = new Person("Alice", 25);
alice.greet(); // Output: Hello, my name is Alice and I am 25 years old
15. What is the difference between a constructor function and a class?
Constructor functions are the old way of creating objects, while classes are syntactic sugar for constructor functions.
16. Explain the concept of method overriding in JavaScript.
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. This allows the subclass to provide a specific behavior while reusing the method name.
class Animal {
speak() {
console.log("Animal makes a noise");
}
}
class Dog extends Animal {
speak() {
console.log("Dog barks");
}
}
let myDog = new Dog();
myDog.speak(); // Output: Dog barks
17. What are getters and setters in JavaScript?
Getters and setters are special methods that allow you to get and set the values of an object's properties. They provide a way to control access to an object's properties.
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
}
18. What is the this
keyword in JavaScript? How does it work?
this
refers to the context in which a function is called.
19. How do you create and use modules in JavaScript?
Modules are created using export and import.
// module.js
export const greet = (name) => `Hello, ${name}!`;
// main.js
import { greet } from './module.js';
20. What are mixins in JavaScript?
Mixins are a way to add properties and methods to a class by merging objects. They allow you to create reusable chunks of functionality.
Advanced Concepts
21. What is a closure in JavaScript? Provide an example.
A closure is a function that retains access to its lexical scope.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
22. Explain the concept of promises in JavaScript.
Promises
represent the eventual completion or failure of an asynchronous operation.
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done!"), 1000);
});
promise.then(result => console.log(result));
23. What are async/await in JavaScript? How do they work?
async/await
is syntactic sugar for working with promises, making asynchronous code look synchronous.
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
24. What is event delegation in JavaScript?
Event delegation allows you to handle events at a higher level in the DOM hierarchy.
25. What is the call, apply, and bind method in JavaScript?
call
and apply
invoke functions with a specific this context. bind returns a new function with this bound to a specific value.
26. What are higher-order functions in JavaScript?
Higher-order functions are functions that take other functions as arguments or return them.
27. What is the event loop in JavaScript?
The event loop is a mechanism that handles asynchronous operations by putting them in a queue and executing them in order.
28. Explain the concept of currying in JavaScript.
Currying transforms a function with multiple arguments into a sequence of functions with single arguments.
function curry(f) {
return function(a) {
return function(b) {
return f(a, b);
};
};
}
const add = (a, b) => a + b;
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)); // 3
29. What is a generator function in JavaScript?
Generator functions can be paused and resumed, using the function* syntax.
function* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator();
console.log(gen.next().value); // 1
30. What are proxy objects in JavaScript?
Proxies are used to create objects with custom behavior for fundamental operations.
let target = {};
let handler = {
get: function(target, prop, receiver) {
return `Hello, ${prop}!`;
}
};
let proxy = new Proxy(target, handler);
console.log(proxy.world); // "Hello, world!"
DOM Manipulation
31. How do you select elements in the DOM using JavaScript?
Using methods like getElementById
, querySelector
, and getElementsByClassName
.
let element = document.getElementById('myId');
32. What are event listeners in JavaScript? How do you add and remove them?
Event listeners respond to user actions. Use addEventListener
and removeEventListener
.
element.addEventListener('click', () => {
console.log('Clicked!');
});
33. How do you manipulate the DOM using JavaScript?
By changing properties like innerHTML
, style
, and using methods like appendChild
.
34. What is the difference between innerHTML and textContent?
innerHTML
parses HTML, textContent
sets the text content only.
35. How do you handle events in JavaScript?
Using event listeners
and callback functions.
ES6+ Features
36. What are the new features introduced in ES6?
ES6 introduced significant enhancements to JavaScript, including let and const for variable declarations, arrow functions, template literals, classes, destructuring, and more.
37. Explain the concept of destructuring in JavaScript.
Destructuring allows you to extract values from arrays or properties from objects into distinct variables.
// Destructuring arrays
let [a, b] = [1, 2];
console.log(a, b); // Output: 1 2
// Destructuring objects
let { firstName, lastName } = { firstName: "John", lastName: "Doe" };
console.log(firstName, lastName); // Output: John Doe
38. What are spread and rest operators in JavaScript?
The spread (...)
operator spreads elements of an iterable (like arrays) into individual elements. The rest (...)
operator collects multiple elements into an array.
// Spread operator
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];
console.log(arr2); // Output: [1, 2, 3, 4, 5]
// Rest operator
function sum(...args) {
return args.reduce((acc, val) => acc + val, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
39. What are Map and Set objects in JavaScript?
Map objects hold key-value pairs and remember the original insertion order. Set objects are collections of unique values.
// Map
let map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
console.log(map.get('key1')); // Output: value1
// Set
let set = new Set();
set.add(1);
set.add(2);
set.add(2);
console.log(set.size); // Output: 2 (2 is added only once)
40. What is the purpose of the Symbol type in JavaScript?
Symbol is a new primitive type introduced in ES6 that represents a unique identifier. Symbols are immutable and unique, which makes them useful for defining object properties that should be distinct.
// Example of Symbol
let sym1 = Symbol('description');
let sym2 = Symbol('description');
console.log(sym1 === sym2); // Output: false (each symbol is unique)
Error Handling
41. How do you handle errors in JavaScript?
Using try...catch
blocks.
try {
// code that may throw an error
} catch (error) {
console.error(error);
}
42. What is a try...catch statement?
A construct for handling exceptions.
43. What are custom errors in JavaScript?
Custom errors are user-defined error types.
class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
44. How do you use the finally block in error handling?
The finally
block executes code after try and catch
, regardless of the outcome.
45. What is the Error object in JavaScript?
The Error
object represents an error in JavaScript and provides information about it.
Best Practices
46. What are some best practices for writing clean and maintainable JavaScript code?
Use meaningful variable names, write modular code, and comment your code.
47. How do you optimize JavaScript code for performance?
Avoid global variables, use efficient loops, and minimize DOM access.
48. What is linting, and why is it important?
Linting checks code for potential errors and enforces coding standards.
49. How do you ensure code quality in a JavaScript project?
Use automated tests, code reviews, and static analysis tools.
50. What are some common security considerations in JavaScript?
Avoid eval, sanitize user inputs, and use HTTPS.
Wrap
Understanding these 50 interview questions and their answers, you'll be well-prepared to tackle JavaScript challenges and demonstrate your proficiency in this ubiquitous programming language.
share
Software Engineer | Product Manager | Technical writer |