Hi folks! 👋 Welcome to yet another session of free ka gyan 💡 (because who doesn’t love free wisdom?). You might be thinking, “Why another session?” Well, because I’ve got another article where I covered React interview questions 💻, and if you’re a React developer, you absolutely should check it out. You’re welcome. 🙌
Now, let’s switch gears to something equally exciting: JavaScript interview questions! 🎉 Yes, the magical land of curly braces {}, tricky syntax, and the occasional “Why is this undefined?” moment.
If you’re prepping for a frontend role, JavaScript will become your new best frenemy. 🥲 Interviewers love JavaScript—probably because it’s vast, unpredictable, and perfect for creating questions that make you doubt your career choices. 😅
To make things easier (and less intimidating), I’ve divided JavaScript questions into 2 juicy categories 🍹:
Theory: 🧠
Ah, the part where they test your inner philosopher. Be prepared for questions about the event loop, inheritance, and everything from “What’s a prototype?” to “Why does this hate me?” 🤔
Feature Coding: 🎨
The showstopper. 🌟 Here, they’ll ask you to build something cool using JavaScript. Maybe it’s a feature, maybe it’s some weird coding problem involving setImmediate or setInterval. ⏳ Don’t panic—I’ve even included an example that was thrown at me in an interview. It’s a fantastic way to dive into promises and async/await while lowkey questioning your life choices. 🌀
So, buckle up! This is going to be one heck of a JavaScript ride. 🚀
Note: I have only mentioned questions that are must-to-know
Theory Javascript Questions:
1. What are the different data types present in javascript?
2. Explain Hoisting in JavaScript?
Hoisting works differently for arrow functions and normal functions. Normal functions are fully hoisted, meaning both their name and definition are moved to the top of the scope. In contrast, arrow functions are not fully hoisted because they are assigned to variables. Only the variable is hoisted, not the arrow function itself.
3. Difference between var
, let
, and const
keyword in javascript?
4. What is pass-by-value and pass-by-reference?
All primitive data types are passed by values(A copy of the value is used) and all non-primitive data types are passed by referenced (The reference to the object is passed by value).
5. What is the difference between a deep copy and a shallow copy?
6. What are Self-Invoking Functions, or Immediately Invoked Function Expressions (IIFE), also known as Anonymous Functions?
(function () {
console.log("I am a self-invoking function!");
})();
7. What do you mean by "strict mode" in JavaScript?
8. Explain Higher-Order Functions in JavaScript.
9. Explain the this
keyword in JavaScript.
10. Explain the call()
, apply()
, and bind()
methods in JavaScript.
11. What is currying in JavaScript?
12. What is lexical scoping in JavaScript?
13. Explain Closures in JavaScript.
14. What are object prototypes?
15. What is prototypal inheritance?
16. What are callbacks in JavaScript?
17. Explain callback hell.
18. What is the rest parameter, and how does it differ from the spread operator?
19. What is the use of Promises in JavaScript?
20. What are generator functions?
21. What is a Temporal Dead Zone in JavaScript?
22. What are async
and await
in JavaScript?
23. Explain the reduce()
function in JavaScript
24. What is implicit coercion in JavaScript?
25. What does it mean for functions to be "first-class citizens" in JavaScript?
26. Explain the scope of this
inside an object.
If a function is inside an object, this
refers to the object and can access its properties.
If this
is used inside a nested function or object, it will refer to the outermost object, which is usually the global window object.
27. What is the significance of the new
keyword in JavaScript?
28. What is memoization in JavaScript?
29. What are Map
, WeakMap
, and WeakSet
in JavaScript?
30. What is event propagation in JavaScript?
31. What is event delegation in JavaScript?
32. What is the event loop in JavaScript?
33. What is control flow in JavaScript?
Control flow in JavaScript determines the order in which statements are executed in your code. Here's a breakdown of the main control flow structures: If Statement, Using If-Else Statement, Using Switch Statement, Using the Ternary Operator, Using For loop.
34. What is the difference between Server-Side Rendering (SSR) and Client-Side Rendering (CSR)?
35. What is the difference between declarative and imperative programming?
Declarative Programming: Describes what to do, focusing on the desired outcome rather than the steps to achieve it.
Imperative Programming: Describes how to do it, specifying the exact steps to achieve the desired result.
36. What is debouncing and throttling?
Feature Based Questions:
1. Reverse a string in javascript?
const reversestring = str => str.split("").reverse().join("");
const res = reversestring("tpircsavaJ iH")
console.log(res) // Hi Javascript
2. Write code for debouncing.
<input placeholder="Enter test" id="userInput"/>
const inputBox = document.getElementById('userInput');
inputBox.addEventListener('input', (event) => {
Debouncing(event);
});
let interval;
function Debouncing (event) {
clearTimeout(interval)
interval = setTimeout(() => {
console.log(event.target.value);
}, 2000)
}
3. Write code for throttling.
<input placeholder="Enter test" id="userInput"/>
const inputBox = document.getElementById('userInput');
inputBox.addEventListener('input', (event) => {
Throttling(event);
});
let value = true;
function Throttling (event) {
if (value === true) {
console.log(event.target.value);
value = false;
setTimeout(() => {
value = true;
}, 2000)
}
}
4. How to sort the array of objects based on a key?
const array = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
];
// Sort by age (ascending)
array.sort((a, b) => a.age - b.age);
console.log(array);
// Output:
// [
// { name: 'Charlie', age: 20 },
// { name: 'Alice', age: 25 },
// { name: 'Bob', age: 30 }
// ]
5. write a constructor function.
function Person(name, age, city) {
// Properties
this.name = name;
this.age = age;
this.city = city;
// Method
this.greet = function () {
console.log(`Hi, I'm ${this.name}, and I live in ${this.city}.`);
};
}
// Creating an instance
const person1 = new Person("Prajesh", 25, "Pune");
const person2 = new Person("Anjali", 28, "Mumbai");
// Using the method
person1.greet(); // Output: Hi, I'm Prajesh, and I live in Pune.
person2.greet(); // Output: Hi, I'm Anjali, and I live in Mumbai.
6. Write the polyfill of a map, reduce, and filter.
Here A polyfill is a piece of code that mimics the functionality or feature of a newer API or method, enabling it to work in environments where it is not natively supported.
- Map
Array.prototype.myMap = function(callback, thisArg) {
if (!this || !Array.isArray(this)) {
throw new TypeError('myMap can only be called on arrays.');
}
const result = [];
for (let i = 0; i < this.length; i++) {
if (this.hasOwnProperty(i)) {
result.push(callback.call(thisArg, this[i], i, this)); // Use callback.call to apply thisArg
}
}
return result;
};
// Example usage
const obj = { multiplier: 2 };
const numbers = [1, 2, 3];
const doubled = numbers.myMap(function (num) {
return num * this.multiplier;
}, obj);
console.log(doubled); // Output: [2, 4, 6]
- Reduce
Array.prototype.myReduce = function(callback, initialValue) {
if (!this || !Array.isArray(this)) {
throw new TypeError('myReduce can only be called on arrays.');
}
if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function.');
}
let accumulator = initialValue;
let startIndex = 0;
if (accumulator === undefined) {
if (this.length === 0) {
throw new TypeError('Reduce of empty array with no initial value.');
}
accumulator = this[0];
startIndex = 1;
}
for (let i = startIndex; i < this.length; i++) {
if (this.hasOwnProperty(i)) {
accumulator = callback(accumulator, this[i], i, this);
}
}
return accumulator;
};
// Example usage
const sum = [1, 2, 3, 4].myReduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 10
- Filter
Array.prototype.myFilter = function(callback, thisArg) {
if (!this || !Array.isArray(this)) {
throw new TypeError('myFilter can only be called on arrays.');
}
if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function.');
}
const result = [];
for (let i = 0; i < this.length; i++) {
if (this.hasOwnProperty(i) && callback.call(thisArg, this[i], i, this)) {
// Use callback.call to apply thisArg
result.push(this[i]);
}
}
return result;
};
// Example usage
const numbers = [1, 2, 3, 4];
const obj = { divisor: 2 };
const evens = numbers.myFilter(function(num) {
return num % this.divisor === 0;
}, obj);
console.log(evens); // Output: [2, 4]
7. Write three functions, each using setTimeout to delay execution for 3 seconds, 2 seconds, and 1 second respectively. Then, write a function to execute these three functions in the same order (one, two, three) such that the output is:
one
two
three
const one = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("one")
resolve();
}, 3000)
})
}
const two = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("two")
resolve();
}, 2000)
})
}
const three = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("three")
resolve();
}, 1000)
})
}
const check = async () => {
await one();
await two();
await three();
}
check();
// output:
// one
// two
// three
8. Write a simple callback function?
// A function that takes a callback as an argument
function greetUser(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}
// A callback function
function displayMessage() {
console.log('Welcome to the platform!');
}
// Using the greetUser function with the callback
greetUser('Jhon', displayMessage);
9. Write a multiply function which will properly work when invoked below syntax.
console.log(multiply (2) (3) (4)) // output: 24
console.log(multiply (3) (4) (5)) // output: 60
function multiply (x) {
return function (y) {
return function (z) {
return x * y * z
}
}
}
10. Write code for memoization.
const memoizeAddition = () => {
let cache = {};
return (value) => {
if (value in cache) {
console.log("Fetching from cache");
return cache[value]; // Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript identifier. Hence, can only be accessed using the square bracket notation.
} else {
console.log("Calculating result");
let result = value + 20;
cache[value] = result;
return result;
}
};
};
// returned function from memoizeAddition
const addition = memoizeAddition();
console.log(addition(20)); //output: 40 calculated
console.log(addition(20)); //output: 40 cached
Congratulations on making it to the bottom of this post, and thank you so much for reading!
🎉 Your dedication to learning JavaScript is truly inspiring. Since you’re here, I’d love to share a fantastic GitHub repository I discovered during my JavaScript journey. It’s packed with valuable insights and resources to deepen your understanding of JavaScript. Trust me, you’re going to love it!
👉 Repo Link: https://github.com/sudheerj/javascript-interview-questions
Top comments (12)
Your string reversing code is using
split
. This will break with some unicode characters (try reversing a string containing emojis). Much better to spread the string to an array ([...str]
) - not perfect, but much better.Hi Jon,
Thank you for your input! You are absolutely correct that using
split
will not handle Unicode characters like emojis or certain symbols effectively. Instead,([...str])
is indeed a better option for such cases.To elaborate for the readers, when using
split
, the string is divided into individual characters based on UTF-16 code units. Emojis, however, are surrogate pairs consisting of two UTF-16 code units, which causessplit
to fail. On the other hand, the spread operator treats Unicode characters as single entities, regardless of how many UTF-16 code units they consist of.I appreciate you pointing this out, and I’ll also edit the code to ensure it handles Unicode characters properly.
Thank you again for sharing your thoughts!
IIFEs are not self invoking (that would make them recursive functions), and they don't have to be anonymous
Hi Jon,
You're almost right! Just a small clarification: IIFEs are "Immediately Invoked Function Expressions" because they execute immediately after being defined, but this doesn't make them recursive. Recursion occurs when a function calls itself from within its own body. Also, you're absolutely correct that IIFEs don't have to be anonymous—they can be named as well.
Small examples:
Anonymous IIFE:
Named IIFE:
Self invoking would mean they invoke themselves. They do not. They are invoked the same way as any other function - from outside (i.e. not by the function itself)
A "self invoking function" is - by definition - recursive.
Calling IIFEs self-invoking is entirely wrong.
You're correct in distinguishing between IIFEs (Immediately Invoked Function Expressions) and recursive functions, and the misuse of the term "self-invoking."
An IIFE is not "self-invoking" in the literal sense. It's explicitly invoked by the surrounding parentheses (()), which execute the function immediately upon definition. The function does not invoke itself; it is invoked by wrapping syntax.
On the other hand, recursive functions do indeed "self-invoke" because they call themselves within their own body, typically with modified arguments, until a base case is met to stop the recursion. I hope that clarifies the statement.
Just now learning Javascript hopefully I can learn most of these values soon to better understand these questions.
That's a wonderful approach! JavaScript can be a bit challenging initially, but with consistent practice, you'll master it in no time. One piece of advice: try to learn concepts through practical examples. Feel free to reach out if you have any questions or need help along the way. You've got this!
Be careful answering this one. JavaScript only has pass by value. Kind of a trick question
Hi Jon!
Thank you for sharing your thoughts! I just wanted to clarify a small point about JavaScript. While it's a common misconception, JavaScript technically doesn't use pass-by-reference. Instead, it uses pass-by-value for everything, but with objects (including arrays and functions), the "value" that's passed is actually a reference to the memory location. This is why it sometimes behaves like pass-by-reference.
To break it down:
Pass-by-Value (Primitives): A copy of the value is passed, so changes inside the function don’t affect the original variable (e.g., numbers, strings, booleans).
Objects (Reference-like behavior): A copy of the reference is passed, which allows changes to the object's properties to reflect outside the function. However, if you reassign the parameter inside the function, the original reference remains unchanged.
It’s a subtle distinction, but it’s a good one to keep in mind! Hope this helps! 😊
The polyfills for
map
andfilter
are both missing the optionalthisArg
. Without this, they're not viable polyfills for these functions.Thank you for pointing this out! You’re absolutely correct—the current polyfills for
map
andfilter
do not include support for the optionalthisArg
parameter, which is essential for fully replicating the behavior of these functions.The
thisArg
allows developers to provide a custom this context for the callback function, which can be crucial in scenarios where the callback depends on a specific execution context. Without it, the polyfills may fail to handle certain use cases properly, making them incomplete.I really appreciate you bringing this to my attention and highlighting its importance!