Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

JavaScript Interview Questions

Question

Uploaded by

jaiishtadev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

JavaScript Interview Questions

Question

Uploaded by

jaiishtadev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

JavaScript Interview Questions

What are different types of data types in JS

• Primitive data type and non-primitive data type


• Primitive data type → String, number, BigInt, Boolean, Undefined, null, Symbol
• Non-Primitive data type → Object

typeof "John Doe" // Returns "string"


typeof 3.14 // Returns "number"
typeof true // Returns "Boolean"
typeof 234567890123456789012345678901234567890n // Returns bigint
typeof undefined // Returns "undefined"
typeof null // Returns "object" (kind of a bug in JavaScript)
typeof Symbol('symbol') // Returns Symbol

What is Hoisting?

• Hoisting is default behavior in JS, where all the variable (Only var) and function declarations
are moved up. It takes place in local and global scope.

x=1;
console.log(x); // Returns 1
var x;
• In order to avoid that, we can “use strict” mode to avoid this.

What is Implicit Type Coercion?

• Automatic conversion of one data type to another data type.


• JS is dynamically typed. It takes place only when two different operand of different data
types are given.
• In a dynamically typed language, the type of a variable is checked during run-time

STRING COERCION

var x = 3;
var y = "3";
var Z = "Hello";
x + y // Returns "33"
x + z // Returns “3Hello”
• Type coercion occurs while using “–“ operator too.

var x = 3;
Var y = "3";
x - y //Returns 0 since the variable y (string type) is converted to a number type

BOOLEAN COERCION
• Boolean coercion takes place when using logical operators, ternary operators, if statements
and loop checks.
• Falsy values are false, 0, 0n, -0,””, undefined, NaN

EQUALITY COERCION

“==” Checks the value but not the type. There is a chance type coercion to occur at one operand.

var a = 12;
var b = "12";
a == b // Returns true because both 'a' and 'b' are converted to the same type and then compared
. Hence the operands are equal.

• “===” Check for both value and type. No type coercion takes place.

var a = 226;
var b = "226";
a === b // Returns false because coercion does not take place and the operands are of different ty
pes. Hence, they are not equal.

What is Logical Operator in JS?

• Unlike other programming languages, Logical AND (&&) and Logical OR (||) returns the one
of the operands not Boolean value
• In OR operator, If the first operand is truthy, then first value is returned. Similarly, if the first
value is falsy. It always returns second operand value.
• In AND operator, if all the values of operands are truthy, then it returns last operand value. If
first operand is falsy then first operand is returned. Similarly, second operand is falsy, then
second operand is returned.

var x = 220;
var y = "Hello";
var z = undefined;
x | | y // Returns 220 since the first value is truthy

x | | z // Returns 220 since the first value is truthy

x && y // Returns "Hello" since both the values are truthy

y && z // Returns undefined since the second value is falsy

if( x && y ){
console.log("Code runs" ); // This block runs because x && y returns "Hello" (Truthy)
}

if( x || z ){
console.log("Code runs"); // This block runs because x || y returns 220(Truthy)
}
What is NaN?

• NaN stands for Not a Number. Type of NaN is Number. It represents value is not valid/legal
number
• isNaN() function is used check whether the provided value is valid/legal number by
converting them to number and then equates to NaN.

Example

isNaN("Hello”) // Returns true


isNaN(345) // Returns false
isNaN(‘1’) // Returns false, since ‘1’ is converted to Number type which results in 0 ( a
number)
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a numb
er)
isNaN(false) // Returns false
isNaN(undefined) // Returns true

What is pass by value?

• Pass by value only happens in Primitive data types like string, number, bigint, boolean,
symbol.

Example:

var y = 234;
var z = y;

• In example, Y is assigned with a value 234, the “=” operator allocates new space in the
memory for value 234 and address or location of value 234 is returned to the variable Y.
• When same variable Y is assigned to variable Z. Here, “=” operator takes the value y(234)
and assigns new space in memory and returns the address back to Z.
• Therefor variable z is not pointing to the location of y. Instead, it is pointing towards new
location in the memory. That’s called Call by value. Changing the variable y will not affect z.

What is pass by reference?

• Pass by Reference happens only in Non-primitive data type like Objects

Example:

var obj = { name: "Vivek", surname: "Bisht" };


var obj2 = obj;
• In example, Obj variable is assigned to obj2. Here instead of passing the value directly to
obj2. It passes the address of obj1 to obj2. So, any changes to obj will affect obj2.
• Because both variable pointing to sample address
What is IIFE(Immediately Invoked Function Expression)?

• Functions runs soon as it is defined.

(function(){
// Do something;
})();

What is Higher Order Function?

• In a programming language, where function is treated as variable like passing it as


arguments, returning it from a function. Manipulating the function etc.
• Map, filter, reduce, sort are some high order functions

What is this Keyword?

• If you’re inside a specific scope or an object or function, this really means whichever object
you’re in.
• This keyword is an object. At the global level, this keyword points to window object provided
by the JavaScript engine. Window === this.
• In a function/object this keyword points to the owner object of the method/function.
• This keyword can be used in objects(methods), functions too.

Example 1:

let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
getFullName: function() {
console.log(`Full name is ${this.name} ${this.lastName}`) //returns Full na
me is Avinash Nallani
}
}

User.getFullName()
** Here this keyword points to owner object “user”.

Example 2:

let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
age: 25,
getFullName: function() {
console.log(`Full name is ${this.name} ${this.lastName}`) //returns Full na
me is Avinash Nallani
}
}
let user1 = {
name: “Jagadeesh”, // property cannot be accessed by any method inside user1
LastName: “M”,
age: 26,
compare: function(user) {
return this.age>user.age? true: false
}
}

User1.compare(user)
** Here this keyword points to owner object “user1”.

Example 3:

var obj = {
name: "vivek",
getName: function(){
console.log(this.name);
}

var getName = obj.getName;

var obj2 = {name:"akshay", getName };


obj2.getName(); // Returns Akshay because getName() method’s owner object is obj2.

Example 4:

var obj1 = {
address : "Mumbai,India",
getAddress: function(){
console.log(this.address);
}
}

var getAddress = obj1.getAddress;


var obj2 = {name:"akshay"};
obj2.getAddress(); // Return error because obj2 doesnot have property of address i
n it.

What is .call()?

• Using .call predefined method, we can do function/method borrowing from an other object
use that function/method with some other object.
• Call() method allows an object to use method/function of an another object.
Example1:

let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
age: 25,
getFullName: function() {
console.log(`Full name is ${this.name} ${this.lastName}`)
}
}

let user1 = {
name: “Jagadeesh”, // property cannot be accessed by any method inside user1
LastName: “M”,
age: 26
}

user.getFullName.call(user1) //Returns Full name is Jagadeesh M

Example2:

let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
age: 25,
}

Let getFullName = function(likings) {


console.log(`Full name is ${this.name} ${this.lastName} likes ${likings}`)
}

let user1 = {
name: “Jagadeesh”, // property cannot be accessed by any method inside user1
LastName: “M”,
age: 26
}

getFullName.call(user1, “Driving”) //Returns Full name is Jagadeesh M like Driving

• We can pass as many arguments as possible to call method.

What is .apply()?

• apply() works as same as .call() method but difference it takes arguments as array.

let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
age: 25,
}
Let getFullName = function(likings) {
console.log(`Full name is ${this.name} ${this.lastName} likes ${likings}`)
}

let user1 = {
name: “Jagadeesh”, // property cannot be accessed by any method inside user1
LastName: “M”,
age: 26
}

getFullName.apply (user1, [“Driving”]) //Returns Full name is Jagadeesh M like Dri


ving

What is bind()?

• Bind method returns a new function and later we can invoke that function to get a desired
result.

Example:

let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
age: 25,
}

Let getFullName = function(likings) {


console.log(`Full name is ${this.name} ${this.lastName} likes ${likings}`)
}

let user1 = {
name: “Jagadeesh”, // property cannot be accessed by any method inside user1
LastName: “M”,
age: 26
}

let fullName = getFullName.bind(user1, “Driving”)


fullName() //Returns Full name is Jagadeesh M like Driving

Working:

• It will take the copy getFullName function and binds it to user1 object and it will return a
function. And that function can be invoked later.

What is currying?

• Currying is nothing but transforming the function that takes multiple arguments into a
series/sequence of function each taking a single argument of its own.
• If we have a function of f(a,b,c), then currying will transform into f(a)(b)(c).
• Using currying, we are not changing the functionality of the function. We are just changing
the way it is invoked.
function add (a) {
return function(b) {
return a + b;
}
}

add(3)(4)

Working

Let add1 = add(3) → returns function(b) { return 3 + b }


Let result = add1(4) → returns 7

What is scope and scope chain?

• Scope represents the accessibility of a particular variables and function in one’s code
• Types Global, local, and block
• Global scope → variable declared in var will have global. It means that variable can accessed
from anywhere inside the code.
• Local/function scope → variable declared in function (let and const) will have local scope.
That can be accessed only in that function. Accessing outside of the function will leads to
reference error
• Block scope → variable that are declared inside {} will have block scope. And can be only
accessed inside the block. Use only let and const. ex: variable i in for loops.
• Scope chain is mechanism in which JavaScript engine uses scope to find the variable. i.e if a
variable is not available in block scope, it checks in the function level scope. If there is no
variable found. It later checks in global scope.

What is closure?

• Closure is technique which is combination of functions that still has access to variable
declared in its outer scope.

Example:

function randomFunc(){
var obj1 = {name:"Vivian", age:45};

return function(){
console.log(obj1.name + " is "+ "awesome"); // Has access to obj1 even when the randomFunc fun
ction is executed
}
}

let initialiseClosure = randomFunc(); // Returns a function

initialiseClosure();
• We can also say that the ability of a function to store a variable for further reference even
after its is executed, is called closure.
Working.

• In above example, randomFunc() is invoked. It knows it should return a function using obj1
in it.
• So instead of destroying the value of obj1 after execution. It saves the value for later/further
reference.
• This is the reason why the returning function is able to use variable declared in the
outerscope even after the function is already executed.

What are Object prototypes?

• All JavaScript inherits properties from a prototype.

Example:

Data object inherits its properties from Date prototype.

Math object inherits its properties from Math prototype.

Array object inherits its properties from Array prototype.

• Prototype is a blueprint of an object. Prototype allows us to use properties and methods of


an objects even if the properties and methods do not exists on the current object.

Example:

var arr = [];


arr.push(2);
console.log(arr); // Outputs [2]

let obj1 = {name: “Avinash”, age: “25”}


delete obj1.age // Deletes the property of age

let new Obj = Object.assign(obj1, {lastname: “Nallani”}) // returns { name: “Avinash”, lastname: “Nall
ani”}

Working:

• In above example, we haven’t defined any property called push, delete, and assign. Js is not
throwing error. Because it inherits these properties from its respective prototype.
• In simple words, whenever a property/method doesn’t exists or found in the current array
or current object. It will look for the method/property in the prototype and utilizes them.

What are callbacks?

• When a function is passed as argument to another function is called callbacks. In JS,


functions are first class citizen. Meaning they can be used as argument to another function.

Example:

function divideByHalf(sum){
console.log(Math.floor(sum / 2));
}
function multiplyBy2(sum){
console.log(sum * 2);
}

function operationOnSum(num1,num2,operation){
var sum = num1 + num2;
operation(sum);
}

operationOnSum(3, 3, divideByHalf); // Outputs 3

operationOnSum(5, 5, multiplyBy2); // Outputs 20

What is memoization?

• Memoization is form of caching where the returned values are stores/cached based on its
parameter in an object.
• Memoization is best suited for compute intense workloads.

Example:

function fib(num, memoization = {}) {


if (num in memoization) return memoization[num]
if (num <= 2) return 1;
memoization[num] = fib(num - 1, memoization) + fib(num - 2, memoization);
return memoization[num];
}

console.log(fib(50))

Working:

• Let’s take an example of getting Fibonacci number for value of 50. If executed normally it
takes more time or even break the server.
• So, in memoization, we are constantly storing every processed data into an object.
• And later we check whether an entry for that is available in memoization. If so then its value
is returned.
• This way we reduce the no of iteration taken by reusing the already computed value.
• Although using memoization saves time. But it leads to large consumption of memory since
we are storing the computed results.

What is recursion?

• Recursion is nothing but ability of a function to call itself repeatedly until it arrives at a
result.
• Important thing to keep in mind while writing recursion is that we should clearly piece out
stopping/end mechanism of iteration.
Example:

function add(number) {
if (number <= 0) {
return 0; // this is the stopping mechanism for the recursive call.
} else {
return number + add (number - 1);
}
}

add(3) => 3 + add(2)


3 + 2 + add(1)
3 + 2 + 1 + add(0)
3+2+1+0=6

What is constructor function in JavaScript?

• Before the introduction of Class in ES6, preferred way was using constructor function.
• Constructor functions are used to create objects in JavaScripts
• When to use constructor function. When we want to create multiple objects having similar
properties but with different values and methods.
• Naming convention of constructor function → Should always written with Pascal
Notation(First Letter capital)

Example:

function Person(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}

var person1 = new Person("Vivek", 76, "male");


console.log(person1);

var person2 = new Person("Courtney", 34, "female");


console.log(person2);

What are Arrow functions?

• Introduced in ES6. It provides new and shorted way to write functions/declaring functions.
• Arrow functions can used as a Function expression.
• If your function has only one statement then no need to use the return keyword and {}.
Arrow function will take care of returning the result.
• If your function has more than one statement, you need to include all the statement under
{} and return is must at the end.
• Arrow function are declared without function keyword.
• If arrow function has only one parameter, then no need to include them around parenthesis
().

Example:

// Traditional function expression


var multiplyBy2 = function(num){
return num * 2;
}
// Arrow function expression
var arrowMultiplyBy2 = num => num * 2;

What is difference between function expression and Arrow function?

• The main difference between function expression and Arrow function are listed below
• Visible syntax differences.
• In Arrow function this keyword always points to the global object i.e., window object.
• Whereas in function expression this keyword points to parent/owner object.

What is difference between var, let and const?

• After ES6, let and const were introduced. Before that we were only using var keyword for
variable declaration.
• Var → global scope, can be re assigned, function scoped, not block scoped
• Let → No global scope, can be re assigned, block scoped.
• Const → no global scope, cannot be re assigned, block scoped.

var c = 15
function test() {
let a = 10;
var b = 11;
const c = 12; // Function scoped so c is 12 even though c is already declared in global scope
console.log(a,b,c) // 10, 11, 12
c = 15 // Cannot assign to 'c' because it is a constant.
{
let x = 9;
console.log(x) // returns 9
var a = 1;
}
console.log(x) // x is not defined.
Console.log(a) // returns 1 bcz var is not block scoped.
}
console.log(b) // b is not defined
console.log(c) // returns 15

test()
What is rest parameter and spread parameter?

• Both were introduced in ES6.


• Both Rest and Spread operator uses “…”
• Rest parameter → using Rest parameter we can convert any number of arguments into an
array. It also helps in extracting some part or all the parts of the arguments.
• Spread operator → It used to spread the object literals and arrays. We can use spread
operator to combine two objects/arrays into single object/array.
• Rest operators are used in Function declarations whereas Spread operator can be used in
function invocation or can be used individually too.
• Rest parameter should be always used at the last of a function.

Example 1: Rest Operator

function extractingArgs(frst, sec, ...rest){ // used in function declarations


console.log(frst, sec, rest); //returns 6, 5, [7, 99]
}

extractingArgs (6, 5, 7, 99);

Example 2: Spread Operator

function add(frst, sec, third, fourth){


return frst+sec+third+fourth; //returns 107
}

Let input = [6,5,7,99]


extractingArgs (…input); // used in function invocation.

Additionally spread operator is used to achieve deep copy for non-primitive data type

Let copyInput = […input] // returns [6,5,7,99]

Let obj1 = {name: “hello”, age: 45}


Let obj2 = {…obj1}

Let obj3 = { lastname: “hi”, isworking: false}

Let finalObj = {…obj1, …obj3} // returns { name: “hello”, age: 45, lastname: “hi”, isworking: false }

What is promises in JS?

• Before ES, Promises are used to handle asynchronous operations in JS.


• Promises is gives you the assurance of data.
• Promises has two callbacks one resolve and reject. Resolve used to resolve the response
from the async call.
• Reject is used in case of any error occurred while performing the async operation.
• Promises has three states. Fulfilled, Pending and Reject.
• We can attach .then and .catch to promise to catch the response and error respectively for a
promise.

What are all methods available in promises?

• Methods available in Promise call are Promise.all, Promise.any, Promise.allSettled,


Promise.race, Promise.reject, Promise.resolve.
• Methods available in promise prototype objects are promises.prototype.catch,
promise.prototype.then, promise.prototype.finally.

What is Promise.all()?

• It helps in making asynchronous calls.


• It takes the iterables of promises as input that resolves to an array of responses.
• This returned promise will resolve when all the input promises have resolved(fulfilled) or if
input iterables contains no promise at all.
• It rejects immediately as soon as it encounters a reject or non-promise error. It does not
care whether or not other promises have resolved or rejected.
• Order of the resolved response is preserved upon the completion of promise.all
• Promise.all displays/rejects with the first rejection message/error.

Example 1:

var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(“foo”);
}, 100);
});

Promise.all([p1, p2, p3]).then(values => {


console.log(values); // [3, 1337, “foo”]
});

• In short, promise.all waits for all promise to get fulfilled. It rejects when it encounters first
reject/error from non-promise and doesn’t care about other promises status.
• If iterables contain non promises inputs, they will be ignored but still counted in returned
promise array value.

var p1 = Promise.all([3,4,5, promise.resolve(6)]);


p1.then((value)=> console.log(value)) // returns [3,4,5,6]

var p2 = Promise.all([3, 4, 5, promise.reject(“Error”)])


p2.catch((error) => console.log(error)) //returns the reject message “Error” only does not care about
other promises results.
var p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('p1_delayed_resolution'), 1000);
});

var p2 = new Promise((resolve, reject) => {


reject(new Error('p2_immediate_rejection'));
});

Promise.all([
p1.catch(error => { return error }),
p2.catch(error => { return error }),
]).then(values => {
console.log(values[0]) // "p1_delayed_resolution"
console.error(values[1]) // "Error: p2_immediate_rejection"
})

What is promise.any()?

• Just as its name says “any”, which means it returns as soon as any one of the iterables gets
fulfilled.
• Accepts iterables of non-promises too
• It rejects with Aggregate Error when none of the iterables was fulfilled.
• It rejects upon receiving empty iterables whereas promise.all won’t reject if passed with
empty iterables.
• It should be used only if the tasks are dependent on each other.

const pErr = new Promise((resolve, reject) => {


reject("Always fails");
});

const pSlow = new Promise((resolve, reject) => {


setTimeout(resolve, 500, "Done eventually");
});

const pFast = new Promise((resolve, reject) => {


setTimeout(resolve, 100, "Done quick");
});

Promise.any([pErr, pSlow, pFast]).then((value) => {


console.log(value);
// pFast fulfills first
})
// expected output: "Done quick"

Promise.any([pErr]).catch ((catch) => {


console.log(catch); // “Aggregate Error” No promise in promise.any was resolved
})
What is promise.race()?

• Just like promise.any, it resolves as soon as one of its promises fulfils. But in promise.race()
reject is also considered.
• Empty iterable to race returns “promise to be forever pending”.
• Accepts iterables of non-promises too.

const promise1 = new Promise((resolve, reject) => {


setTimeout(resolve, 500, 'one');
});

const promise2 = new Promise((resolve, reject) => {


setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then((value) => {


console.log(value);
// Both resolve, but promise2 is faster
});
// expected output: "two"

var foreverPendingPromise = Promise.race([]); // Promise { <status>: “Pending”}

What is Promise.allsettled()?

• Waits until all the promises have been settled (each promise might have resolved or
rejected)
• Takes the input as iterables of promises. Then returns the array of response which describes
the outcomes of each promise. It also takes non promise as iterables too.
• Used only if you have non synchronous tasks that are not dependent on one another to
complete successful.

Example:

const values = await Promise.allSettled([


Promise.resolve(33),
new Promise(resolve => setTimeout(() => resolve(66), 0)),
99,
Promise.reject(new Error('an error'))
])
console.log(values) // [
// {status: "fulfilled", value: 33},
// {status: "fulfilled", value: 66},
// {status: "fulfilled", value: 99},
// {status: "rejected", reason: Error: an error}
// ]
What is temporal dead zone?

• It is behaviour in JS that occurs only in let and const variables.


• Temporal dead zone is nothing but when you try to access the variable before it is initialized.

You might also like