Information Technology

JavaScript Interview Questions and Answers

JavaScript Interview Questions and Answers

JavaScript Interview Questions and Answers

1. What is JavaScript?
JavaScript is a high-level, interpreted programming language used to create interactive effects within web browsers.
 
2. Different types of variables in JavaScript?
- var: Variable redeclaration is possible. Variable reassignment is possible. This variable type is having "Global scope".
 
- let: Variable redeclaration is not possible. Variable reassignment is possible. This variable type is having "Block scope".
 
- const: Variable redeclaration is not possible. Variable reassignment is also not possible. This variable type is having "Block scope".
 
3. What is hoisting variable/function?
Hoisting is a javascript concept where variable and function declarations are moved to the top of their containing scope during the compilation phase. Due to this concept, you can use variable or function before their declarations.
 
4. Explain the difference between '==' and '===' in JavaScript.
'==' compares just the value, while '===' (strict equality operator) compares both value and data-type.
 
5. What is the difference between undefined and null?
'undefined' means a variable has been declared but not assigned a value. 'null' is an assignment value representing a deliberate absence of any object value.
 
6. Explain the difference between 'synchronous' and 'asynchronous' code.
Synchronous code executes line by line and blocks further execution until the current operation is complete. Asynchronous code allows the program to continue to run while waiting for an operation to complete.
 
7. What is Template String or Template Literals?
Template string is string interpolation feature, through which we can interpolate variables and expressions into strings.
 
Example-1: let user = `Welcome ${user}`;
 
Example-2: let total = `Total: ${price * no_of_products * tax}`;
 
8. What is Arrow function?
An arrow function expression is a compact and lightweight alternative to a traditional function expression with a focus on being short in syntax.
 
Example:
//traditional syntax
function multiply(a, b) {
  return a * b;
}
 
//arrow function syntax
let multiply = (a, b) => a * b;
 
9. What is Rest Operator or Rest Parameter?
Rest Parameter is a feature of the JavaScript which uses a specific syntax and allows a function to accept an indefinite number of arguments as an array. The syntax for the Rest Parameter is denoted by three dots (...) followed by the array name that will contain the rest of the function's arguments. There should be only one Rest operator into the single function definition. Also it should be the last parameter, otherwise it will through an error.
 
Example:
let sum = (name, ...args) => {
   let sum = 0;
   for(let i in args) {
      sum += args[i];
   }
   return sum;
};
 
10. What is Spread Operator?
Spread operator is a javascript feature which allows you to spread out elements of an iterable objects, such as an array, map or set etc.
 
Example:
const odd = [1,3,5];
const combined = [2,4,6, ...odd];
console.log(combined);
// op - [2,4,6,1,3,5]
 
11. What is Array Destructuring?
Array Destructuring is a javascript technique which helps us to neatly extract or copy or assign iterable oject's values into variables, at a time. Iterable oject can be an array, map or set etc.
 
Example:
let arr = ["Hello", "World"];
let [first, second] = arr;
console.log(first+', '+second);
// op - Hello, World
 
12. Explain the concept of callback functions.
Callback functions are functions passed as arguments to another function to be executed later when the first function has completed.
 
Example:
function test(callback) {  
    callback();
}
 
13. What is Promise?
Promise is a javascript concept to handle asynchronous operations. It is used to find out if the asynchronous operation is successfully completed or not, instead of callback function calls. A promise can have three states:
- Pending
- Fulfilled
- Rejected
 
Create promise object:
let promObj = new Promise(
  function(resolve, reject){
   const res = fetch('<api_url>').json();
   if(res)
     resolve(data);
   else
     reject("Failed to load json");
 }
);
 
promObj.then((result) => {
   console.log(result);
}).catch((error) => {
   console.log(error);
});
 
14. What is Async Await?
Async function is a function which is declared with 'async' keyword and the zero or more 'await' expressions inside it. Async and await, providing asynchronous and promise-based behaviour to be written in a cleaner style, avoiding the need to explicitly configure promise chains. Async function always return output in the promise format. Await operator is used to wait for a promise. Note, it only makes the async function wait and not the whole program execution.
 
Example:
async function test() {
  const res = await fetch('<api_url>').json();
  return res;
}
 
test().then((res) => {
    console.log(res);
});
 
15. What is Ajax?
Ajax (Asynchronous JavaScript and XML) is used to update content of web-page asynchronously. Means due to ajax concept, specific page section content can update without refreshing whole page. AJAX is the combination of XMLHttpRequest Object, JavaScript and HTML DOM (Document Object Model).
 
16. What is fetch() method?
The fetch() method in javascript is used to request to the server and lead the data on the web-pages. The request can be of any APIs that return the data in the format of JSON or XML. This method always returns a promise.
 
Syntax:
fetch('<api_url>')
.then(response => response.json())
.then(data => console.log(data));
 
Parameters:
- URL: URL to which the request is to be made.
- Options: Array of properties (optional).
 
17. What is Symbol?
JavaScript Symbols are a new type of primitive data type. They are used to represent unique values that can be used as identifiers or keys in objects. They are also used to create private properties and methods in classes.
 
Syntax: const mySymbol = Symbol();
 
18. What is Generators in JavaScript?
A generator function is a special function type in JavaScript that allows pausing and resuming its execution during runtime. Unlike normal javascript functions, which run to completion, generator functions can be paused and resumed multiple times, making them useful for dealing with asynchronous operations, handling large datasets and writing custom iterators.
 
Generator functions are defined using the function* syntax, and they use the yield keyword to pause the function's execution and produce a value. When a generator function is called, it returns an iterator object, which can be used to control the function's execution.
 
Example:
function* myGenerator() {
    yield 2;
    yield 4;
}
 
const iterator = myGenerator();
console.log(iterator.next());
// Output: { value: 2, done: false }
console.log(iterator.next());
// Output: { value: 4, done: false }
console.log(iterator.next());
// Output: { value: undefined, done: true }
 
19. What is Self Invoking Function?
The self-invoking function in JavaScript are known as "Immediately Invoked Function Expressions". It is a function that executes immediately after it has been defined so there is no need to call it manually.
 
Syntax:
(function(){
    //code
})();
 
20. What is Closure?
Closure is an ability of a function to remember the variables and functions that are declared in its outer scope.
 
Example:
let myFun = () => {
    let cnt = 6;
    return () => cnt * cnt;
}
 
let myFunInst = myFun();
myFunInst(); // 36
 
21. What is Currying?
Currying is a technique that involves breaking down a function that takes multiple arguments into a series of functions that take one argument each. This creates a chain of functions, where each function returns another function until the final result is achieved.
 
Example:
function add(a) {
    return function(b) {
         return a + b;
    }
}
 
add(2)(4);
 
22. Explain event capturing?
Event capturing refers to the propagation of events from the outermost element to the innermost element.
 
23. Explain event bubbling?
Event bubbling refers to the propagation of events from the innermost element to the outermost element.
 
24. What is the difference between setTimeout() and setInterval()?
'setTimeout()' executes a function once after a specified delay, while 'setInterval()' repeatedly executes a function at a given interval.
 
25. What is the purpose of the 'use strict' directive in JavaScript?
The 'use strict' directive enables strict mode, which catches common coding errors and provides improved error handling.
 
26. What is the purpose of the localStorage and sessionStorage objects in JavaScript?
Both localStorage and sessionStorage provide a way to store key-value pairs locally in the browser, but localStorage persists even after the browser is closed, while sessionStorage is cleared when the session ends.
 
27. Explain the concept of type coercion in JavaScript.
Type coercion is the automatic conversion of values from one data type to another, which can occur when using operators or comparing values of different types.
 
28. What is the 'NaN' property?
NaN stands for "Not a Number" and is returned when a mathematical operation that expects a number, but receives a value that is not a number.
 
29. What is the purpose of the arguments object in JavaScript?
The 'arguments' object is an array-like object containing the arguments passed to a function. It allows you to access the arguments dynamically, regardless of the number of parameters defined in the function signature.
 
30. What is the purpose of the export and import keywords in JavaScript?
'export' is used to export functions, objects, or primitives from a module, making them available for use in other modules. 'import' is used to import functionalities from other modules into the current module.
 
31. What are the different ways to loop through an array in JavaScript?
You can loop through an array using for loops, forEach(), map(), for...of loops, and for...in loops.