JavaScript Fundamentals
Answer: JavaScript is a high-level programming language mainly used to make web pages interactive and dynamic. It can run in browsers and also on servers using environments such as Node.js.
console.log("Hello, World!");
Answer: var is function-scoped and can be redeclared. let is block-scoped and can be reassigned. const is block-scoped and cannot be reassigned after initialization.[cite: 1]
let age = 20;
age = 21;
const name = 'Ali';
// name = 'Sufiyan'; // Error: Assignment to constant variable.
Answer: Primitive types include string, number, bigint, boolean, undefined, null, and symbol. Objects, arrays, and functions are non-primitive/reference values.[cite: 1]
const str = "Text"; // String (Primitive)
const num = 100; // Number (Primitive)
const obj = { id: 1 }; // Object (Reference)
Answer: == performs type coercion before comparison, while === compares both value and type without coercion. In interviews and production code, === is generally preferred.[cite: 1]
console.log(5 == '5'); // true (Type Coercion)
console.log(5 === '5'); // false (Strict Type Check)
Answer: undefined usually means a variable has been declared but has not been assigned a value, or a requested property does not exist.[cite: 1]
let x;
console.log(x); // undefined
Answer: null is an intentional absence of a value. It is commonly assigned when you deliberately want to represent 'no value'.[cite: 1]
let user = null; // Deliberately set to no value
Answer: NaN means Not-a-Number. It is a special numeric value produced by invalid numeric operations.[cite: 1]
console.log(Number('hello')); // NaN
Answer: Primitive values are simple immutable values. Objects and arrays are reference values, so variables can refer to the same underlying object.[cite: 1]
let p1 = 10;
let p2 = p1; // Value copied
let obj1 = { val: 10 };
let obj2 = obj1; // Reference shared
Functions, Scope & Closures
Answer: A function is a reusable block of code designed to perform a specific task. It can receive parameters and return a value.[cite: 1]
function greet(name) {
return `Hello, ${name}`;
}
Answer: An arrow function is a shorter function syntax. It also handles this differently because it does not create its own this.[cite: 1]
const add = (a, b) => a + b;
Answer: Scope determines where a variable can be accessed. Common JavaScript scopes are global, function, and block scope.[cite: 1]
if (true) {
let blockScoped = "Inside Block";
}
// console.log(blockScoped); // ReferenceError
Answer: Lexical scope means a function can access variables based on where the function was written in the source code.[cite: 1]
const outerVar = "I am outside";
function inner() {
console.log(outerVar); // Accesses outer scope
}
Answer: Hoisting is JavaScript's behavior of processing declarations before code execution. var declarations are initialized as undefined, while let and const remain in the temporal dead zone until initialized.[cite: 1]
console.log(a); // undefined
var a = 5;
Answer: A closure occurs when a function remembers and can access variables from its outer lexical scope even after the outer function has finished executing.[cite: 1]
function counter() {
let count = 0;
return () => ++count;
}
const increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2
Answer: A callback is a function passed to another function so it can be executed later or when an operation completes.[cite: 1]
function processUser(name, callback) {
callback(`User: ${name}`);
}
processUser("Ali", console.log);
Answer: A higher-order function accepts another function as an argument, returns a function, or both.[cite: 1]
const multiplyBy = (factor) => (number) => number * factor;
const double = multiplyBy(2);
console.log(double(5)); // 10
Arrays & Objects
Answer: map() creates a new array by transforming every element of the original array.[cite: 1]
const doubled = [1, 2, 3].map(n => n * 2);
console.log(doubled); // [2, 4, 6]
Answer: filter() creates a new array containing only elements that satisfy a condition.[cite: 1]
const evens = [1, 2, 3, 4].filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
Answer: reduce() processes an array and combines its elements into a single accumulated result, such as a sum or object.[cite: 1]
const sum = [1, 2, 3].reduce((acc, n) => acc + n, 0);
console.log(sum); // 6
Answer: map() returns a new array and is used for transformation. forEach() does not return a transformed array and is commonly used for side effects.[cite: 1]
const a = [1, 2].map(x => x * 2); // [2, 4]
const b = [1, 2].forEach(x => console.log(x)); // undefined
Answer: Destructuring extracts values from arrays or properties from objects into variables.[cite: 1]
const user = { name: 'Ali', age: 20 };
const { name, age } = user;
console.log(name, age); // 'Ali', 20
Answer: The spread operator (...) expands iterable values or object properties, commonly used to copy or combine arrays and objects.[cite: 1]
const a = [1, 2];
const b = [...a, 3]; // [1, 2, 3]
Answer: The rest parameter collects multiple arguments into an array.[cite: 1]
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
Asynchronous JavaScript
Answer: A Promise represents the eventual result of an asynchronous operation. It can be pending, fulfilled, or rejected.[cite: 1]
const myPromise = new Promise((resolve, reject) => {
resolve("Success!");
});
Answer: async/await is syntax built on Promises that makes asynchronous code easier to read and write. An async function returns a Promise.[cite: 1]
async function getData() {
const res = await fetch('/api/users');
return res.json();
}
Answer: The event loop coordinates synchronous code, the call stack, and queued asynchronous callbacks so JavaScript can handle non-blocking operations.[cite: 1]
console.log("Start");
setTimeout(() => console.log("Async Task"), 0);
console.log("End");
Answer: The call stack is the structure JavaScript uses to keep track of currently executing function calls.[cite: 1]
function first() { second(); }
function second() { console.log("Stack execution"); }
first();
Answer: In browsers, Web APIs such as fetch, timers, and DOM APIs are provided by the browser environment rather than by the JavaScript language itself.[cite: 1]
setTimeout(() => {}, 1000); // Web API Timer
Answer: Promise callbacks are microtasks and are generally processed before timer callbacks such as setTimeout callbacks after the current stack is empty.[cite: 1]
Promise.resolve().then(() => console.log("Microtask"));
setTimeout(() => console.log("Macrotask"), 0);
Answer: Use try/catch around awaited operations and handle expected failures appropriately.[cite: 1]
try {
const data = await getData();
} catch (error) {
console.error(error);
}
DOM, Events & Storage
Answer: The Document Object Model is a tree-like representation of an HTML document that JavaScript can read and modify.[cite: 1]
document.getElementById('title').innerText = "Hello";
Answer: Event bubbling means an event starts at the target element and then propagates upward through its ancestors.[cite: 1]
elem.addEventListener('click', handler); // Bubbles up
Answer: Event delegation attaches one handler to a parent and uses event propagation to handle events from its children, reducing the number of handlers.[cite: 1]
parent.addEventListener('click', (e) => {
if (e.target.matches('button')) { /* handle */ }
});
Answer: localStorage persists data until it is removed, while sessionStorage normally lasts for the current browser tab/session.[cite: 1]
localStorage.setItem('key', 'value');
sessionStorage.setItem('tempKey', 'value');
Answer: JSON is a text format commonly used to exchange structured data. JSON.stringify converts a JavaScript value to JSON text, and JSON.parse converts JSON text back to a JavaScript value.[cite: 1]
const str = JSON.stringify({ a: 1 });
const obj = JSON.parse(str);
Interview-Level Concepts
Answer: this refers to a value determined by how a function is called. Arrow functions do not create their own this and instead use the surrounding lexical this.[cite: 1]
const obj = {
name: "Sufiyan",
show() { console.log(this.name); }
};
Answer: A shallow copy duplicates only the top-level structure, while nested objects may still be shared. A deep copy duplicates nested structures as well.[cite: 1]
const shallow = { ...original };
const deep = structuredClone(original);
Answer: Debouncing delays execution until a specified period has passed without another triggering event, useful for search inputs and resize events.[cite: 1]
// Delays function call until user stops typing
Answer: Throttling limits how often a function can execute during a period, useful for scroll or mousemove events.[cite: 1]
// Executes function at most once every N milliseconds
Answer: ES6 introduced important features such as let/const, arrow functions, classes, template literals, destructuring, modules, default parameters, spread/rest, and Promises.[cite: 1]
const template = `Hello ${user}`;
Answer: A module is a JavaScript file whose values can be explicitly exported and imported, helping organize code and manage dependencies.[cite: 1]
export const add = (a, b) => a + b;
import { add } from './math.js';