JavaScript Interview Questions for Freshers: 50+ Questions & Answers
Are you preparing for a JavaScript interview as a fresher or beginner? This guide covers 50+ JavaScript interview questions and answers that can help you prepare for frontend developer, web developer, and JavaScript developer interviews.
The questions start with JavaScript basics and gradually move to important topics such as variables, data types, functions, arrays, objects, DOM, ES6, promises, asynchronous JavaScript, and more.
If you are a beginner, focus on understanding the concepts and examples instead of memorizing the answers.
JavaScript Interview Questions for Freshers
1. What is JavaScript?
JavaScript is a high-level programming language mainly used to make web pages interactive and dynamic.
HTML is used to create the structure of a webpage, CSS is used for styling, and JavaScript is used to add behavior and functionality.
For example, JavaScript can be used to:
- Validate forms
- Handle button clicks
- Change HTML content
- Modify CSS dynamically
- Make API requests
- Create interactive web applications
- Build frontend applications using libraries such as React
2. What is the difference between JavaScript and Java?
JavaScript and Java are different programming languages.
JavaScript is commonly used for web development and can run in browsers as well as server-side environments such as Node.js.
Java is a general-purpose programming language commonly used for backend applications, enterprise software, Android development, and other systems.
The names are similar, but their syntax, execution environments, and use cases are different.
3. How do you add JavaScript to an HTML page?
<script> tag.<script> console.log("Hello JavaScript"); </script>JavaScript can be added to an HTML page using the
You can also place JavaScript in an external file:
<script src="script.js"></script>
Using an external JavaScript file is generally preferable for larger projects because it keeps HTML and JavaScript separate.
4. What are variables in JavaScript?
Variables are used to store data values.
var name = "Rahul"; let age = 25; const country = "India";JavaScript provides three commonly used keywords for declaring variables:
let and const are generally preferred in modern JavaScript.
5. What is the difference between var, let, and const?
var, let, and const are used to declare variables, but they have different behavior.
| Feature | var | let | const |
|---|---|---|---|
| Function scoped | Yes | No | No |
| Block scoped | No | Yes | Yes |
| Can be reassigned | Yes | Yes | No |
| Can be redeclared in same scope | Yes | No | No |
Example:let age = 25; age = 26; const country = "India"; // country = "USA"; // Error
For modern JavaScript development, use let when reassignment is required and const when the binding should not be reassigned.
6. What are the data types in JavaScript?
JavaScript has primitive and non-primitive/reference types.
Common primitive types include:
- String
- Number
- BigInt
- Boolean
- Undefined
- Null
- Symbol
Objects, arrays, and functions are reference types.
Example:let name = "Rahul"; let age = 25; let isDeveloper = true; let value; let data = null;
7. What is the difference between null and undefined?
undefined generally means a value has not been assigned.let name; console.log(name); // undefined
null is an explicitly assigned value representing the absence of an object/value.let user = null;
8. What is the difference between == and ===?
== performs loose equality comparison and may perform type conversion.
=== performs strict equality comparison and checks both value and type.console.log(5 == "5"); // true console.log(5 === "5"); // false
In most situations, strict equality (===) is preferred because its behavior is more predictable.
9. What is type coercion in JavaScript?
Type coercion occurs when JavaScript converts a value from one type to another.
For example:console.log("5" + 2); // "52"
Here, the number 2 is converted to a string during the operation.
Understanding type coercion is important because it can produce unexpected results if you are not familiar with JavaScript’s conversion rules.
10. What is a function in JavaScript?
A function is a reusable block of code designed to perform a particular task.function add(a, b) { return a + b; } console.log(add(10, 20));
Functions can accept parameters and return values.
11. What is an arrow function?
An arrow function is a shorter syntax for writing functions.
Traditional function:function add(a, b) { return a + b; }
Arrow function:const add = (a, b) => a + b;
Arrow functions also have different this behavior from regular functions.
12. What is an array in JavaScript?
An array is an ordered collection of values.const fruits = ["Apple", "Banana", "Mango"];
You can access elements using their index:console.log(fruits[0]); // Apple
JavaScript provides many array methods such as map(), filter(), reduce(), find(), join(), and slice().
13. What is an object in JavaScript?
An object stores data using key-value pairs.const user = { name: "Rahul", age: 25, city: "Delhi" };
You can access properties using dot notation:console.log(user.name);
14. What is the difference between an array and an object?
An array is generally used for an ordered collection of values.const colors = ["Red", "Blue", "Green"];
An object is generally used to represent related properties using key-value pairs.const user = { name: "Rahul", age: 25 };
15. What is the DOM?
DOM stands for Document Object Model.
The browser creates a representation of an HTML document that JavaScript can interact with.
For example:document.getElementById("title").textContent = "Hello JavaScript";
JavaScript can use the DOM to read, modify, add, or remove elements from a webpage.
16. How do you select an HTML element using JavaScript?
Common methods include:document.getElementById("title"); document.querySelector(".box"); document.querySelectorAll(".item");
querySelector() returns the first element matching a CSS selector, while querySelectorAll() returns a collection of matching elements.
17. What is an event in JavaScript?
An event is an action or occurrence that JavaScript can respond to.
Examples include:
- Click
- Mouse movement
- Keyboard input
- Form submission
- Page loading
Example:button.addEventListener("click", function () { console.log("Button clicked"); });
18. What is event bubbling?
Event bubbling is a mechanism in which an event triggered on a nested element can propagate upward through its parent elements.
For example, if a button is inside a div and the button is clicked, the event can propagate from the button to the div and then to its ancestors.
Event bubbling is also important when implementing event delegation.
19. What is event delegation?
Event delegation is a technique where an event listener is attached to a parent element instead of adding separate listeners to multiple child elements.
Example:document.querySelector("#list").addEventListener("click", function (event) { if (event.target.matches("li")) { console.log(event.target.textContent); } });
It can be useful when working with many elements or dynamically created elements.
20. What is scope in JavaScript?
Scope determines where a variable can be accessed.
Common types include:
- Global scope
- Function scope
- Block scope
For example:if (true) { let message = "Hello"; console.log(message); }
The message variable is available inside the block where it was declared.
21. What is hoisting in JavaScript?
Hoisting describes JavaScript’s handling of certain declarations during the creation of an execution context.
For example:console.log(name); var name = "Rahul";
This does not behave the same way as accessing a let or const variable before its declaration.
Understanding hoisting is important when answering JavaScript interview questions involving variables and functions.
22. What is a callback function?
A callback is a function passed to another function as an argument so that it can be called later.
Example:function greet(name, callback) { console.log("Hello " + name); callback(); } greet("Rahul", function () { console.log("Welcome"); });
Callbacks are commonly used with asynchronous operations and event handling.
23. What is a Promise in JavaScript?
A Promise represents the eventual completion or failure of an asynchronous operation.
A Promise can be in states such as:
- Pending
- Fulfilled
- Rejected
Example:const promise = new Promise((resolve, reject) => { resolve("Success"); }); promise.then((result) => { console.log(result); });
24. What is async/await?
async and await provide a convenient syntax for working with Promises.
Example:async function getData() { const response = await fetch("https://example.com/data"); const data = await response.json(); console.log(data); }
An async function returns a Promise, and await can be used inside an async function to wait for a Promise to settle.
25. What is the difference between synchronous and asynchronous JavaScript?
Synchronous code generally executes one operation after another.
Asynchronous programming allows certain operations, such as network requests, to be handled without requiring the entire program to wait for the operation to finish.
Promises, callbacks, and async/await are commonly used for asynchronous programming.
26. What is setTimeout() in JavaScript?
setTimeout() schedules a function to run after a specified delay.setTimeout(() => { console.log("Hello"); }, 2000);
The delay does not mean that the callback will execute at exactly that moment; execution also depends on the JavaScript runtime and event loop.
27. What is setInterval()?
setInterval() repeatedly executes a function after a specified time interval.setInterval(() => { console.log("Hello"); }, 1000);
The interval can be stopped using clearInterval().
28. What is the difference between map(), filter(), and reduce()?
map() creates a new array by transforming each element.const numbers = [1, 2, 3]; const result = numbers.map(num => num * 2); console.log(result);
filter() creates a new array containing elements that satisfy a condition.const result = numbers.filter(num => num > 1);
reduce() can combine array values into a single result.const result = numbers.reduce((sum, num) => sum + num, 0);
29. What is the difference between forEach() and map()?
forEach() is generally used to perform an operation for each element.
map() creates and returns a new array containing the transformed values.const numbers = [1, 2, 3]; numbers.forEach(num => console.log(num)); const doubled = numbers.map(num => num * 2);
30. What is destructuring in JavaScript?
Destructuring allows values to be extracted from arrays or properties to be extracted from objects into variables.
Array example:const numbers = [10, 20]; const [first, second] = numbers;
Object example:const user = { name: "Rahul", age: 25 }; const { name, age } = user;
31. What is the spread operator?
The spread operator (...) expands elements from an iterable or properties from an object.
Example:const first = [1, 2]; const second = [3, 4]; const result = [...first, ...second]; console.log(result);
It is frequently used with arrays and objects.
32. What is the rest parameter?
The rest parameter allows a function to collect multiple arguments into an array.function add(...numbers) { return numbers.reduce((sum, num) => sum + num, 0); } console.log(add(10, 20, 30));
The ...numbers syntax is called a rest parameter in this context.
33. What are template literals?
Template literals allow strings to be written using backticks and support embedded expressions.const name = "Rahul"; console.log(`Hello ${name}`);
They are useful for creating dynamic strings.
34. What is a closure in JavaScript?
A closure occurs when a function retains access to variables from its surrounding lexical environment even after the outer function has finished executing.
Example:function counter() { let count = 0; return function () { count++; return count; }; } const increment = counter(); console.log(increment()); console.log(increment());
Closures are an important topic in JavaScript interviews.
35. What is the this keyword in JavaScript?
this refers to a value determined by how a function is called.
For example, when a method is called as an object property, this commonly refers to the object used for that call.
The behavior of this differs between regular functions and arrow functions, making it a common interview topic.
36. What are call(), apply(), and bind()?
These methods are used to control the this value when working with functions.
Example:function greet(city) { console.log(this.name + " from " + city); } const user = { name: "Rahul" }; greet.call(user, "Delhi");
call() and apply() invoke the function immediately with a specified this value.
bind() creates a new function with a specified this value.
37. What is the difference between local and global variables?
A global variable can generally be accessed from different parts of a program within its applicable global scope.
A local variable is declared within a specific function or block and has a more limited scope.
It is generally better to keep variables scoped as narrowly as practical.
38. What is an IIFE?
IIFE stands for Immediately Invoked Function Expression.
It is a function expression that is executed immediately after it is created.(function () { console.log("Executed immediately"); })();
IIFEs were commonly used to create private scopes before modern JavaScript modules became widespread.
39. What is strict mode in JavaScript?
Strict mode enables stricter parsing and error handling for certain JavaScript code.
It can be enabled using:"use strict";
Strict mode helps identify certain programming mistakes and changes some JavaScript behaviors.
40. What is JSON?
JSON stands for JavaScript Object Notation.
It is a text format commonly used for exchanging structured data.
Example:{ "name": "Rahul", "age": 25 }
JavaScript provides methods such as JSON.parse() and JSON.stringify() for working with JSON data.
41. What is JSON.parse()?
JSON.parse() converts a JSON-formatted string into a JavaScript value.const json = '{"name":"Rahul"}'; const user = JSON.parse(json); console.log(user.name);
42. What is JSON.stringify()?
JSON.stringify() converts a JavaScript value into a JSON string.const user = { name: "Rahul", age: 25 }; const json = JSON.stringify(user); console.log(json);
43. What is the difference between localStorage and sessionStorage?
Both are browser storage mechanisms.
localStorage keeps data until it is explicitly removed, subject to browser storage rules.
sessionStorage is associated with the current browser tab/session and is cleared when that page session ends.
Example:localStorage.setItem("name", "Rahul"); const name = localStorage.getItem("name");
44. What is the Fetch API?
The Fetch API is a browser API used to make network requests.
Example:fetch("https://example.com/data") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
It can also be used with async/await.
45. What is the JavaScript event loop?
JavaScript uses an event-driven execution model. The event loop coordinates the execution of JavaScript code with asynchronous tasks and callback processing.
A good understanding of the event loop helps explain questions involving:
setTimeout()- Promises
async/await- Call stack
- Microtasks
- Tasks
This is a common topic in intermediate and advanced JavaScript interviews.
46. What is the difference between shallow copy and deep copy?
A shallow copy copies the top-level structure while nested objects may still be shared.
A deep copy creates an independent copy of nested data as well.
For example, object spread:const copy = { ...original };
creates a shallow copy.
When deep cloning is appropriate, modern JavaScript environments may provide:const copy = structuredClone(original);
The appropriate approach depends on the data being copied.
47. What is debouncing in JavaScript?
Debouncing delays execution until a specified period has passed without another triggering event.
It is commonly used for:
- Search boxes
- Autocomplete
- Input validation
- Resize events
For example, instead of sending an API request on every keystroke, you can wait until the user stops typing.
48. What is throttling in JavaScript?
Throttling limits how frequently a function can execute within a given period.
It can be useful for events that fire frequently, such as:
- Scroll
- Mouse movement
- Window resize
Debouncing and throttling are common JavaScript interview topics.
49. What is the difference between null, undefined, and NaN?
undefined generally indicates that a value has not been assigned.
null represents an explicitly assigned absence of a value.
NaN means “Not-a-Number” and represents an invalid or undefined numeric result.
Example:let a; let b = null; let c = Number("hello"); console.log(a); // undefined console.log(b); // null console.log(c); // NaN
50. What are the most important JavaScript topics for a fresher interview?
Before attending a JavaScript interview, freshers should be comfortable with:
- Variables
- Data types
- Operators
var,let, andconst- Functions
- Arrow functions
- Arrays
- Objects
- Array methods
- String methods
- Scope
- Hoisting
- Closures
- DOM
- Events
- Event bubbling
- Event delegation
- Promises
- Async/await
setTimeout()setInterval()- JSON
- Fetch API
- ES6 features
- Destructuring
- Spread/rest operators
- Template literals
this- Local storage
- Event loop
- Debouncing
- Throttling
JavaScript Coding Questions for Freshers
Along with theoretical questions, many interviews include basic coding problems.
Practice problems such as:
- Reverse a string using JavaScript.
- Check whether a string is a palindrome.
- Find the largest number in an array.
- Find duplicate elements in an array.
- Remove duplicate elements from an array.
- Reverse an array.
- Find the sum of array elements.
- Count the frequency of characters in a string.
- Find the missing number in an array.
- Check whether a number is prime.
- Generate the Fibonacci sequence.
- Find the factorial of a number.
- Find the second-largest number in an array.
- Check whether two strings are anagrams.
- Flatten a nested array.
For coding interviews, don’t just memorize solutions. Understand the algorithm, explain your approach, and be able to discuss time and space complexity.
JavaScript Interview Preparation Tips for Freshers
Understand the fundamentals
Interviewers often start with basic JavaScript concepts before moving to advanced questions.
Make sure you understand the difference between concepts rather than memorizing definitions.
Practice writing code
Try solving JavaScript problems without looking at the solution.
Start with simple problems involving strings, arrays, objects, loops, and functions.
Understand why the output occurs
Output-based questions can test whether you actually understand JavaScript behavior.
Practice topics such as:
- Type coercion
- Scope
- Hoisting
- Closures
this- Promises
- Event loop
setTimeout()
Build small projects
Projects help you apply JavaScript concepts in real situations.
Good beginner projects include:
- Todo application
- Calculator
- Weather application
- Quiz application
- Digital clock
- Expense tracker
- CRUD application
- API-based application
Frequently Asked Questions
Is JavaScript difficult for freshers?
JavaScript can be challenging initially because it has many concepts that behave differently from simpler programming languages. Start with fundamentals and gradually learn advanced concepts such as closures, promises, asynchronous JavaScript, and the event loop.
Which JavaScript topics should freshers learn first?
Start with variables, data types, operators, conditions, loops, functions, arrays, objects, DOM manipulation, and events. Then move to ES6, promises, async/await, closures, and other advanced concepts.
How can I prepare for a JavaScript interview?
Study the fundamentals, practice coding problems, understand common interview concepts, build projects, and practice explaining your solutions clearly.
Is JavaScript enough for a frontend developer interview?
JavaScript is an important frontend skill, but frontend interviews may also cover HTML, CSS, browser concepts, accessibility, HTTP, APIs, Git, and a frontend framework such as React.
Conclusion
Preparing for a JavaScript interview is easier when you focus on understanding concepts instead of memorizing answers.
Start with JavaScript fundamentals such as variables, data types, functions, arrays, objects, DOM, and events. After that, learn ES6 features, promises, async/await, closures, the event loop, and other advanced concepts.
Practice coding problems regularly and build small JavaScript projects so that you can explain how you would use these concepts in real applications.