By Zain Ali
"Prepare the JavaScript interview questions."
October 7, 2024
JavaScript is a dynamic, lightweight, interpreted programming language used mainly to make web pages interactive. Java is a static, object-oriented programming language used to develop standalone applications.
Example:
// JavaScript code
console.log("Hello, JavaScript!");var, let, and const in JavaScript.var: Function-scoped, can be redeclared, and has hoisting behavior.let: Block-scoped, cannot be redeclared, but can be reassigned.const: Block-scoped, cannot be redeclared or reassigned.Example:
var x = 10;
let y = 20;
const z = 30;
x = 15; // Allowed
y = 25; // Allowed
// z = 35; // Error: Assignment to constant variableA closure is a function that retains access to its outer scope, even after the outer function has finished executing.
Example:
function outer() {
let counter = 0;
return function() {
counter++;
return counter;
};
}
const increment = outer();
console.log(increment()); // 1
console.log(increment()); // 2== vs. === in JavaScript.==: Checks for equality of value, with type coercion.===: Checks for equality of value and type.Example:
console.log(2 == "2"); // true (type coercion)
console.log(2 === "2"); // false (strict equality)setTimeout or fetch).Example:
// Synchronous
console.log("Start");
console.log("End");
// Asynchronous
console.log("Start");
setTimeout(() => console.log("Async Task"), 1000);
console.log("End");A promise is an object that represents the eventual completion (or failure) of an asynchronous operation.
Example:
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success"), 1000);
});
promise.then(result => console.log(result)); // Logs "Success" after 1 secondHoisting is JavaScript's default behavior of moving declarations to the top of the scope. Only variable and function declarations are hoisted, not initializations.
Example:
console.log(x); // undefined due to hoisting
var x = 5;.call(), .apply(), and .bind() methods in JavaScript..call(): Calls a function with a specified this context and individual arguments..apply(): Similar to .call(), but takes an array of arguments..bind(): Returns a new function, permanently binding this to the specified object.Example:
const person = {
name: "Alice",
greet(age) {
console.log(`Hello, I'm ${this.name} and I'm ${age} years old.`);
}
};
person.greet.call({ name: "Bob" }, 25); // Hello, I'm Bob and I'm 25 years old.
person.greet.apply({ name: "Charlie" }, [30]); // Hello, I'm Charlie and I'm 30 years old.
const boundGreet = person.greet.bind({ name: "Dave" });
boundGreet(35); // Hello, I'm Dave and I'm 35 years old.map(), filter(), and reduce() array methods.map(): Returns a new array with results of calling a function on every element.filter(): Returns a new array with elements that pass a condition.reduce(): Executes a reducer function on each element, resulting in a single value.Example:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]
const evens = numbers.filter(num => num % 2 === 0); // [2, 4]
const sum = numbers.reduce((total, num) => total + num, 0); // 15Destructuring allows extracting values from arrays or properties from objects into distinct variables.
Example:
const user = { name: "Alice", age: 25 };
const { name, age } = user;
console.log(name); // Alice
console.log(age); // 25Event delegation is a technique where a single event listener is added to a parent element to handle events for its child elements.
Example:
<div id="parent">
<button class="child">Click me!</button>
</div>
<script>
document.getElementById("parent").addEventListener("click", (event) => {
if (event.target.classList.contains("child")) {
console.log("Button clicked!");
}
});
</script>Currying transforms a function that takes multiple arguments into a sequence of functions, each taking a single argument.
Example:
function add(a) {
return function(b) {
return a + b;
};
}
const add5 = add(5);
console.log(add5(10)); // 15async/await is a syntactic sugar for handling asynchronous code more easily, making asynchronous code appear synchronous.
Example:
async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
}
fetchData();Arrow functions provide a shorter syntax and do not have their own this context, making them ideal for callbacks and array methods.
Example:
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5Example (Debouncing):
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}Example:
const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original };
const deepCopy = JSON.parse(JSON.stringify(original));Mastering these concepts with practical examples will prepare you for many JavaScript interview questions at all levels!