Top 50 JavaScript interview questions along with their answers and examples:
Other Technical Interview Questions and Answers
1. What is JavaScript?
JavaScript is a high-level, interpreted scripting language primarily used for front-end web development to make web pages interactive.
2. What are the different data types in JavaScript?
JavaScript has seven data types: undefined, null, boolean, number, string, object, and symbol (added in ES6).
3. How do you declare a variable in JavaScript?
You can declare a variable using var, let, or const. Example:
var name = "John";
let age = 30;
const PI = 3.14;
4. Explain the difference between var, let, and const.
var has function scope, while let and const have block scope.
let allows reassignment, while const does not.
5. What is a closure in JavaScript?
A closure is a function that has access to its own scope, the outer function's scope, and the global scope.
6. What is the 'this' keyword in JavaScript?
this refers to the current object in a method or function.
7. What is an IIFE (Immediately Invoked Function Expression)?
An IIFE is a function that is executed immediately after it is defined. Example:
(function() {
// Code here
})();
8. Explain hoisting in JavaScript.
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their containing scope.
9. What is a callback function?
A callback function is a function passed as an argument to another function to be executed later.
10. How do you create an array in JavaScript?
- You can create an array using square brackets. Example:
javascript let fruits = ['apple', 'banana', 'orange'];
11. Explain the difference between '==' and '===' operators.
- == checks for equality with type coercion, while === checks for equality without type coercion (strict equality).
12. What is a promise in JavaScript?
- A promise is an object representing the eventual completion or failure of an asynchronous operation.
13. How do you handle exceptions in JavaScript?
- You can use try...catch to handle exceptions. Example:
javascript try { // Code that may throw an exception } catch (error) { // Handle the exception }
14. What is the difference between 'null' and 'undefined' in JavaScript?
- null is an assignment value that represents the absence of an object value, while undefined means a variable has been declared but has not been assigned a value.
15. Explain event delegation in JavaScript.
- Event delegation is a technique where you attach a single event listener to a parent element to manage events on its child elements efficiently.
16. What is the purpose of the bind() method in JavaScript?
- The bind() method is used to create a new function with a specified this value and initial arguments.
17. What is the purpose of the map() function in JavaScript?
- The map() function is used to create a new array by applying a given function to each element of the original array.
18. How do you create a class in JavaScript (ES6)?
- You can create a class using the class keyword. Example:
javascript class Person { constructor(name) { this.name = name; } }
19. Explain the concept of prototypal inheritance in JavaScript.
- In JavaScript, objects inherit properties and methods from a prototype object.
20. What is the difference between 'null' and 'undefined' in JavaScript?
21. How do you handle asynchronous operations in JavaScript?
- You can use callbacks, promises, or async/await to handle asynchronous operations.
22. What is the Event Loop in JavaScript?
- The Event Loop is a mechanism that allows JavaScript to execute non-blocking code asynchronously.
23. Explain the purpose of the 'localStorage' and 'sessionStorage' objects.
- localStorage and sessionStorage are used to store key-value pairs in a web browser.
24. What is the purpose of the 'fetch' API in JavaScript?
- The 'fetch' API is used for making network requests and fetching data from a server.
25. What is JSON and how is it used in JavaScript?
- JSON (JavaScript Object Notation) is a lightweight data interchange format used to exchange data between a server and a web application.
26. How do you check the type of a variable in JavaScript?
- You can use the typeof operator. Example:
javascript typeof variableName;
27. What is the purpose of the 'bind' method in JavaScript?
bind method is used to create a new function that, when called, has its this keyword set to a specific value, and allows the pre-specification of arguments. This is particularly useful when you want to ensure that a function is called with a specific context, regardless of how it's invoked.
Here's a brief example:
const myObject = {
x: 42,
getX: function() {
return this.x;
}
};
28. How do you add an element to the DOM using JavaScript?
- You can use methods like appendChild() or insertBefore(). Example:
javascript const newElement = document.createElement('div'); parentElement.appendChild(newElement);
29. Explain event propagation in JavaScript.
- Event propagation refers to the order in which events are sent to and handled by elements in the DOM.
30. What is a closure in JavaScript, and why is it useful?
A closure in JavaScript is the combination of a function and the lexical environment within which that function was declared. This lexical environment consists of the variables that were in scope at the time the closure was created. Closures allow a function to access and manipulate variables from its outer (enclosing) scope even after that scope has finished executing.
Here's a simple example to illustrate:
```javascript
function outerFunction() {
let outerVariable = 'I am from the outer function';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const closure = outerFunction();
closure(); // Outputs: "I am from the outer function"
31. How do you remove an element from the DOM using JavaScript?
- You can use the removeChild() method. Example:
javascript const elementToRemove = document.getElementById('myElement'); parentElement.removeChild(elementToRemove);
32. What is a callback function in JavaScript?
33. How do you define and call a function in JavaScript?
- You can define a function using the function keyword or using arrow functions (ES6). Example:
javascript function sayHello() { console.log('Hello, world!'); }
34. What is the difference between 'null' and 'undefined' in JavaScript?
In JavaScript, `null` and `undefined` are both special values that indicate the absence of a meaningful value, but they are used in slightly different contexts.
1. undefined`:
- A variable that has been declared but has not been assigned a value is `undefined`.
- Function parameters that are not passed a value default to `undefined`.
- Accessing an object property or array element that doesn't exist returns `undefined`.
- The result of a function that doesn't explicitly return a value is `undefined`.
Example:
```javascript
let x;
console.log(x); // Outputs: undefined
function exampleFunction(y) {
console.log(y);
}
exampleFunction(); // Outputs: undefined
```
2. `null`:
- `null` is explicitly assigned by a programmer to represent the absence of any object value or a deliberate non-value.
- It is often used to indicate that a variable, object property, or function parameter should have no value or is intentionally empty.
Example:
```javascript
let y = null;
console.log(y); // Outputs: null
```
35. How do you convert a string to a number in JavaScript?
- You can use parseInt() or parseFloat(). Example:
javascript let str = '42'; let num = parseInt(str);
36. How do you reverse a string in JavaScript?
- You can use the split(), reverse(), and join() methods. Example:
javascript let str = 'Hello'; let reversedStr = str.split('').reverse().join('');
37. How do you check if an array includes a specific value in JavaScript?
- You can use the includes() method. Example:
javascript let numbers = [1, 2, 3, 4, 5]; let hasThree = numbers.includes(3);
Top 10 JavaScript programming questions that are commonly asked in interviews, along with their solutions:
1. Reverse a String:
Question: Write a function to reverse a string in JavaScript.
Solution:
function reverseString(inputStr) {
return inputStr.split('').reverse().join('');
}
2. Find the Largest Number in an Array:
Question: Write a function to find the largest number in an array in JavaScript.
Solution:
function findLargestNumber(arr) {
return Math.max(...arr);
}
3. Check for Palindrome:
Question: Write a function to check if a given string is a palindrome in JavaScript.
Solution:
function isPalindrome(inputStr) {
return inputStr === inputStr.split('').reverse().join('');
}
4. Calculate Factorial:
Question: Write a function to calculate the factorial of a number in JavaScript.
Solution:
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
5. Find Prime Numbers:
Question: Write a function to find all prime numbers within a given range in JavaScript.
Solution:
function isPrime(n) {
if (n <= 1) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
function findPrimesInRange(start, end) {
const primes = [];
for (let i = start; i <= end; i++) {
if (isPrime(i)) primes.push(i);
}
return primes;
}
6. Fibonacci Sequence:
Question: Write a function to generate the Fibonacci sequence up to a given number of terms in JavaScript.
Solution:
function fibonacci(n) {
const sequence = [0, 1];
while (sequence.length < n) {
sequence.push(sequence[sequence.length - 1] + sequence[sequence.length - 2]);
}
return sequence;
}
7. Check Anagram:
Question: Write a function to check if two strings are anagrams of each other in JavaScript.
Solution:
function areAnagrams(str1, str2) {
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
8. Reverse a Linked List:
Question: Write a function to reverse a singly linked list in JavaScript.
Solution:
class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
function reverseLinkedList(head) {
let prev = null;
let current = head;
while (current !== null) {
const next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
9. Two Sum:
Question: Given an array of integers, return indices of the two numbers such that they add up to a specific target in JavaScript.
Solution:
function twoSum(nums, target) {
const numIndices = {};
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (complement in numIndices) {
return [numIndices[complement], i];
}
numIndices[nums[i]] = i;
}
return null;
}
10. Deep Clone an Object:
- Question: Write a function to deep clone an object in JavaScript.
- Solution:
javascript function deepClone(obj) { if (obj === null || typeof obj !== 'object') { return obj; } const clonedObj = Array.isArray(obj) ? [] : {}; for (let key in obj) { if (obj.hasOwnProperty(key)) { clonedObj[key] = deepClone(obj[key]); } } return clonedObj; }
0 Comments
Thank You for comment
if you have any queries then Contact us k2aindiajob@gmail.com