Table of contents
No headings in the article.
Hey Reader , I am a Front-end Developer and recently , i have been looking for a job switch and after giving interviews for various companies . I collected a few questions that were frequently asked and helped me to ace my JS interviews.
Q1. What are the datatypes in Js?
Ans. Primitive : The predefined datatype that is provided by Js(builtin) , it gets called by value means the copy get passed and the copy is changed not the actual value.
Undefined(identifier): represent absence of value.
Number : used to hold decimal values as well as values without decimals.
Null(keyword) : hold the value Null.
Big Int: represent numbers greater than 253-1 which helps to perform operations on large numbers.
Boolean: accept only two values i.e. true and false.
Symbol: This data type is used to create objects which will always be unique. these objects can be created using Symbol constructor.
String : it holds sequence of character sorrounded by single or double quotes.
Non-Primitive Datatypes: Derived from the primitive
Object: key value pairs.
Array : [1,2,3]
Q2. Difference between undefined and null
Ans. Undefined is a placeholder for those variable that has been declared but has yet not been assigned a value.
let x;
console.log(x); // Output: undefined
function getData() {
// No return statement
}
console.log(getData()); // Output: undefined
Null is an assignment value. It can be assigned to a variable as a representation of no value.It is a primitive value that denotes a null or empty value.
let x = null;
console.log(x); // Output: null
Q3. Explain the difference between var , let and const in Javascript
Ans. Var : it is function scoped, can be updated and redeclared,declared without initialization
let : let is block scope, can be updated but cannot be re-declared into the scope,can be declared without initialization, cannot be accessed without initialization otherwise it will give ‘referenceError’.
const : const is block scope, cannot be updated or re-declared into the scope,cannot be declared without initialization.
Q4. What is Temporal date zone?
Ans. let or const variable is said to be in a "temporal dead zone" (TDZ) from the start of the block until code execution reaches the line where the variable is declared and initialized, While inside the TDZ, the variable has not been initialized with a value, and any attempt to access it will result in a ReferenceError
. The variable is initialized with a value when execution reaches the line of code where it was declared.
console.log(x); // Output: ReferenceError: x is not defined
let x = 5; // till we reach this line x is in temporal dead zone
Q5. What are the features introduced in es6?
Ans. most popular ES6 features that we can use in your everyday JavaScript coding.
let and const Keywords
Arrow Functions
Multi-line Strings
Default Parameters
Template Literals
Destructuring Assignment
Enhanced Object Literals
Promises
Classes
Modules
Q6. What is Template literal/Interpolation/Template string ?
Ans. Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.
let a = "Ajay"
let b = "Chauhan"
console.log(`My name is ${a} ${b}`)
Q7. What are mutable and immutable?
Ans. When an object or data structure is mutable, it means that its state or value can be modified after it is created. In JS objects, arrays, and functions, are mutable. This means you can modify their properties, elements, or behavior directly.
let person = { name: "Ravi", age: 20 };
person.age = 21; // Modifying the age property
Immutable: refers to the property of an object or data structure that cannot be changed once it is created
let s1 = "Hello";
let s2 = greeting + ", World!"; // Concatenating strings creates a new string
in the above case s1 remains the same
Q8. Explain Code execution in Js
Ans. Js is a synchronous single threaded language means that it can only execute one line at a time means that it can only go to the next line once the current line get executed.
Whenever we run any js program execution context is created
Memory Creation Phase: in the first phase js skims through the program and allocates memory , Variables are stored as undefined , functions are stored with their whole code.
Code Execution Phase: The value of the variables are now placed and when function is invoked new execution context is created where the above two "memory creation and code execution " happens again and after the function code is finished the control get back to the program
Js has its call stack where the global execution context in pushed once there is any function invoked there is formation of new execution and it is push in the call stack and after execution it is popped out of the call stack.
var a = 10;
function sum (num){
var summ = num+num;
return summ;
}
var data1 = sum(a);
Q9. What is Hoisting?
Ans: During the memory creation phase the memory is allocated to the variable and functions and due to that if we access the variable before it is defined it will give undefined and for the function it will return the proper value.This process is called Hoisting.
getHello();
console.log(a);
var a = 10;
function getHello(){
console.log("Hello World")
}
o/p:
Hello World // because during memory creat phase func is stored inside memory.
undefined
Are let and const Hoisted : yes, because they are not in global space,they remain in the temporal dead zone until they are explicitly declared in the code.
Q10. What is Type Coercion?
Ans. Type Coercion means that if the datatypes of the operands we are comparing are different, then the JavaScript Engine automatically converts one of the operands to be the same as the other one in order to make the comparison possible.
Rules of type coecion:
If either operand is a string, the other operand will be converted to a string
If either operand is a number, the other operand will be converted to a number.
If either operand is a boolean, it will be converted to a number( true = 1 and false = 0).
If one operand is an object and the other is a primitive value, the object will be converted to a primitive value before the comparison is made.
If one of the operands is null or undefined, the other must also be null or undefined to return true. Otherwise it will return false.
Q11. Difference between == and ===
Ans. Double equals (==) is often referred to as 'loose equality' because it performs type coercion before making any comparison.
const a = 100; a is converted to string
const b = '100';
console.log(a == b) // true
Triple equals (===), also referred to as "strict equality", it does not convert the types of the operands before comparing.
const a = 100;
const b = '100';
console.log(a === b); // false because of different datatype and no coversion
Q12. What is Scope and Scope Chain?
Ans. Scope determines the accessibility and visibility of variables, functions, and objects in a particular part of code. It defines the portion of the code where a particular variable or function can be accessed.
Global Scope: Variables declared outside of any function or block have global scope. They can be accessed from anywhere within the code, including other functions or blocks.
Local Scope: Variables declared inside a function or block have local scope. They can only be accessed within the function or block where they are defined. Local variables are not accessible from outside the function or block, and their scope is limited to the specific context in which they are declared.
var a = 10; function ab(){ console.log("This is the global scope variable---" , a); } function ac(){ var b = 20; console.log("This is the local scope variable---" , b); } ab(); O/P-- This is the global scope variable--- 10 ac(); O/P-- This is the local scope variable--- 20 console.log(b); O/P-- ReferenceError: b is not defined
Scope Chain : Whenever a Execution context is created, a lexical environment(local memory + lexical environment of parent) is also created. It determines the order in which JavaScript looks for variables and functions when they are referenced.
When you reference a variable or call a function, JavaScript starts searching for it within the current scope. If the variable or function is not found, it continues to search in the outer scope, and this process continues until it either finds the desired variable/function or reaches the global scope.
Q13. What is a Block?
Ans. Block is a set of statements enclosed within curly braces {}
. Blocks are used to group multiple statements together and define the scope of variables and functions. It can be used in a place where Js expect single statement . Example -- function bodies, loop bodies, conditional statements.
Q14. What is Optional Chaining?
Ans. Optional chaining allows safe access nested properties of an object without worrying about whether intermediate properties exist or not. It provides a concise way to handle situations where a property or method might be undefined or null. Without optional chaining it will return error and with it it will be undefined. If any of the intermediate properties along the chain are nullish (null or undefined), the expression will immediately return undefined without attempting to access the subsequent properties.
const calculator = {
add: function (a, b) {
return a + b;
}
};
console.log(calculator.subtract.(2, 3)); // ERROR SyntaxError: Unexpected token '('
console.log(calculator.subtract?.(5, 2)); // undefined
Q15. Spread and Rest operator
Ans. The spread operator is used to unpack elements from an array or object. It spreads the individual elements or properties of the source into a new array or object.
In arrays, the spread operator is used to create a shallow copy of an array or concatenate multiple arrays into a single array.
In objects, the spread operator is used to create a new object by merging properties from multiple source objects.
```javascript const numbers = [1, 2, 3]; const copy = [...numbers]; // Creates a shallow copy of the numbers array
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combined = [...arr1, ...arr2]; // Concatenates arr1 and arr2 into a single array [1, 2, 3, 4, 5, 6]
const obj1 = { x: 1, y: 2 }; const obj2 = { z: 3 }; const merged = { ...obj1, ...obj2 }; // Creates a new object with properties from both Output: { x: 1, y: 2, z: 3 }
const names = ["Alia", "Deepika","Sushmita"]; function getNames(n1,n2,n3){ console.log(n1,n2,n3); }
getNames(...names); Output: Alia Deepika Sushmita
Rest Operator : The rest operator is used in function parameters to gather the remaining arguments into an array, allows functions to accept a variable number of arguments and access them conveniently as an array.
```javascript
function sum(...val){
sum = 0;
val.map(e=>sum+=e);
console.log(sum);
}
sum(2,3,4); o/p -- 9
var students={
name:"Ajay",
age:28,
hobbies:["Travelling","Cycling"]
}
const {age,...rest} = students;
console.log(rest); -- { name: 'Ajay', hobbies: [ 'Travelling', 'Cycling' ] }
console.log(age); --28
Q16. What is Closure?
Ans. Functions along with its lexical environment is called closure. It allows functions to retain access to variables and parameters from their parent scope, even after the parent function has finished executing.
function a(){
var a = 10;
function b(){
console.log(a);
}
return b;
}
var b = a();
console.log(b);
b();
Even a has finished executing, the b still maintains a reference to its parent
scope including the variable a.
When closureFunction() is called, it executes the b function, which logs the
value of a (which is still accessible) to the console.
Q17. Deep copy vs Shallow copy
Ans. Shallow Copy : when we copy a object by using assignment operator . They both reference to the same object and when we change any of them ultimately it change other one.
Deep Copy: it creates a completely independent copy of an object or array, including all nested objects or arrays. It recursively copies all values, ensuring that any changes made to the copy do not affect the original.
Shallow Copy
let originalObject = { name:"Shyam", age:20 }
let copiedObject = originalObject
Deep Copy
1. using JSON.stringify
let originalObject = { name:"Shyam", age:20 }
let obj2 = JSON.parse(JSON.stringify(originalObject))
obj2.name = "Ram"
console.log(originalObject) -- { name: 'Shyam', age: 20 }
console.log(obj2) -- { name: 'Ram', age: 20 }
Disadvantage: Doesnt copy the function of the object.
2. Using Object.assign()
let copiedObject = Object.assign({},originalObject);
Diasdvantage: give partial deep copy, if we have nested object the nested
one will be mutated.
3. Using Spread Operator
let copiedObject = {...originalObject}
copiedValue.address.city = "Dehradun"; // will do same like object.assign
so instead of that we need to update like(for nested keys)
copiedValue = {
...copiedValue,address:{...copiedValue.address,city:"Dehradun"}
}
4. Loadash Library: clone deep method
Q18. Dom and Bom
Ans. DOM stands for Document Object Model. It is a programming interface that represents the HTML or XML document as a structured tree-like model, where each element of the document is represented as a node in the tree. The DOM provides methods and properties to interact with these nodes, allowing you to manipulate and traverse the document dynamically.
DOM provides several methods to find & manipulate the behavior of the HTML Document:
getElementsByName()
BOM(Browser Object Model) : It represents the browser window or tab that contains the DOM document. It allows JavaScript to “interact with” the browser environment, such as manipulating the browser history, controlling the location of the current page, displaying dialog boxes, and accessing information about the browser and its capabilities.
Q19 Local storage, session storage and cookies
Ans. Local storage: refers to a web browser feature that allows you to store data persistently on the client-side. It provides a simple key-value storage mechanism and is useful for saving small amounts of data that need to be accessed across different sessions or pages within a website.
localStorage.setItem('key', 'value'); //setting data
var value = localStorage.getItem('key'); // getting data
localStorage.setItem('key', 'new value'); //updating data
localStorage.removeItem('key'); //removing data
localStorage.clear(); //clearing data
Cookies : are small pieces of data that websites can store on a user's web browser. Cookies are commonly used to track and maintain information about the user's browsing behavior, preferences, and session state. They can be accessed and manipulated using the document.cookie property.
Setting cookies
document.cookie = "cookieName=cookieValue; expires=expirationDate; path=pathValue";
var cookies = document.cookie; // Retrieving
document.cookie = "cookieName=; expires=expirationDate; path=pathValue"; //Deleting
Session Storage : is a web storage mechanism provided by modern web browsers that allows you to store key-value pairs of data during a user's session on a website. It provides a way to store data on the client side, meaning the data is saved locally on the user's device and can be accessed and manipulated using JavaScript.
sessionStorage.setItem('key', 'value');
sessionStorage.setItem('username', 'Jake'); //setting items
const value = sessionStorage.getItem('key');
const username = sessionStorage.getItem('username'); //getting items
console.log(username); // Output: Jake
sessionStorage.removeItem('key'); //removing items
sessionStorage.clear(); // clearing items
Q20. call apply bind
Ans. Call : method allows you to invoke a function and specify the value of this explicitly. It also accepts multiple arguments that are passed to the function individually.
It follows the concept of function borrowing where one objectt borrowing the function of another object
let ob1 = {
name:"Ajay Chauhan",
Age:28,
printDetails:function(country){
console.log(this)}
}
ob1.printDetails();
let ob2 = {
name:"John Doe",
Age:30 }
ob1.printDetails.call(ob2);
Giving multiple arguments
let ob1 = {
name:"Ajay Chauhan",
Age:28,
printDetails:function(country){
console.log(this.name + " " + country)}
}
let ob2 = {
name:"John Doe",
Age:30 }
ob1.printDetails("Indian");
ob1.printDetails.call(ob2,"Indian");
Apply : same as call but the argument we pass in is array list.
let ob1 = {
name:"Ajay Chauhan",
Age:28,
}
let printDetails=function(city,country){
console.log(this.name + " " + city + " " + country)
}
printDetails.apply(ob1,["Dehradun","India"]);
let ob2 = {
name:"John Doe",
Age:30
}
printDetails.apply(ob2,["Dehradun","India"]);
Bind :It is like call, It gives a copy of the function rather than calling it right away which can be invoked later when needed in the program.
let ob1 = {
name:"Ajay Chauhan",
Age:28,
}
let printDetails=function(city,country){
console.log(this.name + " " + city + " " + country)
}
printDetails.apply(ob1,["Dehradun","India"]);
let ob2 = {
name:"John Doe",
Age:30
}
let newOne = printDetails.bind(ob2,["Dehradun","India"]);
newOne();