JavaScript Interview Questions and Answers for 2025



Lupa will help you hire top talent in Latin America.
Book a Free ConsultationLupa helps you build, manage, and pay your remote team. We deliver pre-vetted candidates within a week!
Book a Free ConsultationJavaScript is the backbone of modern web pages and applications, powering everything from interactive user interfaces to robust backend systems. As a versatile programming language and scripting language, it's essential for both frontend and backend development, making it a must-have skill for developers worldwide. Mastering javascript interview questions is crucial for anyone aiming to land a top developer role.
This guide covers the most relevant javascript interview questions and answers, offering actionable insights and practical code examples. Whether you're freshers entering the field or experienced engineers, you'll be equipped to tackle interviews with confidence.
JavaScript Interview Questions for Freshers
1. What are the different data types in JavaScript?
JavaScript code has primitive data types and non-primitive data types:
Primitive Data Types:
// String
const name = "Lupa Developer";
console.log(typeof name); // "string"
// Number (both integers and floats)
const age = 25;
console.log(typeof age); // "number"
// Boolean
const isActive = true;
console.log(typeof isActive); // returns true for boolean check
// Undefined
let unassigned;
console.log(typeof unassigned); // "undefined"
// Null
const data = null;
console.log(typeof data); // "object" (JavaScript quirk)
// Symbol (ES6+)
const uniqueKey = Symbol('id');
// BigInt
const largeNumber = 123n;
Non-Primitive: Objects, arrays, and functions are all object types.
2. What is the difference between == and ===?
This is one of the most common javascript interview questions and answers.
// Loose equality (==) allows type coercion
console.log(5 == '5'); // returns true (string coerced to number)
console.log(true == 1); // returns true
console.log(null == undefined); // returns true
// Strict equality (===) - no type coercion
console.log(5 === '5'); // false (different types)
console.log(true === 1); // false
console.log(null === undefined); // false
// Best practice: Always use === for predictable results
3. Explain the difference between var, let, and const.
These keywords have different scoping rules:
// var: function scope, hoisted
function varExample() {
if (true) {
var functionScoped = "Available throughout function";
}
console.log(functionScoped); // Works - var ignores block scope
}
// let: block scope, temporal dead zone
function letExample() {
if (true) {
let blockScoped = "Only in this block";
}
// console.log(blockScoped); // ReferenceError
}
// const: block scope, immutable reference
const immutableRef = { name: "Test" };
immutableRef.name = "Updated"; // Works - object is mutable
// immutableRef = {}; // Error - reference is immutable
// Hoisting behavior
console.log(varVariable); // undefined
console.log(letVariable); // ReferenceError: temporal dead zone
var varVariable = "var value";
let letVariable = "let value";
const constVariable = "const value";
4. What is hoisting in JavaScript?
Hoisting moves variable declarations and function declarations to the top of their scope during compile-time:
// Variable hoisting
console.log(hoistedVar); // undefined (declaration hoisted, not initialization)
var hoistedVar = "Hello";
// Function declaration hoisting
console.log(hoistedFunction()); // "I work!" - fully hoisted
function hoistedFunction() {
return "I work!";
}
// Function expression - only variable hoisted
console.log(expressed); // undefined
console.log(expressed()); // TypeError
var expressed = function() {
return "Not hoisted";
};
// let and const have temporal dead zone
console.log(modernVar); // ReferenceError
let modernVar = "Block scoped";
5. What is strict mode?
Strict mode enables restricted Java variant using "use strict":
"use strict";
function strictExample() {
// Prevents implicit global variables
// undeclaredVar = "error"; // ReferenceError in strict mode
// this is undefined in functions (not global object)
console.log(this); // undefined in strict mode
// Prevents duplicate parameters
// function invalid(a, a) {} // SyntaxError in strict mode
}
6. Explain the this keyword.
The this keyword refers to the object executing the current function:
// Global context
console.log(this); // window object (browsers) or undefined (strict mode)
// Object method
const person = {
name: "Ana",
greet: function() {
console.log(`Hello, ${this.name}`); // this refers to person
}
};
// Arrow functions inherit lexical this
const obj = {
name: "Test",
regularMethod: function() {
console.log(this.name); // "Test"
},
arrowMethod: () => {
console.log(this.name); // undefined (lexical this)
}
};
// Constructor function
function Person(name) {
this.name = name;
this.greet = function() {
return `Hello, ${this.name}`;
};
}
const newPerson = new Person("Carlos");
7. What are closures?
Closures occur when functions access variables from outer scope even after outer function execution:
// Basic closure
function outerFunction(x) {
return function innerFunction(y) {
console.log(`Outer: ${x}, Inner: ${y}`);
return x + y;
};
}
const closure = outerFunction(10);
closure(5); // Inner function remembers x = 10
// Practical use: private variables
function createCounter() {
let count = 0; // Private variable
return {
increment: function() {
count++;
return count;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.getCount()); // 1
// count is not directly accessible
// Memoization using closures for performance
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) return cache[key];
const result = fn.apply(this, args);
cache[key] = result;
return result;
};
}
8. What is the difference between function declarations and function expressions?
Function declarations are fully hoisted, while function expressions follow variable hoisting:
// Function Declaration - fully hoisted
console.log(declared()); // Works!
function declared() {
return "I'm hoisted";
}
// Function Expression - variable hoisted, not function
console.log(expressed); // undefined
console.log(expressed()); // TypeError
var expressed = function() {
return "Not hoisted";
};
// Arrow Functions (ES6+)
const arrow = (name) => `Hello, ${name}`;
// IIFE (Immediately Invoked Function Expression)
(function() {
console.log("Executed immediately");
})();
9. What are callback functions?
A callback function is passed as argument to another function and executed later:
// Basic callback
function processData(data, callback) {
console.log("Processing data...");
callback(data);
}
function displayResult(result) {
console.log("Result:", result);
}
processData("user data", displayResult);
// Array methods use callbacks
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(num) {
return num * 2;
});
// Asynchronous operations
function fetchUserData(userId, callback) {
setTimeout(() => {
const userData = { id: userId, name: `User ${userId}` };
callback(userData);
}, 1000);
}
fetchUserData(123, function(user) {
console.log("Received:", user.name);
});
10. What are higher-order functions?
Higher-order functions take other functions as parameters or return functions:
// Array methods are higher-order functions
const numbers = [1, 2, 3, 4, 5];
// map transforms each element
const doubled = numbers.map(n => n * 2);
// filter selects elements
const evens = numbers.filter(n => n % 2 === 0);
// reduce accumulates values
const sum = numbers.reduce((acc, n) => acc + n, 0);
// Custom higher-order function
function withLogging(fn) {
return function(...args) {
console.log('Function calls with:', args);
return fn.apply(this, args);
};
}
const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
Core JavaScript Concepts
11. What is the event loop?
The event loop enables non-blocking asynchronous operations in single-threaded JavaScript:
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
Promise.resolve().then(() => console.log('Promise'));
console.log('End');
// Output: Start, End, Promise, Timeout
// Explanation: Microtasks (Promises) run before macrotasks (setTimeout)
12. What are promises and async/await?
Promises handle asynchronous operations better than callbacks:
// Creating promises
function fetchUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) {
resolve({ id, name: `User ${id}` });
} else {
reject(new Error("Invalid ID"));
}
}, 1000);
});
}
// Using promises
fetchUser(1)
.then(user => console.log(user.name))
.catch(error => console.error(error));
// async/await syntax (cleaner)
async function getUserData() {
try {
const user = await fetchUser(1);
console.log(user.name);
return user;
} catch (error) {
console.error(error);
}
}
13. What are arrow functions?
Arrow functions provide concise syntax and lexical this binding:
// Traditional function
function traditional(name) {
return `Hello, ${name}`;
}
// Arrow function
const arrow = (name) => `Hello, ${name}`;
const singleParam = name => `Hi, ${name}`;
const noParams = () => "Hello World";
// Key difference: lexical this
const obj = {
name: "Lupa",
regularMethod: function() {
console.log(this.name); // "Lupa"
},
arrowMethod: () => {
console.log(this.name); // undefined (lexical this)
}
};
14. What is prototypal inheritance?
JavaScript uses prototypal inheritance where objects inherit from other objects:
// Constructor function approach
function Animal(type) {
this.type = type;
}
Animal.prototype.speak = function() {
console.log(`${this.type} makes a sound`);
};
function Dog(name) {
Animal.call(this, 'Dog');
this.name = name;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
const myDog = new Dog("Buddy");
myDog.speak(); // Inherited method
// ES6 Classes (syntactic sugar over prototypes)
class Vehicle {
constructor(make) {
this.make = make;
}
start() {
console.log(`${this.make} starting`);
}
}
class Car extends Vehicle {
honk() {
console.log("Beep beep!");
}
}
const myCar = new Car("Toyota");
DOM and Web APIs
15. What is the DOM?
The Document Object Model (DOM) represents HTML as objects JavaScript can manipulate:
// Selecting HTML elements
const element = document.getElementById('main');
const buttons = document.getElementsByClassName('btn');
const paragraphs = document.getElementsByTagName('p');
// Modern selectors
const firstButton = document.querySelector('.btn');
const allButtons = document.querySelectorAll('.btn');
// Manipulating elements
if (element) {
element.textContent = 'New content';
element.style.color = 'blue';
element.classList.add('active');
element.setAttribute('data-id', '123');
}
// Creating elements
const newDiv = document.createElement('div');
newDiv.textContent = 'Dynamic content';
document.body.appendChild(newDiv);
// Event handling
document.addEventListener('click', (event) => {
if (event.target.matches('.btn')) {
console.log('Button clicked');
}
});
16. What is the difference between setTimeout and setInterval?
Both handle timing but behave differently:
// setTimeout: execute once after delay
setTimeout(() => {
console.log("Executed once after 2 seconds");
}, 2000);
// setInterval: execute repeatedly
const intervalId = setInterval(() => {
console.log("Repeats every 3 seconds");
}, 3000);
// Clear interval
setTimeout(() => {
clearInterval(intervalId);
}, 10000);
// Recursive setTimeout (alternative to setInterval)
function recursiveTimeout() {
console.log("Recursive execution");
setTimeout(recursiveTimeout, 1000);
}
Modern JavaScript Features
17. What are template literals?
Template literals enable string interpolation and multi-line strings:
const name = 'Ana';
const age = 28;
// String interpolation
const greeting = `Hello, my name is ${name} and I'm ${age} years old.`;
// Multi-line strings
const multiline = `
This is a multi-line string
that preserves formatting
and supports ${name} interpolation.
`;
// Expression evaluation
const result = `The sum is: ${5 + 3}`;
const conditional = `Status: ${age >= 18 ? 'Adult' : 'Minor'}`;
18. What is destructuring?
Destructuring extracts values from arrays or object properties:
// Array destructuring
const colors = ['red', 'green', 'blue'];
const [primary, secondary, ...others] = colors;
// Object destructuring
const user = { name: 'Carlos', email: 'carlos@example.com', age: 30 };
const { name, email, age = 25 } = user; // Default values supported
// Function parameter destructuring
function createUser({ name, email, role = 'User' }) {
return { name, email, role, id: Date.now() };
}
// Nested destructuring
const response = {
data: {
user: { name: 'Maria', settings: { theme: 'dark' } }
}
};
const { data: { user: { name: userName, settings: { theme } } } } = response;
19. What is the spread operator?
The spread operator expands iterables and objects:
// Array spreading
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
// Object spreading
const user = { name: 'Ana', age: 28 };
const updatedUser = { ...user, email: 'ana@example.com' };
// Function arguments
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Clone arrays/objects (shallow copy)
const originalArray = [1, 2, 3];
const clonedArray = [...originalArray];
Error Handling and Debugging
20. What are the different error types?
JavaScript has several built-in error types:
// ReferenceError: undeclared variables
try {
console.log(undeclaredVariable);
} catch (error) {
console.log(error instanceof ReferenceError); // true
}
// TypeError: wrong type operations
try {
const num = 42;
num.toUpperCase();
} catch (error) {
console.log(error instanceof TypeError); // true
}
// SyntaxError: invalid syntax
try {
eval('const invalid syntax');
} catch (error) {
console.log(error instanceof SyntaxError); // true
}
// Custom errors
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
// Global error handling
window.addEventListener('error', (event) => {
console.error('Global error:', event.error);
});
Coding Questions
21. What is the output of these code snippets?
Question 1:
console.log(typeof NaN); // ?
console.log(NaN === NaN); // ?
console.log(isNaN('hello')); // ?
Answer: "number", false, returns true (NaN is not a number type but typeof returns "number")
Question 2:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
Answer: Prints 3, 3, 3 because var is function-scoped and all callbacks reference the same i.
22. Common Implementation Challenges
Remove duplicates from array:
function removeDuplicates(arr) {
return [...new Set(arr)]; // Using Set
}
// Alternative with filter
function removeDupsFilter(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
Debounce function:
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// Usage
const debouncedSearch = debounce((query) => {
console.log('Searching:', query);
}, 300);
Conclusion
This guide covers the most frequently asked javascript interview questions across technical interviews. Focus on understanding these core concepts: data types, scope, closures, asynchronous operations, and modern ES6+ features.
Key preparation tips:
- Master fundamentals like hoisting, the this keyword, and prototypal inheritance
- Practice async patterns with promises and async/await
- Understand DOM manipulation and event handling
- Learn modern JavaScript syntax and features
- Practice common coding challenges and output prediction questions
Success in JavaScript interviews comes from solid fundamentals combined with practical problem-solving skills. Keep practicing these concepts and you'll be well-prepared for any technical interview.
Ready to advance your JavaScript career?
Lupa connects premium LatAm developers with companies that value technical depth and cultural alignment. We understand JavaScript interview nuances and match developers with roles where their skills truly shine.
Book a discovery call to discuss strategic career opportunities—quality matches with companies that appreciate strong engineering fundamentals.
Strategic recruiting for high-bar teams. Not faster, not cheaper—just better.
Frequently Asked Questions
What are basic JavaScript interview questions?
Basic JavaScript interview questions cover core concepts like data types using the typeof operator, variable declarations with var keyword, let keyword, and const keyword, and scope differences between global scope and local scope. Common topics include javascript function basics, javascript objects manipulation, array prototype methods, and creating a new array. Interviews often test ECMAScript 2015 features, modules understanding, and basic asynchronous javascript patterns.
How to ace a JavaScript interview?
Master fundamentals: scope (global scope vs local scope), lexical scoping, and runtime behavior with different variable declarations. Practice javascript function implementations and javascript objects manipulation. Understand OOP concepts and array prototype methods. Study modern features like modules, asynchronous javascript, and specialized collections like WeakMap and WeakSet. Know how JavaScript works in browsers and Node.js environments, including CSS integration use case scenarios.
How do you explain "this" in JavaScript?
The "this" keyword in a javascript function refers to the executing object, but its single value depends on the call context. In global scope, "this" is the global object or undefined in strict mode. In javascript objects methods, "this" refers to the owning object. Arrow functions use lexical scoping, inheriting "this" from the enclosing scope. This behavior is consistent across different runtime environments including Node.js.
What is the difference between == and === in JavaScript interview questions?
These comparison operators differ in type handling: == performs type coercion before comparison, while === compares both value and type without coercion. The == operator can produce unexpected results across different data types, while === provides predictable behavior. Use === for most use case scenarios to avoid runtime issues. This applies whether building frontend applications with CSS or backend services with Node.js.


