JavaScript Interview Questions - Complete Solutions
Easy & Medium Level Based on 2-Week Fundamentals
EASY LEVEL QUESTIONS
JavaScript Basics
1. What is JavaScript and where is it used? JavaScript is a high-level, interpreted programming
language primarily used for:
Client-side web development (making web pages interactive)
Server-side development (Node.js)
Mobile app development
Desktop applications
Game development
2. How do you include JavaScript in an HTML page?
html
<!-- Inline JavaScript -->
<script>
console.log("Hello World");
</script>
<!-- External JavaScript file -->
<script src="script.js"></script>
<!-- Inline event handlers -->
<button onclick="alert('Clicked!')">Click me</button>
3. What does console.log() do? console.log() prints output to the browser's developer console,
primarily used for debugging and testing code without showing alerts to users.
4. What's the difference between alert() and console.log()?
alert() : Shows a popup dialog box to the user that must be dismissed
console.log() : Prints to the browser console (only visible in developer tools)
Variables and Data Types
5. What are the different ways to declare variables in JavaScript?
javascript
var name = "John"; // Function-scoped, can be redeclared
let age = 25; // Block-scoped, can be reassigned
const city = "NYC"; // Block-scoped, cannot be reassigned
6. Name the primitive data types in JavaScript.
string - Text data
number - Integers and floating-point numbers
boolean - true/false values
null - Intentional absence of value
undefined - Variable declared but not assigned
symbol - Unique identifier (ES6+)
bigint - Large integers (ES2020+)
7. What is the difference between null and undefined?
null : Intentionally assigned to represent "no value"
undefined : Variable exists but hasn't been assigned a value
8. How do you check the type of a variable?
javascript
typeof variable;
// Examples:
typeof "hello"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
Operators
9. What are the different types of operators in JavaScript?
Arithmetic: + , - , * , / , % , **
Assignment: = , += , -= , *= , /=
Comparison: == , === , != , !== , < , > , <= , >=
Logical: && , || , !
10. What is the difference between == and ===?
== (loose equality): Compares values with type coercion
=== (strict equality): Compares values and types without coercion
javascript
5 == "5"; // true (type coercion)
5 === "5"; // false (different types)
11. What will be the output of 5 + "3"? Output: "53" (string concatenation occurs because one
operand is a string)
Control Flow
12. Explain the if-else statement with an example.
javascript
let age = 18;
if (age >= 18) {
console.log("You can vote!");
} else {
console.log("You cannot vote yet.");
}
13. When would you use a switch statement instead of if-else? Use switch when:
Testing the same variable against multiple values
You have many conditions to check
Code readability is improved
javascript
switch (day) {
case "Monday":
console.log("Start of work week");
break;
case "Friday":
console.log("TGIF!");
break;
default:
console.log("Regular day");
}
14. What is the ternary operator? Give an example.
javascript
// Syntax: condition ? valueIfTrue : valueIfFalse
let age = 20;
let status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"
Loops
15. What are the different types of loops in JavaScript?
for - Traditional counter loop
while - Loop while condition is true
do-while - Execute at least once, then check condition
for...in - Iterate over object properties
for...of - Iterate over iterable values
16. What's the difference between break and continue?
break : Exits the entire loop
continue : Skips current iteration and moves to next
17. Write a simple for loop to print numbers 1 to 5.
javascript
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Functions
18. What is a function? Why do we use functions? A function is a reusable block of code that performs
a specific task. Benefits:
Code reusability
Better organization
Easier debugging and maintenance
Modularity
19. What's the difference between function declaration and function expression?
javascript
// Function Declaration (hoisted)
function greet() {
return "Hello!";
}
// Function Expression (not hoisted)
const greet = function() {
return "Hello!";
};
20. What are arrow functions? Give an example.
javascript
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
// With single parameter
const square = x => x * x;
MEDIUM LEVEL QUESTIONS
Advanced Variables and Scope
21. Explain hoisting in JavaScript with examples. Hoisting moves variable and function declarations to
the top of their scope.
javascript
console.log(x); // undefined (not error)
var x = 5;
// Equivalent to:
var x;
console.log(x); // undefined
x = 5;
// let and const are hoisted but not initialized
console.log(y); // ReferenceError
let y = 10;
22. What is the difference between var, let, and const?
Feature var let const
Scope Function Block Block
Hoisting Yes (initialized with undefined) Yes (not initialized) Yes (not initialized)
Reassignment Yes Yes No
Redeclaration Yes No No
23. What is block scope? Give an example.
javascript
{
let blockScoped = "I'm in a block";
var functionScoped = "I'm function scoped";
}
console.log(blockScoped); // ReferenceError
console.log(functionScoped); // "I'm function scoped"
24. What is a closure? Provide a simple example. A closure is when an inner function has access to
outer function's variables.
javascript
function outerFunction(x) {
return function innerFunction(y) {
return x + y; // Inner function accesses outer's variable
};
}
const addFive = outerFunction(5);
console.log(addFive(3)); // 8
Arrays - Advanced
25. What is the difference between push() and concat() methods?
javascript
let arr1 = [1, 2, 3];
let arr2 = [4, 5];
// push() modifies original array
arr1.push(4, 5);
console.log(arr1); // [1, 2, 3, 4, 5]
// concat() returns new array
let arr3 = [1, 2, 3];
let newArr = arr3.concat([4, 5]);
console.log(arr3); // [1, 2, 3] (unchanged)
console.log(newArr); // [1, 2, 3, 4, 5]
26. Explain the map() method with an example. map() creates a new array by transforming each
element using a callback function.
javascript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
27. What's the difference between map() and forEach()?
map() : Returns a new array with transformed elements
forEach() : Executes function for each element, returns undefined
javascript
const nums = [1, 2, 3];
// map returns new array
const doubled = nums.map(x => x * 2); // [2, 4, 6]
// forEach returns undefined
const result = nums.forEach(x => x * 2); // undefined
28. How does the filter() method work? filter() creates a new array with elements that pass a test
function.
javascript
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
29. Explain the reduce() method with a simple example. reduce() reduces an array to a single value
using an accumulator.
javascript
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // 10
Objects - Advanced
30. What is the this keyword in JavaScript? this refers to the object in the current execution context.
Its value depends on how a function is called.
javascript
const person = {
name: "John",
greet: function() {
return `Hello, ${this.name}!`; // this refers to person object
}
};
31. How do you iterate over object properties?
javascript
const person = { name: "John", age: 30, city: "NYC" };
// for...in loop
for (let key in person) {
console.log(key, person[key]);
}
// Object.keys()
Object.keys(person).forEach(key => console.log(key, person[key]));
// Object.entries()
Object.entries(person).forEach(([key, value]) => console.log(key, value));
32. What is destructuring? Give examples for arrays and objects.
javascript
// Object destructuring
const person = { name: "John", age: 30 };
const { name, age } = person;
// Array destructuring
const colors = ["red", "green", "blue"];
const [first, second] = colors;
// With default values
const { name: personName = "Unknown" } = person;
Modern JavaScript Features
33. What are template literals? How are they different from regular strings?
javascript
// Template literals use backticks
const name = "John";
const age = 30;
// Variable interpolation
const message = `Hello, ${name}! You are ${age} years old.`;
// Multiline strings
const multiline = `This is
a multiline
string`;
// Regular strings
const regular = "Hello, " + name + "! You are " + age + " years old.";
34. Explain the spread operator with examples.
javascript
// Array spreading
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// Object spreading
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
// Function arguments
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
35. What is the rest parameter?
javascript
// Collects remaining arguments into an array
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// With other parameters
function greet(greeting, ...names) {
return `${greeting} ${names.join(", ")}!`;
}
console.log(greet("Hello", "John", "Jane", "Bob")); // "Hello John, Jane, Bob!"
36. What is optional chaining and when would you use it?
javascript
const user = {
profile: {
social: {
twitter: "@johndoe"
}
}
};
// Without optional chaining (risky)
// console.log(user.profile.social.twitter); // Could throw error if any property is undefined
// With optional chaining (safe)
console.log(user.profile?.social?.twitter); // "@johndoe"
console.log(user.profile?.social?.facebook); // undefined (no error)
37. Explain the nullish coalescing operator (??).
javascript
// Returns right side only if left side is null or undefined
const name = null ?? "Default Name"; // "Default Name"
const age = 0 ?? 25; // 0 (because 0 is not null/undefined)
const score = undefined ?? 100; // 100
// Compare with || operator
const value1 = 0 || "default"; // "default" (0 is falsy)
const value2 = 0 ?? "default"; // 0 (0 is not null/undefined)
Advanced Functions
38. What are higher-order functions? Functions that either take other functions as arguments or return
functions.
javascript
// Function that takes another function as argument
function processArray(arr, callback) {
return arr.map(callback);
}
const doubled = processArray([1, 2, 3], x => x * 2); // [2, 4, 6]
// Function that returns another function
function createMultiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = createMultiplier(2);
console.log(double(5)); // 10
39. What are default parameters in functions?
javascript
function greet(name = "Guest", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet()); // "Hello, Guest!"
console.log(greet("John")); // "Hello, John!"
console.log(greet("John", "Hi")); // "Hi, John!"
40. How do you handle variable number of arguments in a function?
javascript
// Using rest parameters (modern approach)
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Using arguments object (older approach)
function sumOld() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3, 4, 5)); // 15
Error Handling
41. How do you handle errors in JavaScript?
javascript
try {
// Code that might throw an error
let result = riskyOperation();
console.log(result);
} catch (error) {
// Handle the error
console.error("An error occurred:", error.message);
} finally {
// This always runs
console.log("Cleanup code here");
}
42. What is the difference between throw and return?
throw : Raises an exception and stops normal execution
return : Returns a value and exits the function normally
javascript
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero"); // Throws exception
}
return a / b; // Returns result normally
}
43. When would you use finally block? Use finally for cleanup code that must run regardless of
success or failure.
javascript
function processFile(filename) {
let file;
try {
file = openFile(filename);
processData(file);
} catch (error) {
console.error("Error processing file:", error);
} finally {
// This always runs - cleanup
if (file) {
closeFile(file);
}
}
}
CODING CHALLENGES
Easy Coding Questions
44. Write a function to check if a number is even or odd.
javascript
function isEven(number) {
return number % 2 === 0;
}
// Usage
console.log(isEven(4)); // true
console.log(isEven(5)); // false
45. Create a function that returns the larger of two numbers.
javascript
function findLarger(a, b) {
return a > b ? a : b;
}
// Alternative using Math.max
const findLarger2 = (a, b) => Math.max(a, b);
console.log(findLarger(10, 5)); // 10
46. Write a function to reverse a string.
javascript
function reverseString(str) {
return str.split('').reverse().join('');
}
// Alternative using loop
function reverseStringLoop(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
console.log(reverseString("hello")); // "olleh"
47. Create a function that counts vowels in a string.
javascript
function countVowels(str) {
const vowels = 'aeiouAEIOU';
return str.split('').filter(char => vowels.includes(char)).length;
}
// Alternative with regex
function countVowelsRegex(str) {
const matches = str.match(/[aeiouAEIOU]/g);
return matches ? matches.length : 0;
}
console.log(countVowels("hello world")); // 3
48. Write a function to find the sum of all numbers in an array.
javascript
function sumArray(numbers) {
return numbers.reduce((sum, num) => sum + num, 0);
}
// Alternative with loop
function sumArrayLoop(numbers) {
let sum = 0;
for (let num of numbers) {
sum += num;
}
return sum;
}
console.log(sumArray([1, 2, 3, 4, 5])); // 15
Medium Coding Questions
49. Write a function that removes duplicates from an array.
javascript
function removeDuplicates(arr) {
return [...new Set(arr)];
}
// Alternative with filter
function removeDuplicatesFilter(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]
50. Create a function that finds the second largest number in an array.
javascript
function findSecondLargest(numbers) {
const uniqueNumbers = [...new Set(numbers)].sort((a, b) => b - a);
return uniqueNumbers.length >= 2 ? uniqueNumbers[1] : undefined;
}
// Alternative without sorting
function findSecondLargestEfficient(numbers) {
let largest = -Infinity;
let secondLargest = -Infinity;
for (let num of numbers) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num < largest) {
secondLargest = num;
}
}
return secondLargest === -Infinity ? undefined : secondLargest;
}
console.log(findSecondLargest([1, 5, 3, 9, 2])); // 5
51. Write a function that checks if a string is a palindrome.
javascript
function isPalindrome(str) {
const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleaned === cleaned.split('').reverse().join('');
}
// Alternative with two pointers
function isPalindromePointers(str) {
const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
let left = 0;
let right = cleaned.length - 1;
while (left < right) {
if (cleaned[left] !== cleaned[right]) {
return false;
}
left++;
right--;
}
return true;
}
console.log(isPalindrome("A man, a plan, a canal: Panama")); // true
52. Create a function that flattens a nested array one level deep.
javascript
function flattenOneLevel(arr) {
return arr.flat(1);
}
// Manual implementation
function flattenOneLevelManual(arr) {
const result = [];
for (let item of arr) {
if (Array.isArray(item)) {
result.push(...item);
} else {
result.push(item);
}
}
return result;
}
console.log(flattenOneLevel([1, [2, 3], [4, [5, 6]]])); // [1, 2, 3, 4, [5, 6]]
53. Write a function that groups an array of objects by a property.
javascript
function groupBy(array, property) {
return array.reduce((groups, item) => {
const key = item[property];
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(item);
return groups;
}, {});
}
const people = [
{ name: "John", age: 25 },
{ name: "Jane", age: 30 },
{ name: "Bob", age: 25 }
];
console.log(groupBy(people, 'age'));
// { 25: [{name: "John", age: 25}, {name: "Bob", age: 25}], 30: [{name: "Jane", age: 30}] }
54. Create a function that implements a simple calculator.
javascript
function calculator(operation, a, b) {
switch (operation) {
case 'add':
case '+':
return a + b;
case 'subtract':
case '-':
return a - b;
case 'multiply':
case '*':
return a * b;
case 'divide':
case '/':
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
default:
throw new Error("Invalid operation");
}
}
console.log(calculator('add', 5, 3)); // 8
console.log(calculator('*', 4, 2)); // 8
console.log(calculator('divide', 10, 2)); // 5
55. Write a function that converts the first letter of each word to uppercase.
javascript
function capitalizeWords(str) {
return str.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}
// Alternative with regex
function capitalizeWordsRegex(str) {
return str.replace(/\b\w/g, char => char.toUpperCase());
}
console.log(capitalizeWords("hello world javascript")); // "Hello World Javascript"
SCENARIO-BASED QUESTIONS
56. How would you debug JavaScript code that's not working?
Use console.log() to track variable values
Use browser developer tools and debugger
Set breakpoints to pause execution
Check console for error messages
Use console.error() and console.warn() for different log levels
Validate assumptions about data types and values
57. What would you do if you get "undefined" when accessing an object property?
Check if the object exists: if (object && object.property)
Use optional chaining: object?.property
Provide default values: object.property || defaultValue
Validate object structure before accessing nested properties
Use hasOwnProperty() to check if property exists
58. How would you optimize a loop that's running slowly?
Cache array length: for (let i = 0, len = arr.length; i < len; i++)
Use appropriate array methods ( map , filter , find ) instead of manual loops
Break early when possible using break or return
Avoid nested loops when possible
Use for...of for simple iterations over values
59. What's your approach to organizing JavaScript code?
Separate concerns into different functions
Use modules to group related functionality
Follow consistent naming conventions
Keep functions small and focused on single tasks
Use comments for complex logic
Group related variables and functions together
60. How do you ensure your JavaScript code is readable and maintainable?
Use descriptive variable and function names
Write comments for complex logic
Follow consistent coding style
Keep functions small (single responsibility)
Use proper indentation and formatting
Avoid deeply nested code
Use modern JavaScript features appropriately
QUICK FIRE ROUNDS
Easy:
What does NaN stand for? "Not a Number"
Is JavaScript case-sensitive? Yes
What symbol is used for single-line comments? //
Which method converts string to number? Number() , parseInt() , or parseFloat()
What does Array.length return? The number of elements in the array
Medium:
What happens when you access an array index that doesn't exist? Returns undefined
Can you change a const array's contents? Yes, you can modify contents but not reassign the array
What's the output of "5" - 3? 2 (string "5" is converted to number)
Name three ways to create an empty array: [] , new Array() , Array()
What does !! operator do? Converts any value to boolean (double negation)
BEST PRACTICES QUESTIONS
61. When should you use const vs let?
Use const for values that won't be reassigned (objects, arrays, functions)
Use let for variables that will be reassigned
Prefer const by default for better code clarity
62. Why is it better to use === instead of ==?
Avoids unexpected type coercion
More predictable behavior
Prevents bugs from implicit type conversion
Makes code intentions clearer
63. How do you make your code more readable?
Use meaningful variable and function names
Write comments for complex logic
Use consistent formatting and indentation
Break complex operations into smaller functions
Use white space appropriately
64. What are some common JavaScript mistakes beginners make?
Not understanding scope (var vs let/const)
Unexpected type coercion with == operator
Not handling asynchronous operations properly
Forgetting to declare variables (creating globals)
Not understanding this context
65. How do you test your JavaScript functions?
Manual testing with console.log()
Writing simple test cases with expected vs actual output
Using browser developer tools
Testing edge cases (empty inputs, null values)
Using testing frameworks like Jest for automated testing