Top Javascript Interview Questions

JavaScriptvarletconstVariable Declaration
var is function-scoped and can be redeclared; it is hoisted with undefined. let is block-scoped, cannot be redeclared in the same scope, and is hoisted but not initialized. const is block-scoped, cannot be reassigned after declaration, but its properties can be modified if it's an object.
Example:
var x = 1;
let y = 2;
const z = 3;
x = 10; // OK
y = 20; // OK
z = 30; // Error
console.log(x, y, z);

JavaScriptHoistingVariable Scope
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope during compilation. var variables are hoisted and initialized with undefined; let and const are hoisted but not initialized, causing a Temporal Dead Zone.
Example:
console.log(x); // undefined
var x = 5;
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;

JavaScriptEquality OperatorStrict Equality
== performs type coercion before comparison, while === (strict equality) compares both value and type without coercion.
Example:
console.log(5 == '5'); // true
console.log(5 === '5'); // false
console.log(null == undefined); // true
console.log(null === undefined); // false

JavaScriptData Types
JavaScript has primitive types: undefined, null, boolean, number, bigint, string, symbol, and a non-primitive type: object (includes arrays, functions, etc.).
Example:
let a = 42; // number
let b = 'hello'; // string
let c = true; // boolean
let d = null; // null
let e = {}; // object
let f = Symbol('id'); // symbol

JavaScriptthis KeywordContext
this refers to the object executing the current function. Its value depends on the context: global (window in browsers), object for methods, constructor for new instances, or explicit binding with call/apply/bind.
Example:
const obj = {
    name: 'Test',
    getName: function() { return this.name; }
};
console.log(obj.getName()); // Test
const fn = obj.getName;
console.log(fn()); // undefined (or window.name in non-strict mode)

JavaScriptClosureScope
A closure is a function that retains access to its lexical scope's variables even after the outer function has executed. It enables data privacy and state preservation.
Example:
function outer() {
    let count = 0;
    return function inner() {
        return ++count;
    };
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

JavaScriptData Types
null represents an intentional absence of value, while undefined indicates a variable has been declared but not assigned. null is explicitly set; undefined is the default for uninitialized variables.
Example:
let a;
console.log(a); // undefined
let b = null;
console.log(b); // null
console.log(a == null); // true
console.log(a === null); // false

JavaScriptArrow FunctionsRegular Functions
Arrow functions (=>) are concise and do not bind their own this, inheriting it from the surrounding scope. Regular functions have their own this and can be used as constructors. Arrow functions cannot be used with new or as generators.
Example:
const regular = function() { return this; };
const arrow = () => this;
const obj = { fn: regular, arrowFn: arrow };
console.log(obj.fn()); // obj
console.log(obj.arrowFn()); // window (or enclosing this)

JavaScripttypeof OperatorType Checking
The typeof operator returns a string indicating the type of a value. It is used to check data types like 'number', 'string', 'object', 'undefined', etc.
Example:
console.log(typeof 42); // 'number'
console.log(typeof 'test'); // 'string'
console.log(typeof undefined); // 'undefined'
console.log(typeof null); // 'object' (historical quirk)

JavaScriptTemplate LiteralsString Interpolation
Template literals are strings enclosed in backticks (`) that support embedded expressions (${}) and multi-line text without concatenation.
Example:
const name = 'Alice';
const greeting = `Hello, ${name}!
Welcome!`;
console.log(greeting); // Hello, Alice!
// Welcome!

JavaScriptDOMDOM Access
The DOM (Document Object Model) is a tree-like representation of a webpage’s structure. Access elements using methods like getElementById, querySelector, or getElementsByClassName.
Example:
const element = document.getElementById('myId');
const div = document.querySelector('.myClass');
console.log(element.textContent);
div.style.color = 'blue';

JavaScriptType ConversionString to Number
Convert a string to a number using parseInt (for integers), parseFloat (for decimals), Number(), or the unary plus operator (+).
Example:
const str = '123.45';
console.log(parseInt(str)); // 123
console.log(parseFloat(str)); // 123.45
console.log(Number(str)); // 123.45
console.log(+str); // 123.45

JavaScriptEvent BubblingEvent Capturing
Event bubbling is when an event propagates from the target element up to the root (default). Event capturing (or trickling) is when the event propagates from the root down to the target. Use addEventListener’s capture option to control this.
Example:
document.getElementById('child').addEventListener('click', () => console.log('Child'), false); // Bubbling
document.getElementById('parent').addEventListener('click', () => console.log('Parent'), true); // Capturing

JavaScriptSynchronousAsynchronousExecution
Synchronous code executes sequentially, blocking until each operation completes. Asynchronous code runs non-blocking, allowing other tasks to proceed while waiting for operations like I/O.
Example:
console.log('Start');
setTimeout(() => console.log('Async'), 0); // Asynchronous
console.log('End'); // Start, End, Async

JavaScriptCallbacksAsynchronous Programming
A callback is a function passed as an argument to another function, executed after a task completes. It’s used for asynchronous operations like timers or API calls.
Example:
function fetchData(callback) {
    setTimeout(() => callback('Data'), 1000);
}
fetchData(data => console.log(data)); // Data (after 1s)

JavaScriptPromisesAsynchronous Programming
Promises represent the eventual completion (or failure) of an asynchronous operation, with states: pending, fulfilled, or rejected. They chain with .then() and .catch().
Example:
const promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve('Success'), 1000);
});
promise.then(result => console.log(result)).catch(err => console.log(err)); // Success

JavaScriptsetTimeoutsetIntervalTimers
setTimeout executes a function once after a delay (in milliseconds). setInterval executes a function repeatedly at a fixed interval. Both are asynchronous.
Example:
setTimeout(() => console.log('Delayed'), 1000); // Runs once after 1s
setInterval(() => console.log('Repeated'), 1000); // Runs every 1s

JavaScriptAsynchronous Programming
Asynchronous programming allows non-blocking execution, enabling tasks like API calls or timers to run without halting the main thread. It uses callbacks, promises, or async/await.
Example:
setTimeout(() => console.log('Async'), 1000);
console.log('Sync'); // Sync, then Async

JavaScriptfor...infor...ofLoops
for...in iterates over enumerable properties of an object (including inherited ones). for...of iterates over values of iterable objects like arrays or strings.
Example:
const arr = [1, 2, 3];
for (let i in arr) console.log(i); // 0, 1, 2 (indices)
for (let v of arr) console.log(v); // 1, 2, 3 (values)

JavaScriptObject CloningCopying
Clone an object using Object.assign(), spread operator (...), or structuredClone() for deep cloning. Shallow cloning only copies top-level properties.
Example:
const obj = { a: 1, b: { c: 2 } };
const shallowClone = { ...obj };
const deepClone = structuredClone(obj);
obj.b.c = 3;
console.log(shallowClone.b.c); // 3 (shallow)
console.log(deepClone.b.c); // 2 (deep)

JavaScriptHigher-Order FunctionsFunctional Programming
A higher-order function takes a function as an argument or returns a function. It’s used for abstraction and functional programming, like map or filter.
Example:
function higherOrder(fn) {
    return function(...args) {
        console.log('Before');
        fn(...args);
    };
}
const log = higherOrder(console.log);
log('Test'); // Before, Test

JavaScriptSpread OperatorES6
The spread operator (...) expands elements of an iterable (e.g., array) or object properties. It’s used for copying, merging, or passing arguments.
Example:
const arr = [1, 2];
const newArr = [...arr, 3]; // [1, 2, 3]
const obj = { a: 1 };
const newObj = { ...obj, b: 2 }; // { a: 1, b: 2 }
console.log(newArr, newObj);

JavaScriptmapfilterforEachArray Methods
map() transforms each element and returns a new array. filter() returns a new array with elements that pass a test. forEach() executes a function for each element without returning anything.
Example:
const arr = [1, 2, 3];
const mapped = arr.map(x => x * 2); // [2, 4, 6]
const filtered = arr.filter(x => x > 1); // [2, 3]
arr.forEach(x => console.log(x)); // 1, 2, 3

JavaScriptTruthyFalsyType Coercion
Falsy values evaluate to false in a boolean context: false, 0, -0, '', null, undefined, NaN. Truthy values evaluate to true: all others, like non-empty strings, objects, or non-zero numbers.
Example:
console.log(!!0); // false (falsy)
console.log(!!'hello'); // true (truthy)
if ({}) console.log('Object is truthy'); // Object is truthy

JavaScriptBreak StatementContinue StatementControl Flow
break exits a loop or switch statement entirely. continue skips the current iteration and proceeds to the next one in a loop.
Example:
for (let i = 0; i < 5; i++) {
    if (i === 2) continue;
    if (i === 4) break;
    console.log(i); // 0, 1, 3
}

JavaScriptObjectsObject Creation
JavaScript objects are key-value pairs storing data and functions. Create them using object literals, Object.create(), or constructors/classes.
Example:
const obj = { name: 'Test', getName: function() { return this.name; } };
const obj2 = Object.create({}); obj2.key = 'value';
class MyClass { constructor() { this.prop = 1; } }
const obj3 = new MyClass();

JavaScriptDestructuring AssignmentES6
Destructuring assignment unpacks values from arrays or objects into variables, simplifying code for accessing properties or elements.
Example:
const obj = { a: 1, b: 2 };
const { a, b } = obj;
console.log(a, b); // 1, 2
const arr = [1, 2];
const [x, y] = arr;
console.log(x, y); // 1, 2