JavaScript Interview Questions for Freshers
JavaScript is a high-level, interpreted programming language that conforms to the ECMAScript specification. It is dynamic, weakly typed, prototype-based, and multi-paradigm.
Key features include:
- Client-side scripting that runs in web browsers
- Provides dynamic interactivity on websites
- Supports object-oriented programming
- Handles events effectively
- Performs form validation
- Can create and manage cookies
- Also used server-side with environments like Node.js
JavaScript has 8 fundamental data types:
- String – represents textual data
- Number – represents both integer and floating-point numbers
- BigInt – represents integers of arbitrary length
- Boolean – logical values: true or false
- Undefined – variable declared but not assigned
- Null – intentional absence of a value
- Symbol – unique and immutable primitive, often for object keys
- Object – collections of key-value pairs and complex entities
JavaScript is dynamically typed, so variables can hold any type without explicit declaration.
These keywords differ in scoping, hoisting, and reassignment:
- var: Function-scoped, can be redeclared and updated, hoisted with
undefined. - let: Block-scoped, can be updated but not redeclared, hoisted but not initialized (TDZ).
- const: Block-scoped, cannot be updated or redeclared, must be initialized at declaration. Objects remain mutable.
In modern JavaScript, let and const are preferred to avoid common bugs from var.
Hoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation.
- Variables declared with var – hoisted and initialized with
undefined. - let and const – hoisted but not initialized (Temporal Dead Zone).
- Function declarations – fully hoisted (name and body).
- Function expressions – follow variable hoisting rules.
The this keyword refers to the object executing the current function. Its value depends on context:
- In a method: Refers to the owner object
- Alone: Refers to global object (
windowin browsers) - In a function: Refers to global object (non-strict) or
undefined(strict) - In an event: Refers to the element that triggered the event
- With call/apply/bind: Explicitly set
- Arrow functions: Inherit
thisfrom their parent scope
A closure is a function that has access to:
- Its own scope
- The outer function's scope
- The global scope
Closures allow data privacy and encapsulation, function factories, and partial applications.
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
A promise represents the eventual result of an asynchronous operation.
- Pending: Initial state
- Fulfilled: Operation completed successfully
- Rejected: Operation failed
Promises help avoid callback hell and provide chaining with .then() and .catch(). They also integrate with async/await for cleaner async code.
Both compare values, but differ in type coercion:
==– performs type coercion before comparing===– strict equality, checks both type and value
Examples:
5 == '5'→ true5 === '5'→ falsenull == undefined→ truenull === undefined→ false
Arrow functions (=>) are concise function expressions introduced in ES6. Differences:
- Shorter syntax
- No own
this(inherits lexicalthis) - No
argumentsobject - Cannot be used as constructors
- Not suitable for object methods needing
this - Cannot use
yield(not generators)
The event loop manages concurrency in JavaScript, allowing non-blocking operations despite being single-threaded.
Components:
- Call Stack – tracks function calls
- Heap – memory allocation
- Queue – stores messages (callbacks)
The event loop moves tasks from the queue to the stack when it’s empty, enabling async execution.
null and undefined are both primitive values, but they represent different concepts:
- undefined – A variable that has been declared but not assigned a value.
- null – An explicit assignment that represents 'no value' or 'empty'.
In short: undefined means 'not assigned', while null means 'intentionally empty'.
A function in JavaScript is a block of code designed to perform a specific task. Functions can take inputs, process them, and return outputs.
Types of functions:
- Function Declaration: Standard way to define a function using the
functionkeyword. - Function Expression: Assigning a function to a variable.
- Arrow Function: A shorter syntax introduced in ES6 (
() => {}). - Anonymous Function: Functions without a name, often used inline.
- Immediately Invoked Function Expression (IIFE): A function executed right after it is defined.
These keywords are used to declare variables, but they behave differently:
- var: Function-scoped, can be redeclared and updated, hoisted.
- let: Block-scoped, can be updated but not redeclared in the same scope.
- const: Block-scoped, cannot be updated or redeclared. Values are constant references, but objects/arrays can still be mutated.
Both are comparison operators, but they behave differently:
- == (Equality): Compares values after type conversion (loose comparison).
- === (Strict Equality): Compares both value and type without type conversion.
Example: 5 == '5' → true, but 5 === '5' → false.
Synchronous programming: Code runs line by line, blocking further execution until the current line finishes.
Asynchronous programming: Allows non-blocking execution, so tasks like API calls, timers, or file reads can happen without stopping other code.
JavaScript uses callbacks, Promises, and async/await to handle asynchronous operations.
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
States of a Promise:
- Pending: Initial state, not yet fulfilled or rejected.
- Fulfilled: Operation completed successfully.
- Rejected: Operation failed.
Example: fetch('url').then(response => ...).catch(error => ...)
async/await is syntax sugar built on top of Promises that makes asynchronous code look synchronous.
async: Declares a function that always returns a Promise.
await: Pauses execution until the Promise resolves or rejects.
Example:
async function fetchData() {
const response = await fetch('url');
const data = await response.json();
console.log(data);
}A closure is created when a function 'remembers' the variables from its outer scope even after the outer function has finished executing.
Closures allow functions to have private variables.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
return count;
}
}
const counter = outer();
counter(); // 1
counter(); // 2All three are used to set the this value explicitly in functions:
- call(): Invokes the function immediately, passing arguments one by one.
- apply(): Invokes the function immediately, passing arguments as an array.
- bind(): Returns a new function with
thisbound, but does not invoke immediately.
Example: func.call(obj, a, b), func.apply(obj, [a, b]), const f = func.bind(obj)
Events are actions or occurrences that happen in the browser (like a user clicking a button, typing, or resizing a window).
Event Listeners are functions that wait for specific events to happen and then run code.
Example:
document.getElementById('btn').addEventListener('click', function() {
alert('Button clicked!');
});