10 JavaScript interview questions with solutions and code
How do you check if a variable is an array?
Solution:
function isArray(variable) {
return Array.isArray(variable);
}
What is the difference between null and undefined in JavaScript?
Solution:
null is an intentional absence of any object value and is often used to indicate a deliberate non-value. undefined indicates the absence of any value or reference.
What is the difference between == and === operators in JavaScript?
Solution:
== performs type coercion and checks the value of the operands, whereas === checks the type and value of the operands.
How do you reverse a string in JavaScript?
Solution:
function reverseString(str) {
return str.split(”).reverse().join(”);
}
What is the difference between let, const and var in JavaScript?
Solution:
let and const are block-scoped and cannot be redeclared in the same scope. var is function-scoped and can be redeclared.
How do you check if a number is an integer in JavaScript?
Solution:
function isInteger(num) {
return Number.isInteger(num);
}
How do you remove a specific element from an array in JavaScript?
Solution:
function removeElementFromArray(array, element) {
return array.filter(e => e !== element);
}
What is a closure in JavaScript and how do you use it?
Solution:
A closure is a function that has access to variables in its outer (enclosing) function’s scope chain. You can create a closure in JavaScript by returning a function from another function.
function outerFunction() {
const message = ‘Hello, ‘;
function innerFunction(name) {
console.log(message + name);
}
return innerFunction;
}
const greeting = outerFunction();
greeting(‘John’); // Output: Hello, John
What is the difference between synchronous and asynchronous code in JavaScript?
Solution:
Synchronous code executes in a predictable order, one line at a time. Asynchronous code can execute out of order and can allow other code to continue while it is waiting for an operation to complete, such as an API call or a file read.
How do you handle errors in JavaScript?
Solution:
You can handle errors in JavaScript using try/catch blocks.
try {
// Code that might throw an error
} catch (error) {
// Handle the error
}