IT Training
Blog
Search

30 JavaScript Interview Questions and Answers for Freshers

Laptop screen showing JavaScript code in a code editor

The JavaScript interview questions that freshers face most often cover data types, scope and hoisting, closures, the this keyword, promises and async/await, the event loop and array methods. This guide gives you 30 of them with short, accurate answers and small code samples you can run in the browser console, so you can explain each idea in your own words instead of memorising definitions.

Key takeaways

  • Use let and const by default; var is function-scoped and hoisted with the value undefined, which causes subtle bugs.
  • A closure is a function that keeps access to the variables of the scope where it was created, even after that scope has finished running.
  • Use === for comparisons, because == converts types first and gives surprising results such as 0 == '' being true.
  • JavaScript runs on one thread; the event loop runs microtasks (promise callbacks) before the next macrotask (setTimeout callbacks).
  • Interviewers care more about how you reason through output-prediction questions than about textbook definitions.

How to use these JavaScript interview questions

Read the question, answer it aloud first, then check the answer and run the code. If you are preparing for a wider full stack role, pair this list with our full stack developer interview questions and the full stack developer roadmap.

JavaScript basics

1. What is JavaScript and where does it run?

JavaScript is a high-level, dynamically typed language. It runs in every web browser to make pages interactive, and on servers through runtimes such as Node.js. The language standard is called ECMAScript.

2. What are the primitive data types in JavaScript?

There are seven: string, number, bigint, boolean, undefined, null and symbol. Everything else, including arrays and functions, is an object. Primitives are copied by value; objects are passed around by reference.

3. What is the difference between var, let and const?

KeywordScopeRe-assignHoisting behaviour
varFunctionYesHoisted and set to undefined
letBlockYesHoisted but in the temporal dead zone
constBlockNoHoisted but in the temporal dead zone

Note that const stops re-assignment, not mutation. You can still push into a const array.

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

== converts both values to a common type before comparing; === compares value and type without conversion. Prefer ===.

console.log(0 == '');   // true
console.log(0 === '');  // false
console.log(null == undefined);  // true
console.log(null === undefined); // false

5. What is the difference between null and undefined?

undefined means a variable was declared but never given a value, or a property does not exist. null is a value you assign on purpose to say there is nothing here. typeof null returns 'object', which is a long-standing quirk of the language.

6. What is hoisting?

Before code runs, the engine registers declarations in their scope. Function declarations are fully hoisted, so you can call them before the line where they appear. var variables are hoisted with the value undefined. let and const are hoisted but cannot be read before their declaration line; reading them early throws a ReferenceError.

console.log(a); // undefined
var a = 5;
console.log(b); // ReferenceError
let b = 5;

7. What is the temporal dead zone?

It is the time between entering a block and reaching a let or const declaration. During that time the variable exists but any access throws a ReferenceError.

8. What are truthy and falsy values?

The falsy values are false, 0, -0, 0n, an empty string, null, undefined and NaN. Every other value, including an empty array and an empty object, is truthy.

Functions, scope and closures

9. What is scope in JavaScript?

Scope decides where a variable can be accessed. JavaScript has global scope, function scope and block scope. An inner scope can read variables from outer scopes, which is called lexical scoping, but not the other way round.

10. What is a closure? Give an example.

A closure is a function bundled with the variables from the scope where it was created. It is how JavaScript creates private state.

function makeCounter() {
  let count = 0;
  return function () {
    count++;
    return count;
  };
}
const next = makeCounter();
next(); // 1
next(); // 2

count cannot be changed from outside; only the returned function can reach it.

11. What is the difference between a function declaration and a function expression?

A declaration (function add() {}) is hoisted fully. An expression (const add = function () {}) is only available after the line runs. Arrow functions are a shorter form of expression.

12. How are arrow functions different from regular functions?

  • They do not have their own this; they use this from the surrounding scope.
  • They have no arguments object.
  • They cannot be used as constructors with new.

13. How does the this keyword work?

this depends on how a function is called. In a method call (obj.method()) it is obj. In a plain function call it is undefined in strict mode. With new it is the new object. Arrow functions take this from where they are defined. call, apply and bind let you set it explicitly.

14. What is the difference between call, apply and bind?

call runs the function with a given this and arguments listed one by one. apply does the same but takes the arguments as an array. bind does not run the function; it returns a new function with this fixed.

function greet(city) { return this.name + ' from ' + city; }
const user = { name: 'Asha' };
greet.call(user, 'Pune');
greet.apply(user, ['Pune']);
const g = greet.bind(user); g('Pune');

15. What is a higher-order function?

A function that takes another function as an argument or returns one. map, filter, reduce and setTimeout are common examples.

16. What are debouncing and throttling?

Both limit how often a function runs. Debouncing waits until events stop for a set time, which suits search boxes. Throttling runs the function at most once per interval, which suits scroll and resize handlers.

Objects, arrays and prototypes

17. What is prototypal inheritance?

Every object has a hidden link to another object called its prototype. When you read a property that the object does not have, JavaScript looks up the prototype chain. The class syntax is a cleaner way to write the same prototype-based model.

18. What is the difference between map, filter and reduce?

const nums = [1, 2, 3, 4];
nums.map(n => n * 2);              // [2, 4, 6, 8]
nums.filter(n => n % 2 === 0);     // [2, 4]
nums.reduce((sum, n) => sum + n, 0); // 10

map transforms each item, filter keeps items that pass a test, reduce combines all items into one value. None of them change the original array.

19. What is the difference between a shallow copy and a deep copy?

A shallow copy (spread syntax or Object.assign) copies the top level only; nested objects are still shared. A deep copy duplicates everything. Modern browsers and Node.js provide structuredClone() for deep copies.

20. What do the spread and rest operators do?

Both use three dots. Spread expands an array or object into individual items, for example […a, …b]. Rest collects remaining items into an array, for example function sum(…nums).

21. What is destructuring?

const user = { name: 'Ravi', role: 'tester' };
const { name, role } = user;
const [first, second] = [10, 20];

It unpacks values from arrays or properties from objects into variables in one line.

Asynchronous JavaScript

22. What is the event loop?

JavaScript runs one piece of code at a time on a single thread. Slow work such as timers and network calls is handed to the browser or Node.js. When it finishes, its callback waits in a queue. The event loop takes the next callback when the call stack is empty, and it always empties the microtask queue (promise callbacks) before taking the next macrotask (such as a setTimeout callback).

23. What is the output of this code?

console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');

The output is A, D, C, B. Synchronous code runs first, then the promise callback (a microtask), then the timer callback (a macrotask).

24. What is a promise?

A promise is an object that represents a value that will be available later. It is pending, then either fulfilled or rejected. You handle it with then, catch and finally, or with await.

25. How do async and await work?

An async function always returns a promise. Inside it, await pauses that function until a promise settles, without blocking the rest of the program. Wrap awaits in try and catch to handle errors.

async function loadUser(id) {
  try {
    const res = await fetch('/api/users/' + id);
    if (!res.ok) throw new Error('Request failed');
    return await res.json();
  } catch (err) {
    console.error(err.message);
  }
}

26. What is the difference between Promise.all and Promise.allSettled?

Promise.all fails as soon as one promise rejects. Promise.allSettled waits for every promise and returns the status and result of each, which is useful when you want partial results.

27. What is callback hell and how do you avoid it?

It is deeply nested callbacks that are hard to read and handle errors in. Promises and async/await flatten the code so each step reads top to bottom.

Browser and DOM questions

28. What is event bubbling and event delegation?

When an event fires on an element it bubbles up through its parents. Event delegation uses this: you add one listener on a parent and check event.target, instead of adding a listener to every child. It saves memory and works for elements added later.

29. What is the difference between localStorage, sessionStorage and cookies?

localStorage keeps data until it is cleared. sessionStorage keeps it only for the browser tab session. Cookies are small, are sent to the server with every request and can have an expiry date. Never store passwords or tokens that grant access in localStorage on a site that may have third-party scripts.

30. What does use strict do?

It turns on strict mode, which throws errors for silent mistakes such as assigning to an undeclared variable, and makes this undefined in plain function calls. ES modules and classes are in strict mode automatically.

How to prepare for a JavaScript interview

  • Practise output-prediction questions on hoisting, closures, this and the event loop, because they show how well you understand the language.
  • Write small programs without a framework: a to-do list, a debounced search box and a fetch call with error handling.
  • Be ready to explain one project line by line, including why you chose let or const and how you handled errors.
  • Revise array methods and string methods until you can use them without looking them up.

If you are also preparing for back-end rounds, revise how JavaScript runs on the server through our MERN stack guide.

Frequently asked questions

Are JavaScript interview questions different for freshers and experienced developers?

Yes. Freshers are mostly asked about fundamentals such as data types, scope, closures and promises. Experienced developers get deeper questions on performance, architecture, testing and framework internals.

Do I need to learn TypeScript for a JavaScript interview?

Not for most fresher roles, but many companies use TypeScript, so knowing basic types and interfaces is a plus. Get strong in JavaScript first, because TypeScript is built on it.

Which topics are asked most in JavaScript interviews?

Closures, hoisting, the this keyword, == versus ===, promises and async/await, the event loop and array methods come up most often, usually as code you must predict the output of.

How long does it take to prepare for a JavaScript interview?

If you already know the basics, two to three weeks of daily practice on these topics and a couple of small projects is usually enough to answer confidently.

Find more guides in our full stack development section.

Other articles

Radium4 — IT training blog

Practical, plain-English guides for DevOps, cloud, data, Python, testing and security learners.