JavaScript Interview Mastery: Essential Questions and Answers

JavaScript Interview Mastery: Essential Questions and Answers

JavaScript is a versatile and widely used programming language that plays a crucial role in web development.

If you’re preparing for a JavaScript interview, it’s essential to be well-versed in the language’s core concepts, syntax, and best practices.

Beginner-Level JavaScript Interview Questions and Answers

1. What is JavaScript, and what are its key features?

JavaScript is a high-level, dynamic, and interpreted programming language primarily used for creating interactive elements on websites.

It is an essential part of web development, alongside HTML and CSS, and runs on the client side (in the browser) to improve user interfaces and web page behavior. JavaScript can also be executed on the server side using environments like Node.js.

download

Key Features of JavaScript:

  1. Lightweight and interpreted: JavaScript is executed directly within the browser environment without the need for pre-compilation, making it faster and more efficient for web development.

    It reduces the overhead of setup and allows changes to be seen almost immediately during development.
    .
  2. Dynamic typing: JavaScript determines variable types during runtime, allowing a high level of flexibility in how variables are used and reassigned. This feature enables programmers to write versatile and adaptable code without being constrained by strict type definitions.
    .
  3. Prototype-based object orientation: Instead of using classical inheritance, JavaScript employs prototype-based inheritance, where objects can inherit directly from other objects. This approach provides a more flexible and simpler model for object-oriented programming.
    .
  4. First-class functions: In JavaScript, functions are treated as first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and even returned as values from functions.

    This makes functions highly versatile and essential to many JavaScript paradigms.
    .
  5. Event-driven: JavaScript is designed to handle events such as clicks, key presses, mouse movements, and more. This capability enables interactive web applications where user inputs trigger specific actions, enhancing the user experience.
    .
  6. Asynchronous programming: JavaScript handles asynchronous operations efficiently with features like Promises, async/await, and callback functions.

    This allows the language to manage long-running tasks, such as fetching data from a server, without blocking the main thread of execution.
    .

2. What is the difference between “let” and “const”?

Both let and const are used to declare variables in JavaScript, but they have different behavior:

let:

Used to declare block-scoped variables, which means the variable is only accessible within the block (enclosed in {}) where it’s defined.

The value of a let variable can be reassigned after declaration.

Example:

let x = 5;
x = 10; // Reassignment is allowed

const:

Also block-scoped but used for declaring variables whose value cannot be reassigned.

However, for objects and arrays, while the reference cannot be changed, the properties or elements can still be modified.

Example:

const y = 15;
y = 20; // Error: reassignment is not allowed
const arr = [1, 2, 3];
arr.push(4); // Allowed because the array's content can change

3. What is the difference between “==” and “===” in JavaScript?

== (Loose equality): This operator checks for equality after performing type coercion (automatic conversion of one type to another). If the two values are of different types, JavaScript attempts to convert them to the same type before making the comparison.

Example:

5 == '5'; // true because '5' is coerced to a number

=== (Strict equality): This operator checks for both value and type equality. No type conversion is performed, so if the types differ, the comparison will return false.

Example:

5 === '5';  // false because 5 is a number and '5' is a string

4. What is an object in JavaScript?

In JavaScript, an object is a collection of properties, where each property is defined as a key-value pair. Objects can store multiple related values, and the values can be of any type, including other objects, functions, arrays, etc.

Example:

const person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // Output: "Hello, John"

5. What is an array in JavaScript?

An array is a special type of object in JavaScript that stores an ordered collection of elements. Each element has an associated index, starting from 0. Arrays can hold elements of any data type and have methods to manipulate the data, such as push(), pop(), and forEach().

Example:

const arr = [1, 2, 3, 4];
console.log(arr[0]); // Output: 1
arr.push(5); // Adds 5 to the array

6. What is a function in JavaScript?

A function in JavaScript is a reusable block of code designed to perform a particular task. Functions can be defined using the function keyword or as an arrow function.

Example of a regular function:

function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // Output: "Hello, Alice"

Example of an arrow function:

const greet = (name) => "Hello, " + name;
console.log(greet("Alice")); // Output: "Hello, Alice"

7. What is an event in JavaScript?

An event in JavaScript refers to an action or occurrence detected by the browser, such as a mouse click, key press, or page load.

JavaScript provides event listeners or handlers to execute specific code in response to these events.

Example:

document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});

8. What is a callback function in JavaScript?

A callback function is a function passed as an argument to another function and is invoked after the completion of that function.

This pattern is often used in asynchronous code, where the callback function is called once an operation (like a server request) finishes.

Example:

function fetchData(callback) {
setTimeout(() => {
const data = "Data fetched";
callback(data); // Calling the callback function with fetched data
}, 1000);
}

fetchData((data) => console.log(data)); // Output after 1 second: "Data fetched"

9. What is a closure in JavaScript?

A closure is a function that retains access to the variables in its outer lexical environment, even after the outer function has returned. Closures enable private variables and encapsulation in JavaScript.

Example:

function outerFunction() {
let outerVariable = "I'm outside!";

function innerFunction() {
console.log(outerVariable); // The inner function has access to outerVariable
}

return innerFunction;
}

const closure = outerFunction();
closure(); // Output: "I'm outside!"

10. What is the purpose of “strict mode” in JavaScript?

“Strict mode” is a feature in JavaScript that enables a stricter parsing and error-checking mode for your code. It catches common coding mistakes and unsafe actions, such as using undeclared variables.

You can enable strict mode by adding "use strict"; at the beginning of a script or function.

Example:

"use strict";
x = 3.14; // Error: x is not declared

Advanced-Level JavaScript Interview Questions and Answers

11. What is prototypal inheritance in JavaScript?

Prototypal inheritance is a feature in JavaScript where objects can inherit properties and methods from other objects. Every JavaScript object has an internal property called [[Prototype]], which refers to another object.

This is known as the object’s prototype. When you try to access a property or method on an object, JavaScript looks up the prototype chain until it finds the property or reaches the end of the chain.

Example:

const animal = {
eats: true,
walk() {
console.log("Animal walks");
}
};

const rabbit = Object.create(animal);
rabbit.walk(); // Output: "Animal walks"

12. What is a module in JavaScript, and how do you create one?

A module in JavaScript is a self-contained piece of code that can be exported and imported into other code files. Modules allow for better code organization and reusability. In modern JavaScript, modules can be created using the import and export syntax.

Example:

math.js (module file):

export function add(a, b) {
return a + b;
}

main.js (importing module):

import { add } from './math.js';
console.log(add(5, 3)); // Output: 8

13. What is the difference between “call” and “apply” in JavaScript?

Both call and apply are methods in JavaScript that allow you to invoke a function with a specified this context, but the key difference between them lies in how they handle arguments passed to the function:

call: This method takes arguments individually, meaning you pass each argument one by one to the function when invoking it.

function greet(message) {
console.log(message + ", " + this.name);
}

const person = { name: "John" };
greet.call(person, "Hello"); // Output: "Hello, John"

apply: This method takes arguments as an array, meaning you pass a single array of arguments that will be unpacked and used as the arguments for the function when it is invoked.

greet.apply(person, ["Hi"]);  // Output: "Hi, John"

14. What is a higher-order function in JavaScript?

A higher-order function is a function that either takes one or more functions as arguments or returns another function as a result. Higher-order functions allow for the abstraction of actions, not just values.

Example:

function multiplyBy(factor) {
return function(number) {
return number * factor;
};
}

const double = multiplyBy(2);
console.log(double(5)); // Output: 10

15. What is the difference between synchronous and asynchronous code in JavaScript?

Synchronous code: Executes line by line in sequence. Each operation must complete before the next one begins, which can block the execution of further code if an operation is slow (e.g., file reading or network requests).

Example:

console.log("Start");
const data = readFileSync('file.txt'); // Blocking operation
console.log("End");

Asynchronous code: Allows other code to execute while waiting for operations like network requests or file I/O to complete. Asynchronous behavior is commonly handled using callbacks, Promises, or async/await.

Example:

console.log("Start");
readFileAsync('file.txt', () => console.log("File read"));
console.log("End");

16. What is the difference between a Promise and a Callback in JavaScript?

Callback: A function passed as an argument to another function, to be executed after an asynchronous operation completes.

Example:

function fetchData(callback) {
setTimeout(() => {
callback("Data fetched");
}, 1000);
}
fetchData(data => console.log(data)); // Output: "Data fetched" after 1 second

Promise: An object representing the eventual completion or failure of an asynchronous operation. Promises provide better error handling and a cleaner, more readable syntax.

Example:

const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
promise.then(data => console.log(data)); // Output: "Data fetched" after 1 second

17. What is the difference between “null” and “undefined” in JavaScript?

null: Represents an intentional absence of a value. It’s explicitly set by the programmer to indicate “no value.”

Example:

let a = null;
console.log(a); // Output: null

undefined: Represents the absence of a value by default. If a variable is declared but not initialized, it is undefined.

Example:

let b;
console.log(b); // Output: undefined

18. What is event bubbling in JavaScript?

Event bubbling is a mechanism where an event triggered on a child element propagates upward through its parent elements. When an event is triggered, it first runs the handler on the element where it occurred, then moves up to its parent, and so on until it reaches the root.

Example:

document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
});

document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});

In the example, clicking on the child element will also trigger the parent’s click handler due to event bubbling.

19. What is the difference between “document” and “window” in JavaScript?

window: Represents the global object in the browser environment, containing properties like setTimeout, alert, location, etc. It is the top-level object of the browser and represents the browser window.

Example:

console.log(window.location);  // Outputs the current URL

document: Represents the HTML document loaded in the window. It’s a property of the window object and provides methods to access and manipulate the DOM (Document Object Model).

Example:

console.log(document.title);  // Outputs the title of the current page

20. What is the purpose of the “use strict” directive in JavaScript?

The "use strict" directive enables strict mode in JavaScript, enforcing stricter parsing and error handling in the code. It helps catch common mistakes, such as using undeclared variables, and disallows some unsafe actions (e.g., defining duplicate property names).

Example:

"use strict";
x = 5; // Error: x is not declared

Common JavaScript Coding Interview Questions and Answers

21. Write a function to reverse a string in JavaScript.

Example:

function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString("hello")); // Output: "olleh"

22. Write a function to find the largest number in an array in JavaScript.

Example:

function findLargestNumber(arr) {
return Math.max(...arr);
}
console.log(findLargestNumber([1, 5, 3, 9, 2])); // Output: 9

23. Write a function to check if a given number is prime in JavaScript.

Example:

function isPrime(num) {
if (num < 2) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
console.log(isPrime(7)); // Output: true

24. Write a function to remove duplicates from an array in JavaScript.

Example:

function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4])); // Output: [1, 2, 3, 4]

25. Write a function to check if two strings are anagrams in JavaScript.

Example:

function areAnagrams(str1, str2) {
const formatString = str => str.toLowerCase().replace(/[^a-z0-9]/g, '').split('').sort().join('');
return formatString(str1) === formatString(str2);
}
console.log(areAnagrams("listen", "silent")); // Output: true

26. Write a function to find the factorial of a given number in JavaScript.

Example:

function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120

27. Write a function to sort an array in JavaScript.

Example:

function sortArray(arr) {
return arr.sort((a, b) => a - b);
}
console.log(sortArray([4, 2, 7, 1])); // Output: [1, 2, 4, 7]

28. Write a function to implement a stack in JavaScript.

A stack follows the LIFO (Last In, First Out) principle.

Example:

class Stack {
constructor() {
this.items = [];
}

push(element) {
this.items.push(element);
}

pop() {
return this.items.pop();
}

peek() {
return this.items[this.items.length - 1];
}

isEmpty() {
return this.items.length === 0;
}
}

const stack = new Stack();
stack.push(10);
stack.push(20);
console.log(stack.pop()); // Output: 20

29. Write a function to implement a queue in JavaScript.

A queue follows the FIFO (First In, First Out) principle.

Example:

class Queue {
constructor() {
this.items = [];
}

enqueue(element) {
this.items.push(element);
}

dequeue() {
return this.items.shift();
}

front() {
return this.items[0];
}

isEmpty() {
return this.items.length === 0;
}
}

const queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
console.log(queue.dequeue()); // Output: 10

30. Write a function to implement binary search in JavaScript.

Example:

function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;

while (low <= high) {
let mid = Math.floor((low + high) / 2);

if (arr[mid] === target) return mid;
if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}

return -1; // Target not found
}

console.log(binarySearch([1, 2, 3, 4, 5], 3)); // Output: 2

31. Write a function to implement bubble sort in JavaScript.

Example:

function bubbleSort(arr) {
let swapped;
do {
swapped = false;
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true;
}
}
} while (swapped);
return arr;
}
console.log(bubbleSort([5, 1, 4, 2])); // Output: [1, 2, 4, 5]

32. Write a function to implement quicksort in JavaScript.

Example:

function quickSort(arr) {
if (arr.length <= 1) return arr;

const pivot = arr[arr.length - 1];
const left = [];
const right = [];

for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] < pivot) left.push(arr[i]);
else right.push(arr[i]);
}

return [...quickSort(left), pivot, ...quickSort(right)];
}

console.log(quickSort([5, 3, 7, 2, 1])); // Output: [1, 2, 3, 5, 7]

33. Write a function to implement a linked list in JavaScript.

Example:

class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}

class LinkedList {
constructor() {
this.head = null;
}

append(value) {
const newNode = new ListNode(value);

if (!this.head) {
this.head = newNode;
return;
}

let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}

display() {
let current = this.head;
while (current) {
console.log(current.value);
current = current.next;
}
}
}

const list = new LinkedList();
list.append(1);
list.append(2);
list.display(); // Output: 1, 2

34. Write a function to implement a binary tree in JavaScript.

Example:

class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}

class BinaryTree {
constructor() {
this.root = null;
}

insert(value) {
const newNode = new TreeNode(value);

if (!this.root) {
this.root = newNode;
return;
}

const insertNode = (node, newNode) => {
if (newNode.value < node.value) {
if (!node.left) node.left = newNode;
else insertNode(node.left, newNode);
} else {
if (!node.right) node.right = newNode;
else insertNode(node.right, newNode);
}
};

insertNode(this.root, newNode);
}
}

const tree = new BinaryTree();
tree.insert(10);
tree.insert(5);
tree.insert(15);

35. Write a function to implement breadth-first search in a binary tree in JavaScript.

Example:

function breadthFirstSearch(root) {
const queue = [root];
while (queue.length) {
const currentNode = queue.shift();
console.log(currentNode.value);

if (currentNode.left) queue.push(currentNode.left);
if (currentNode.right) queue.push(currentNode.right);
}
}

36. Write a function to implement depth-first search in a binary tree in JavaScript.

Example:

function depthFirstSearch(root) {
if (!root) return;

console.log(root.value);
depthFirstSearch(root.left);
depthFirstSearch(root.right);
}

37. Write a function to compare two binary trees in JavaScript.

Example:

function areTreesEqual(root1, root2) {
if (!root1 && !root2) return true;
if (!root1 || !root2) return false;
if (root1.value !== root2.value) return false;

return areTreesEqual(root1.left, root2.left) && areTreesEqual(root1.right, root2.right);
}

Related Posts