DEV Community

FatimaAlam1234
FatimaAlam1234

Posted on • Updated on

Javascript Interview Questions

Q. What is the way to find the number of parameters expected by a function
You can use function.length syntax to find the number of parameters expected by a function. Let's take an example of sum function to calculate the sum of numbers,

function sum(num1, num2, num3, num4) {
  return num1 + num2 + num3 + num4;
}
sum.length; // 4 is the number of parameters expected.

Q. Difference with new keyword ->

Image description

It doesn't create a new context rather just overwrites and so now every object of type user has same values. That is why new keyword is necessary.

Q. Can I use reserved words as identifiers
No, you cannot use the reserved words as variables, labels, object or function names. Let's see one simple example,

var else = "hello"; // Uncaught SyntaxError: Unexpected token else

Important
Q. Why to avoid creating objects of primitives in JavaScript?

JavaScript has both primitive and object versions of strings, numbers, and booleans. There's almost never any reason to create the object version of any of them explicitly, and doing so can indeed lead to confusion; see inline comments:

var s1, s2, n1, n2;

// These are false because with ===, an object is never equal to a non-object
s1 = new String("hi");
s2 = "hi";
console.log(s1 === s2); // false
n1 = new Number(42);
n2 = 42;
console.log(n1 === n2); // also false

// These are false because even with ==, two *different* objects are never equal
// (even if they're equivalent)
s1 = new String("what the...");
s2 = new String("what the...");
console.log(s1 == s2);  // also false
n1 = new Number(42);
n2 = new Number(42);
console.log(n1 == n2);  // also false

eval()eval()

Q. What are the recommendations to create new object
It is recommended to avoid creating new objects using new Object(). Instead you can initialize values based on it's type to create the objects.

eval()

console.log(eval('2 + 2'));
// Expected output: 4

console.log(eval(new String('2 + 2')));
// Expected output: 2 + 2

console.log(eval('2 + 2') === eval('4'));
// Expected output: true

console.log(eval('2 + 2') === eval(new String('2 + 2')));
// Expected output: false

Q. Is it recommended to use eval
No, it allows arbitrary code to be run which causes a security problem. As we know that the eval() function is used to run text as code. In most of the cases, it should not be necessary to use it.

Q. What are regular expression patterns
Regular Expressions provide a group of patterns in order to match characters. Basically they are categorized into 3 types,

Brackets: These are used to find a range of characters. For example, below are some use cases,
[abc]: Used to find any of the characters between the brackets(a,b,c)
[0-9]: Used to find any of the digits between the brackets
(a|b): Used to find any of the alternatives separated with |
Metacharacters: These are characters with a special meaning For example, below are some use cases,
\d: Used to find a digit
\s: Used to find a whitespace character
\b: Used to find a match at the beginning or ending of a word
Quantifiers: These are useful to define quantities For example, below are some use cases,
n+: Used to find matches for any string that contains at least one n
n*: Used to find matches for any string that contains zero or more occurrences of n
n?: Used to find matches for any string that contains zero or one occurrences of n

Q. Is javascript a statically typed or a dynamically typed language?

JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to a statically typed language, where the type of a variable is checked during compile-time.

Image description

Q. What are js labels
The label statement allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later. For example, the below code with labels avoids printing the numbers when they are same,

ar i, j;

loop1: for (i = 0; i < 3; i++) {
  loop2: for (j = 0; j < 3; j++) {
    if (i === j) {
      continue loop1;
    }
    console.log("i = " + i + ", j = " + j);
  }
}

Q2. What is NaN property in JavaScript?

NaN property represents the “Not-a-Number” value. It indicates a value that is not a legal number.

typeof of NaN will return a Number.

To check if a value is NaN, we use the isNaN() function,

Note- isNaN() function converts the given value to a Number type, and then equates to NaN.
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 number)
isNaN(false) // Returns false
isNaN(undefined) // Returns true

Q3. 9. Explain passed by value and passed by reference.

var x = 2;

Image description

var y = 234;
var z = y;
var y = #8454; // y pointing to address of the value 234

var z = y; 

var z = #5411; // z pointing to a completely new address of the value 234

// Changing the value of y
y = 23;
console.log(z);  // Returns 234, since z points to a new address in the memory so changes in y will not effect z

Image description

var obj = { name: "Vivek", surname: "Bisht" };
var obj2 = obj;
var obj = #8711;  // obj pointing to address of { name: "Vivek", surname: "Bisht" }
var obj2 = obj;

var obj2 = #8711; // obj2 pointing to the same address 

// changing the value of obj1

obj.name = "Akki";
console.log(obj2);
  1. What is an Immediately Invoked Function in JavaScript? An Immediately Invoked Function ( known as IIFE and pronounced as IIFY) is a function that runs as soon as it is defined.

Syntax of IIFE :

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

The first set of parenthesis:
While executing javascript code, whenever the compiler sees the word “function”, it assumes that we are declaring a function in the code. Therefore, if we do not use the first set of parentheses, the compiler throws an error because it thinks we are declaring a function, and by the syntax of declaring a function, a function should always have a name.

function() {
  //Do something;
}
// Compiler gives an error since the syntax of declaring a function is wrong in the code above.

To remove this error, we add the first set of parenthesis that tells the compiler that the function is not a function declaration, instead, it’s a function expression.

The second set of parenthesis:

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

From the definition of an IIFE, we know that our code should run as soon as it is defined. A function runs only when it is invoked. If we do not invoke the function, the function declaration is returned:

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

// Returns the function declaration

Therefore to invoke the function, we use the second set of parenthesis.

  1. What do you mean by strict mode in javascript and characteristics of javascript strict-mode?
    Characteristics of strict mode in javascript

    Duplicate arguments are not allowed by developers.
    In strict mode, you won't be able to use the JavaScript keyword as a parameter or function name.
    The 'use strict' keyword is used to define strict mode at the start of the script. Strict mode is supported by all browsers.
    Engineers will not be allowed to create global variables in 'Strict Mode.

Explain Higher Order Functions in javascript.

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.

Higher-order functions are a result of functions being first-class citizens in javascript.
Examples of higher-order functions:


function higherOrder(fn) {
  fn();
}

higherOrder(function() { console.log("Hello world") });  
function higherOrder2() {
  return function() {
    return "Do something";
  }
}      
var x = higherOrder2();
x()   // Returns "Do something"
  1. Explain “this” keyword. The “this” keyword refers to the object that the function is a property of.

The value of the “this” keyword will always depend on the object that is invoking the function.\

Confused? Let’s understand the above statements by examples:

function doSomething() {
  console.log(this);
}

doSomething();

What do you think the output of the above code will be?

Note - Observe the line where we are invoking the function.

Check the definition again:

The “this” keyword refers to the object that the function is a property of.

In the above code, the function is a property of which object?

Since the function is invoked in the global context, the function is a property of the global object.

Therefore, the output of the above code will be the global object. Since we ran the above code inside the browser, the global object is the window object.
Example 2:

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

obj.getName();

In the above code, at the time of invocation, the getName function is a property of the object obj , therefore, this keyword will refer to the object obj, and hence the output will be “vivek”.

Example 3:

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

}

var getName = obj.getName;

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

Can you guess the output here?

The output will be “akshay”.

Although the getName function is declared inside the object obj, at the time of invocation, getName() is a property of obj2, therefore the “this” keyword will refer to obj2.

The silly way to understand the “this” keyword is, whenever the function is invoked, check the object before the dot. The value of this . keyword will always be the object before the dot.

If there is no object before the dot-like in example1, the value of this keyword will be the global object.

Example 4:

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

var getAddress = obj1.getAddress;
var obj2 = {name:"akshay"};
obj2.getAddress();

Can you guess the output?

The output will be an error.

Although in the code above, this keyword refers to the object obj2, obj2 does not have the property “address”‘, hence the getAddress function throws an error.

  1. What do you mean by Self Invoking Functions?

Without being requested, a self-invoking expression is automatically invoked (initiated). If a function expression is followed by (), it will execute automatically. A function declaration cannot be invoked by itself.

Normally, we declare a function and call it, however, anonymous functions may be used to run a function automatically when it is described and will not be called again. And there is no name for these kinds of functions.

  1. Explain call(), apply() and, bind() methods.

  2. call():

    It’s a predefined method in javascript.
    This method invokes a method (function) by specifying the owner object.
    Example 1:

function sayHello(){
return "Hello " + this.name;
}

var obj = {name: "Sandy"};

sayHello.call(obj);

// Returns "Hello Sandy"

call() method allows an object to use the method (function) of another object.
Example 2:

var person = {
age: 23,
getAge: function(){
return this.age;
}
}

var person2 = {age: 54};
person.getAge.call(person2);

// Returns 54

call() accepts arguments:

function saySomething(message){
return this.name + " is " + message;
}

var person4 = {name: "John"};

saySomething.call(person4, "awesome");
// Returns "John is awesome"

apply()

The apply method is similar to the call() method. The only difference is that,

call() method takes arguments separately whereas, apply() method takes arguments as an array.

function saySomething(message){
return this.name + " is " + message;
}

var person4 = {name: "John"};
saySomething.apply(person4, ["awesome"]);

  1. bind():

    This method returns a new function, where the value of “this” keyword will be bound to the owner object, which is provided as a parameter.
    Example with arguments:

var bikeDetails = {
displayDetails: function(registrationNumber,brandName){
return this.name+ " , "+ "bike details: "+ registrationNumber + " , " + brandName;
}
}

var person1 = {name: "Vivek"};

var detailsOfPerson1 = bikeDetails.displayDetails.bind(person1, "TS0122", "Bullet");

// Binds the displayDetails function to the person1 object

detailsOfPerson1();
//Returns Vivek, bike details: TS0122, Bullet

So, the difference between all is call and apply are similar with the difference of how the arguments are sent with the arguments being sent as it is and being sent as an artray in call() and apply() respectively.
And bind() basically returns a new function so it can be stored as a new function and so is not immediately called as call() and apply() but rather assigned like a variable.

  1. What is the difference between exec () and test () methods in javascript?

    test () and exec () are RegExp expression methods used in javascript.
    We'll use exec () to search a string for a specific pattern, and if it finds it, it'll return the pattern directly; else, it'll return an 'empty' result.
    We will use a test () to find a string for a specific pattern. It will return the Boolean value 'true' on finding the given text otherwise, it will return 'false'.

  2. What is currying in JavaScript?

Currying is an advanced technique to transform a function of arguments n, to n functions of one or fewer arguments.

Example of a curried function:

function add (a) {
return function(b){
return a + b;
}
}

add(3)(4)

For Example, if we have a function f(a,b), then the function after currying, will be transformed to f(a)(b).

By using the currying technique, we do not change the functionality of a function, we just change the way it is invoked.

Let’s see currying in action:

function multiply(a,b){
return a*b;
}

function currying(fn){
return function(a){
return function(b){
return fn(a,b);
}
}
}

var curriedMultiply = currying(multiply);

multiply(4, 3); // Returns 12

curriedMultiply(4)(3); // Also returns 12

As one can see in the code above, we have transformed the function multiply(a,b) to a function curriedMultiply , which takes in one parameter at a time.

  1. Explain Scope and Scope Chain in javascript.

Scope in JS determines the accessibility of variables and functions at various parts of one’s code.

In general terms, the scope will let us know at a given part of code, what are variables and functions we can or cannot access.

There are three types of scopes in JS:

Global Scope
Local or Function Scope
Block Scope

Global Scope: Variables or functions declared in the global namespace have global scope, which means all the variables and functions having global scope can be accessed from anywhere inside the code.

var globalVariable = "Hello world";

function sendMessage(){
return globalVariable; // can access globalVariable since it's written in global space
}
function sendMessage2(){
return sendMessage(); // Can access sendMessage function since it's written in global space
}
sendMessage2(); // Returns “Hello world”

Function Scope: Any variables or functions declared inside a function have local/function scope, which means that all the variables and functions declared inside a function, can be accessed from within the function and not outside of it.

function awesomeFunction(){
var a = 2;

var multiplyBy2 = function(){
console.log(a*2); // Can access variable "a" since a and multiplyBy2 both are written inside the same function
}
}
console.log(a); // Throws reference error since a is written in local scope and cannot be accessed outside

multiplyBy2(); // Throws reference error since multiplyBy2 is written in local scope

Block Scope: Block scope is related to the variables declared using let and const. Variables declared with var do not have block scope. Block scope tells us that any variable declared inside a block { }, can be accessed only inside that block and cannot be accessed outside of it.

{
let x = 45;
}

console.log(x); // Gives reference error since x cannot be accessed outside of the block

for(let i=0; i<2; i++){
// do something
}

console.log(i); // Gives reference error since i cannot be accessed outside of the for loop block

Scope Chain: JavaScript engine also uses Scope to find variables. Let’s understand that using an example:

var y = 24;

function favFunction(){
var x = 667;
var anotherFavFunction = function(){
console.log(x); // Does not find x inside anotherFavFunction, so looks for variable inside favFunction, outputs 667
}

var yetAnotherFavFunction = function(){
console.log(y); // Does not find y inside yetAnotherFavFunction, so looks for variable inside favFunction and does not find it, so looks for variable in global scope, finds it and outputs 24
}

anotherFavFunction();
yetAnotherFavFunction();
}
favFunction();

As you can see in the code above, if the javascript engine does not find the variable in local scope, it tries to check for the variable in the outer scope. If the variable does not exist in the outer scope, it tries to find the variable in the global scope.

If the variable is not found in the global space as well, a reference error is thrown.

  1. Explain Closures in JavaScript.

Closures are an ability of a function to remember the variables and functions that are declared in its outer scope.

var Person = function(pName){
var name = pName;

this.getName = function(){
return name;
}
}

var person = new Person("Neelesh");
console.log(person.getName());

Let’s understand closures by 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 function is executed

}
}

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

initialiseClosure();

Let’s understand the code above,

The function randomFunc() gets executed and returns a function when we assign it to a variable:

var initialiseClosure = randomFunc();

The returned function is then executed when we invoke initialiseClosure:

initialiseClosure();

The line of code above outputs “Vivian is awesome” and this is possible because of closure.

console.log(obj1.name + " is "+ "awesome");

When the function randomFunc() runs, it seems that the returning function is using the variable obj1 inside it:

Therefore randomFunc(), instead of destroying the value of obj1 after execution, saves the value in the memory for further reference. This is the reason why the returning function is able to use the variable declared in the outer scope even after the function is already executed.

This ability of a function to store a variable for further reference even after it is executed is called Closure.

  1. What are object prototypes?

All javascript objects inherit properties from a prototype. For example,

Date objects inherit properties from the Date prototype
Math objects inherit properties from the Math prototype
Array objects inherit properties from the Array prototype.
On top of the chain is Object.prototype. Every prototype inherits properties and methods from the Object.prototype.
A prototype is a blueprint of an object. The prototype allows us to use properties and methods on an object even if the properties and methods do not exist on the current object.

Let’s see prototypes help us use methods and properties:

var arr = [];
arr.push(2);

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

In the code above, as one can see, we have not defined any property or method called push on the array “arr” but the javascript engine does not throw an error.

The reason is the use of prototypes. As we discussed before, Array objects inherit properties from the Array prototype.

The javascript engine sees that the method push does not exist on the current array object and therefore, looks for the method push inside the Array prototype and it finds the method.

Whenever the property or method is not found on the current object, the javascript engine will always try to look in its prototype and if it still does not exist, it looks inside the prototype's prototype and so on.

  1. What are callbacks?

A callback is a function that will be executed after another function gets executed. In javascript, functions are treated as first-class citizens, they can be used as an argument of another function, can be returned by another function, and can be used as a property of an object.

Functions that are used as an argument to another function are called callback functions. 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

Difference between Arrow and Normal Functions:

var obj1 = {
  valueOfThis: function(){
    return this;
  }
}
var obj2 = {
  valueOfThis: ()=>{
    return this;
  }
}

obj1.valueOfThis(); // Will return the object obj1
obj2.valueOfThis(); // Will return window/global object

Differences between declaring variables using var, let and const.

Before the ES6 version of javascript, only the keyword var was used to declare variables. With the ES6 Version, keywords let and const were introduced to declare variables.
keyword const let var
global scope no no yes
function scope yes yes yes
block scope yes yes no
can be reassigned no yes yes

Let’s understand the differences with examples:

var variable1 = 23;

let variable2 = 89;

function catchValues(){
console.log(variable1);
console.log(variable2);

// Both the variables can be accessed anywhere since they are declared in the global scope
}

window.variable1; // Returns the value 23

window.variable2; // Returns undefined

The variables declared with the let keyword in the global scope behave just like the variable declared with the var keyword in the global scope.
Variables declared in the global scope with var and let keywords can be accessed from anywhere in the code.
But, there is one difference! Variables that are declared with the var keyword in the global scope are added to the window/global object. Therefore, they can be accessed using window.variableName.
Whereas, the variables declared with the let keyword are not added to the global object, therefore, trying to access such variables using window.variableName results in an error.

var vs let in functional scope

function varVsLetFunction(){
let awesomeCar1 = "Audi";
var awesomeCar2 = "Mercedes";
}

console.log(awesomeCar1); // Throws an error
console.log(awesomeCar2); // Throws an error

Variables are declared in a functional/local scope using var and let keywords behave exactly the same, meaning, they cannot be accessed from outside of the scope.

{
var variable3 = [1, 2, 3, 4];
}

console.log(variable3); // Outputs [1,2,3,4]

{
let variable4 = [6, 55, -1, 2];
}

console.log(variable4); // Throws error

for(let i = 0; i < 2; i++){
//Do something
}

console.log(i); // Throws error

for(var j = 0; j < 2; i++){
// Do something
}

console.log(j) // Outputs 2

In javascript, a block means the code written inside the curly braces {}.
Variables declared with var keyword do not have block scope. It means a variable declared in block scope {} with the var keyword is the same as declaring the variable in the global scope.
Variables declared with let keyword inside the block scope cannot be accessed from outside of the block.

Const keyword

Variables with the const keyword behave exactly like a variable declared with the let keyword with only one difference, any variable declared with the const keyword cannot be reassigned.
Example:

const x = {name:"Vivek"};

x = {address: "India"}; // Throws an error

x.name = "Nikhil"; // No error is thrown

const y = 23;

y = 44; // Throws an error

In the code above, although we can change the value of a property inside the variable declared with const keyword, we cannot completely reassign the variable itself.

Actual representation of Promise, resolve and reject

In the function below, we are returning a promise inside a function:

function sumOfThreeElements(...elements){
  return new Promise((resolve,reject)=>{
    if(elements.length > 3 ){
      reject("Only three elements or less are allowed");
    }
    else{
      let sum = 0;
      let i = 0;
      while(i < elements.length){
        sum += elements[i];
        i++;
      }
      resolve("Sum has been calculated: "+sum);
    }
  })
}
  1. Explain WeakSet in javascript.

In javascript, a Set is a collection of unique and ordered elements. Just like Set, WeakSet is also a collection of unique and ordered elements with some key differences:

Weakset contains only objects and no other type.
An object inside the weakset is referenced weakly. This means, that if the object inside the weakset does not have a reference, it will be garbage collected.
Unlike Set, WeakSet only has three methods, add() , delete() and has() .
const newSet = new Set([4, 5, 6, 7]);
console.log(newSet);// Outputs Set {4,5,6,7}

const newSet2 = new WeakSet([3, 4, 5]); //Throws an error


let obj1 = {message:"Hello world"};
const newSet3 = new WeakSet([obj1]);
console.log(newSet3.has(obj1)); // true

Why do we use callbacks?

A callback function is a method that is sent as an input to another function (now let us name this other function "thisFunction"), and it is performed inside the thisFunction after the function has completed execution.

JavaScript is a scripting language that is based on events. Instead of waiting for a reply before continuing, JavaScript will continue to run while monitoring for additional events. Callbacks are a technique of ensuring that a particular code does not run until another code has completed its execution.

  1. Explain WeakMap in javascript.

In javascript, Map is used to store key-value pairs. The key-value pairs can be of both primitive and non-primitive types. WeakMap is similar to Map with key differences:

The keys and values in weakmap should always be an object.
If there are no references to the object, the object will be garbage collected.

const map1 = new Map();
map1.set('Value', 1);

const map2 = new WeakMap();
map2.set('Value', 2.3); // Throws an error

let obj = {name:"Vivek"};
const map3 = new WeakMap();
map3.set(obj, {age:23});

  1. What is Object Destructuring?

Object destructuring is a new way to extract elements from an object or an array.

Object destructuring: Before ES6 version:

const classDetails = {
strength: 78,
benches: 39,
blackBoard:1
}

const classStrength = classDetails.strength;
const classBenches = classDetails.benches;
const classBlackBoard = classDetails.blackBoard;

The same example using object destructuring:

const classDetails = {
strength: 78,
benches: 39,
blackBoard:1
}

const {strength:classStrength, benches:classBenches,blackBoard:classBlackBoard} = classDetails;

console.log(classStrength); // Outputs 78
console.log(classBenches); // Outputs 39
console.log(classBlackBoard); // Outputs 1

As one can see, using object destructuring we have extracted all the elements inside an object in one line of code. If we want our new variable to have the same name as the property of an object we can remove the colon:

const {strength:strength} = classDetails;
// The above line of code can be written as:
const {strength} = classDetails;

Array destructuring: Before ES6 version:

const arr = [1, 2, 3, 4];
const first = arr[0];
const second = arr[1];
const third = arr[2];
const fourth = arr[3];

The same example using object destructuring:

const arr = [1, 2, 3, 4];
const [first,second,third,fourth] = arr;
console.log(first); // Outputs 1
console.log(second); // Outputs 2
console.log(third); // Outputs 3
console.log(fourth); // Outputs 4

Notice how we are using {} while destructuring an object and [] while destructuring an array. That's how we know that to destructure a data structure in javascript we need to have a similar structure in the LHS or in the assigned side.

  1. What is event bubbling
    Event bubbling is a type of event propagation where the event first triggers on the innermost
    target element, and then successively triggers on the ancestors (parents) of the target element in
    the same nesting hierarchy till it reaches the outermost DOM element.

  2. What is event capturing
    Event capturing is a type of event propagation where the event is first captured by the outermost
    element, and then successively triggers on the descendants (children) of the target element in
    the same nesting hierarchy till it reaches the innermost DOM element.

How do you submit a form using JavaScript
You can submit a form using JavaScript use document.form[0].submit(). All the form input's
information is submitted using onsubmit event handler
function submit() {
document.form[0].submit();
}

Question 2. For which value of x the results of the following statements are not the same?

if( x <= 100 ) {...}
if( !(x > 100) ) {...}

Answer

NaN <= 100 is false and NaN > 100 is also false, so if the value of x is NaN, the statements are not the same.

The same holds true for any value of x that being converted to type Number, returns NaN, e.g.: undefined, [1,2,5], {a:22} , etc.

This is why you need to pay attention when you deal with numeric variables. NaN can’t be equal, less than or more than any other numeric value, so the only reliable way to check if the value is NaN, is to use the isNaN() function.

Question 5. Write a mul function which will work properly when invoked with following syntax.

console.log(mul(2)(3)(4)); // output : 24
console.log(mul(4)(3)(4)); // output : 48

Answer

function mul (x) {
return function (y) { // anonymous function
return function (z) { // anonymous function
return x * y * z;
};
};
}

Question 6. How to empty an array in JavaScript?

For instance:

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f'];

How can we empty the array above?
Answer

There are a couple of ways by which we can empty an array, So let's discuss all the possible way by which we can empty an array.
Method 1

arrayList = [];

The code above will set the variable arrayList to a new empty array. This is recommended if you don't have references to the original array arrayList anywhere else because It will actually create a new empty array. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged, Only use this way if you have only referenced the array by its original variable arrayList.

For instance:

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by another variable
arrayList = []; // Empty the array
console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f']

Method 2

arrayList.length = 0;

The code above will clear the existing array by setting its length to 0. This way of emptying an array will also update all the reference variables that point to the original array.

For instance:

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by another variable
arrayList.length = 0; // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []

Method 3

arrayList.splice(0, arrayList.length);

Above implementation will also work perfectly. This way of empty the array will also update all the references of the original array.

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by another variable
arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []

Method 4

while(arrayList.length) {
arrayList.pop();
}

Above implementation can also empty the array. But not recommended to use often.

Question 21. Calculate the length of the associative array

var counterArray = {
A : 3,
B : 4
};
counterArray["C"] = 1;

Answer

First of all, in the case of JavaScript an associative array is the same as an object. Secondly, even though there is no built-in function or property available to calculate the length/size an object, we can write such function ourselves.
Method 1

Object has keys method which can be used to calculate the length of object.

Object.keys(counterArray).length; // Output 3

Method 2

We can also calculate the length of object by iterating through the object and by doing a count of own property of object. This way we will ignoge the properties that came from the object's prototype chain:

function getLength(object) {
var count = 0;
for(key in object) {
// hasOwnProperty method check own property of object
if(object.hasOwnProperty(key)) count++;
}
return count;
}

Method 3

All modern browsers (including IE9+) support the getOwnPropertyNames method, so we can calculate the length using the following code:

Object.getOwnPropertyNames(counterArray).length; // Output 3

Method 4

Underscore and lodash libraries have the method size dedicated to calculate the object length. We don't recommend to include one of these libraries just to use the size method, but if it's already used in your project - why not?

_.size({one: 1, two: 2, three: 3});
=> 3

Question 22. Difference between Function, Method and Constructor calls in JavaScript.
Answer

If your are familiar with Object-oriented programming, More likely familiar to thinking of functions, methods, and class constructors as three separate things. But In JavaScript, these are just three different usage patterns of one single construct.

functions : The simplest usages of function call:

function helloWorld(name) {
return "hello world, " + name;
}

helloWorld("JS Geeks"); // "hello world JS Geeks"

Methods in JavaScript are nothing more than object properties that are functions.

var obj = {
helloWorld : function() {
return "hello world, " + this.name;
},
name: 'John Carter'
}
obj.helloWorld(); // // "hello world John Carter"

Notice how helloWorld refer to this properties of obj. Here it's clear or you might have already understood that this gets bound to obj. But the interesting point that we can copy a reference to the same function helloWorld in another object and get a difference answer. Let see:

var obj2 = {
helloWorld : obj.helloWorld,
name: 'John Doe'
}
obj2.helloWorld(); // "hello world John Doe"

You might be wonder what exactly happens in a method call here. Here we call the expression itself determine the binding of this this, The expression obj2.helloWorld() looks up the helloWorld property of obj and calls it with receiver object obj2.

The third use of functions is as constructors. Like function and method, constructors are defined with function.

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

var emp1 = new Employee('John Doe', 28);
emp1.name; // "John Doe"
emp1.age; // 28

Unlike function calls and method calls, a constructor call new Employee('John Doe', 28) creates a brand new object and passes it as the value of this, and implicitly returns the new object as its result.

The primary role of the constructor function is to initialize the object.

Question 29. Write a function called deepClone which takes an object and creates a object copy of it.

var newObject = deepClone(obj);

Answer

function deepClone(object){
var newObject = {};
for(var key in object){
if(typeof object[key] === 'object' && object[key] !== null ){
newObject[key] = deepClone(object[key]);
}else{
newObject[key] = object[key];
}
}
return newObject;
}

Question 31. Write a function called Clone which takes an object and creates a object copy of it but not copy deep property of object.

var objectLit = {foo : 'Bar'};
var cloneObj = Clone(obj); // Clone is the function which you have to write
console.log(cloneObj === Clone(objectLit)); // this should return false
console.log(cloneObj == Clone(objectLit)); // this should return true

Answer

function Clone(object){
var newObject = {};
for(var key in object){
newObject[key] = object[key];
}
return newObject;
}

Question 33. How to check whether a key exist in a JavaScript object or not.
Answer

Let say we have person object with property name and age

var person = {
name: 'Nishant',
age: 24
}

Now we want to check whether name property exist in person object or not ?

In JavaScript object can have own property, in above example name and age is own property of person object. Object also have some of inherited property of base object like toString is inherited property of person object.

So how we will check whether property is own property or inherited property.

Method 1: We can use in operator on objet to check own property or inherited property.

console.log('name' in person); // checking own property print true
console.log('salary' in person); // checking undefined property print false

in operator also look into inherited property if it doesn't find property defined as own property. For instance If I check existence of toString property as we know that we haven't declared this property on person object so in operator look into there base property.

Here

console.log('toString' in person); // Will print true

If we want to test property of object instance not inherited properties then we will use hasOwnProperty method of object instance.

console.log(person.hasOwnProperty('toString')); // print false
console.log(person.hasOwnProperty('name')); // print true
console.log(person.hasOwnProperty('salary')); // print false

Question 34. What is NaN, why do we need it, and when can it break the page?
Answer

NaN stands for “not a number.” and it can break your table of numbers when it has an arithmetic operation that is not allowed. Here are some examples of how you can get NaN:

Math.sqrt(-5);
Math.log(-1);
parseFloat("foo"); /* this is common: you get JSON from the server, convert some strings from JSON to a number and end up with NaN in your UI. */

NaN is not equal to any number, it’s not less or more than any number, also it's not equal to itself:

NaN !== NaN
NaN < 2 // false
NaN > 2 // false
NaN === 2 // false

To check if the current value of the variable is NaN, you have to use the isNaN function. This is why we can often see NaN in the webpages: it requires special check which a lot of developers forget to do.

Question 35. Fix the bug using ES5 only

var arr = [10, 32, 65, 2];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log('The index of this number is: ' + i);
}, 3000);
}

Answer

For ES6, you can just replace var i with let i.

For ES5, you need to create a function scope like here:

var arr = [10, 32, 65, 2];
for (var i = 0; i < arr.length; i++) {
setTimeout(function(j) {
return function () {
console.log('The index of this number is: ' + j)
};
}(i), 3000);
}

This can also achieve by forEach (allows you to keep that variable within the forEach’s scope)

var arr = [10, 32, 65, 2];
arr.forEach(function(ele, i) {
setTimeout(function() {
console.log('The index of this number is: ' + i);
}, 3000);
})

Question 36. How to check if the value of a variable in an array?
Answer

We always encounter in such situation where we need to know whether value is type of array or not.

For instance : the code below perform some operation based value type

function(value){
if("value is an array"){
// Then perform some operation
}else{
// otherwise
}
}

Let's discuss some way to detect an array in JavaScript.

Method 1:

Juriy Zaytsev (Also known as kangax) proposed an elegant solution to this.

function isArray(value){
    return Object.prototype.toString.call(value) === '[object Array]';
}

This approach is most popular way to detecting a value of type array in JavaScript and recommended to use. This approach relies on the fact that, native toString() method on a given value produce a standard string in all browser.

Method 2:

Duck typing test for array type detection

// Duck typing arrays
function isArray(value){
return typeof value.sort === 'function';
}

As we can see above isArray method will return true if value object have sort method of type function. Now assume you have created a object with sort method

var bar = {
    sort: function(){
        // Some code 
    }
}

Now when you check isArray(bar) then it will return true because bar object has sort method, But the fact is bar is not an array.

So this method is not a best way to detect an array as you can see it's not handle the case when some object has sort method.

Method 3:

ECMAScript 5 has introduced Array.isArray() method to detect an array type value. The sole purpose of this method is accurately detecting whether a value is an array or not.

In many JavaScript libraries you may see the code below for detecting an value of type array.

function(value){
// ECMAScript 5 feature
if(typeof Array.isArray === 'function'){
return Array.isArray(value);
}else{
return Object.prototype.toString.call(value) === '[object Array]';
}
}

Method 4:

You can query the constructor name:

function isArray(value) {
return value.constructor.name === "Array";
}

Method 5:

You check if a given value is an instanceof Array:

function isArray(value) {
return value instanceof Array;
}

Question 37. Best way to detect reference values of any type in JavaScript ?
Answer

In Javascript Object are called as reference type, Any value other then primitive is definitely a reference type. There are several built-in reference type such as Object, Array, Function, Date, null and Error.

Detecting object using typeof operator

console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof new Array()); // object
console.log(typeof null); // object
console.log(typeof new RegExp()); // object
console.log(typeof new Date()); // object

But the downside of using typeof operator to detect an object is that typeof returns object for null (However this is fact that null is an object in JavaScript).

The best way to detect an object of specific reference type using instanceof operator.

NOTE
In addition to this Object.create() method also allows to specify a second argument which is an object containing additional properties and methods to add to the new object.

For example

var emp1 = Object.create(employee, {
name: {
value: "John"
}
});

emp1.displayName(); // "John"
employee.displayName(); // "Nishant"

Question 40. How we can prevent modification of object in JavaScript ?.
Answer

ECMAScript 5 introduce several methods to prevent modification of object which lock down object to ensure that no one, accidentally or otherwise, change functionality of Object.

There are three levels of preventing modification:

1: Prevent extensions :

No new properties or methods can be added to the object, but one can change the existing properties and method.

For example:

var employee = {
name: "Nishant"
};

// lock the object
Object.preventExtensions(employee);

// Now try to change the employee object property name
employee.name = "John"; // work fine

//Now try to add some new property to the object
employee.age = 24; // fails silently unless it's inside the strict mode

2: Seal :

It is same as prevent extension, in addition to this also prevent existing properties and methods from being deleted.

To seal an object, we use Object.seal() method. you can check whether an object is sealed or not using Object.isSealed();

var employee = {
name: "Nishant"
};

// Seal the object
Object.seal(employee);

console.log(Object.isExtensible(employee)); // false
console.log(Object.isSealed(employee)); // true

delete employee.name // fails silently unless it's in strict mode

// Trying to add new property will give an error
employee.age = 30; // fails silently unless in strict mode

when an object is sealed, its existing properties and methods can't be removed. Sealed object are also non-extensible.

3: Freeze :

Same as seal, In addition to this prevent existing properties methods from being modified (All properties and methods are read only).

To freeze an object, use Object.freeze() method. We can also determine whether an object is frozen using Object.isFrozen();

var employee = {
name: "Nishant"
};

//Freeze the object
Object.freeze(employee);

// Seal the object
Object.seal(employee);

console.log(Object.isExtensible(employee)); // false
console.log(Object.isSealed(employee)); // true
console.log(Object.isFrozen(employee)); // true

employee.name = "xyz"; // fails silently unless in strict mode
employee.age = 30; // fails silently unless in strict mode
delete employee.name // fails silently unless it's in strict mode

Frozen objects are considered both non-extensible and sealed.

Recommended:

If you are decided to prevent modification, sealed, freeze the object then use in strict mode so that you can catch the error.

For example:

"use strict";

var employee = {
name: "Nishant"
};

//Freeze the object
Object.freeze(employee);

// Seal the object
Object.seal(employee);

console.log(Object.isExtensible(employee)); // false
console.log(Object.isSealed(employee)); // true
console.log(Object.isFrozen(employee)); // true

employee.name = "xyz"; // fails silently unless in strict mode
employee.age = 30; // fails silently unless in strict mode
delete employee.name; // fails silently unless it's in strict mode

// Destructing Assignment
const { title, price, description } = {
title: "iPhone",
price: 999,
description: "The iPhone is a smartphone developed by Apple"
};

console.log(title); // iPhone
console.log(price); // 999
console.log(description); // The iPhone is a smartphone developed by Apple

The names title, price, description actually maps to the keys of the object and so no other names on the LHS would help.

Example: Declaring global variable within function

window.value = 90;

// Declaring global variable by window object
function setValue() {
window.value = 100;
}

// Accessing global variable from other function
function getValue() {
setValue();
return window.value;
}

console.log(getValue()); // 100

What is the difference between == and === operators?

JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators takes type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,

Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal. i.e, Having the same number value. There are two special cases in this,
    NaN is not equal to anything, including NaN.
    Positive and negative zeros are equal to one another.
Two Boolean operands are strictly equal if both are true or both are false.
Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are not equal with ===, but equal with ==. i.e, null===undefined --> false but null==undefined --> true

When to use Function Expressions & Declarations
There are a few key differences between function expressions and function declarations:

Function declarations are hoisted, while function expressions are not. This means that you can call a function declaration before it is defined, but you cannot do this with a function expression.
With function expressions, you can use a function immediately after it is defined. With function declarations, you have to wait until the entire script has been parsed.
Function expressions can be used as an argument to another function, but function declarations cannot.
Function expressions can be anonymous, while function declarations cannot.

What is Function binding?
Function binding ( .bind() ) is a method on the prototype of all functions in JavaScript. It allows to create a new function from an existing function, change the new function's this context, and provide any arguments you want the new function to be called with. The arguments provided to bind will precede any arguments that are passed to the new function when it is called.

Example:

// Function Binding
const person = {
firstName: "Nirupama",
lastName: "Randhawa",
getName: function () {
return this.firstName + " " + this.lastName;
}
};

const member = {
firstName: "Alisha",
lastName: "Chhabra"
};

let getName = person.getName.bind(member);
console.log(getName()); // Alisha Chhabra

How function overloading works in JavaScript?
Function overloading refers to the ability to define multiple functions with the same name but with different parameters. In many programming languages, the function to be executed is determined at compile time based on the parameters provided. However, in JavaScript, function overloading does not work in the same way because JavaScript functions can be called with any number and type of arguments.

One way to achieve function overloading in JavaScript is by using conditional statements to determine the appropriate behavior based on the arguments passed to the function.

Example

function myFunction() {
if (arguments.length === 1) {
console.log("Hello " + arguments[0]);
} else if (arguments.length === 2) {
console.log("Hello " + arguments[0] + " and " + arguments[1]);
} else {
console.log("Hello world");
}
}

myFunction(); // output: "Hello world"
myFunction("Alice"); // output: "Hello Alice"
myFunction("Bob", "Charlie"); // output: "Hello Bob and Charlie"

What is the purpose of void(0)?
The void(0) is used to prevent the page from refreshing. This will be helpful to eliminate the unwanted side-effect, because it will return the undefined primitive value.

It is commonly used for HTML document that uses href="JavaScript:void(0);" within an element. i.e, when you click a link, the browser loads a new page or refreshes the same page. But this behavior will be prevented using this expression.

event.preventDefault()

Example: the below link notify the message without reloading the page

Click Me!

<!DOCTYPE html>




Single Page Application Example
<br> #content {<br> padding: 20px;<br> }<br>


Home
About
Contact


<!-- Content will be dynamically updated here -->

<br> document.getElementById(&quot;home&quot;).addEventListener(&quot;click&quot;, function(event) {<br> event.preventDefault();<br> updateContent(&quot;Home Page&quot;);<br> });</p> <div class="highlight"><pre class="highlight plaintext"><code>document.getElementById("about").addEventListener("click", function(event) { event.preventDefault(); updateContent("About Us"); }); document.getElementById("contact").addEventListener("click", function(event) { event.preventDefault(); updateContent("Contact Us"); }); function updateContent(page) { // Simulate fetching content from the server or updating the DOM document.getElementById("content").innerHTML = `&lt;h2&gt;${page}&lt;/h2&gt;&lt;p&gt;This is the ${page} content.&lt;/p&gt;`; } </code></pre></div> <p>

In this example:

Clicking on navigation links (Home, About, Contact) won't cause the browser to reload or navigate to a different page.
The default action is prevented (event.preventDefault()), and the content is dynamically updated based on the clicked link using the updateContent function.

StopPropogation

Click DIV1 Element

DIV 2
DIV 1

function firstFunc(event) {
alert("DIV 1");
event.stopPropagation();
}

function secondFunc() {
alert("DIV 2");
}

Q 10.11. What is difference between stoppropagation, stopimmediatepropagation and preventdefault in javascript?

  1. event.preventDefault():

This method is used to stop the browser's default behavior when performing an action.

Example:

Please click on the checkbox control.

Checkbox:

document.querySelector("#id-checkbox").addEventListener("click", function(event) {
document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault()</code> won't let you check this!<br>";
event.preventDefault();
}, false);

  1. event.stopPropagation():

This method is used to prevent the propagation of an event as defined in the capturing/bubbling phase of the flow of an event in the browser.

Example:

function buttonClick(event) {
    event.stopPropagation();
    console.log('child');
}
Enter fullscreen mode Exit fullscreen mode
  1. event.stopImmediatePropagation():

With stopImmediatePropagation(), along with the event propagation, other event handlers will also be prevented from execution.

As a result, clicking on the div element will:

Prevent event bubbling to the parent elements
Prevent the execution of any other event listener attached to the element

What is the difference between document load and DOMContentLoaded events?

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images).

Singleton Pattern:

A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this way one can ensure that they don't accidentally create multiple instances.

let object = new function() {
this.name = "Alex";
}

What is the difference between get and defineProperty?

Both has similar results until unless you use classes. If you use get the property will be defined on the prototype of the object whereas using Object.defineProperty() the property will be defined on the instance it is applied to.

What are the advantages of Getters and Setters?

Below are the list of benefits of Getters and Setters,

They provide simpler syntax
They are used for defining computed properties, or accessors in JS.
Useful to provide equivalence relation between properties and methods
They can provide better data quality
Useful for doing things behind the scenes with the encapsulated logic.

Can I add getters and setters using defineProperty method?

Yes, You can use Object.defineProperty() method to add Getters and Setters. For example, the below counter object uses increment, decrement, add and substract properties,

var counterObj = {counter : 0};

// Define getters
Object.defineProperty(obj, "increment", {
  get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
  get : function () {this.counter--;}
});

// Define setters
Object.defineProperty(obj, "add", {
  set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
  set : function (value) {this.counter -= value;}
});

obj.add = 10;
obj.subtract = 5;
console.log(obj.increment); //6
console.log(obj.decrement); //5

What is an error object?

An error object is a built in error object that provides error information when an error occurs. It has two properties: name and message.

Example:

try {
  greeting("Welcome");
}
catch(err) {
  console.log(err.name + ": " + err.message);
}
// Output
ReferenceError: greeting is not defined

Q. What is the reason for wrapping the entire content of a JavaScript source file in a function block?

This is a common practice used in many popular JavaScript libraries (jQuery, Node.js, etc.). It creates a closure around the entire contents of the file which makes a private namespace and thereby avoids potential name clashes between different JavaScript modules and libraries.

use strict
When invoking a method on an object, this is the object that owns the method.
The global object is determined by the execution environment. In a browser, the global object is window object. Outside of the browser the global object is global .
While in strict mode this is undefined in a function.
this is the value passed as the first argument to .call() or .apply() or bind() methods.

Q. What will be the output of the following code?
var Employee = {
company: 'Acme'
}
var employee1 = Object.create(Employee);
delete employee1.company
console.log(employee1.company);

Q. Consider the two functions below. Will they both return the same thing?
function foo1()
{
return {
bar: "hello"
};
}
function foo2()
{
return
{
bar: "hello"
};
}

Answer
The two functions foo1 and foo2 may seem similar, but they actually behave differently due to the automatic semicolon insertion in JavaScript.

In foo1, the object is returned on the same line as the return statement, so it works as expected:

javascript
Copy code
function foo1() {
return {
bar: "hello"
};
}

console.log(foo1()); // { bar: "hello" }
In foo2, the issue arises because of the automatic semicolon insertion. JavaScript automatically inserts a semicolon after the return statement, treating the code as if it were written like this:

javascript
Copy code
function foo2() {
return; // semicolon is automatically inserted here
{
bar: "hello"
};
}

console.log(foo2()); // undefined
Due to this automatic semicolon insertion, the return statement ends prematurely, and the subsequent block is treated as a separate code block rather than an object literal. So, foo2 effectively returns undefined.

To avoid this issue, it's recommended to keep the opening brace on the same line as the return statement or use parentheses:

javascript
Copy code
// Version 1: Keep opening brace on the same line
function foo2() {
return {
bar: "hello"
};
}

// Version 2: Use parentheses
function foo2() {
return (
{
bar: "hello"
}
);
}
Both of these versions will correctly return the object { bar: "hello" }.

What is the 'this keyword' and how does its context change?
In JavaScript, the context of this refers to the execution context, typically an object that owns the function where this is used.

'this' in the Global Scope
In non-strict mode, this in the global scope refers to the window object. In strict mode, this is undefined.

'this' in Functions
In non-arrow functions, the value of this depends on how the function is invoked. When invoked:

As a method of an object: this is the object.
Alone: In a browser, this is window or global in Node.js. In strict mode, it's undefined.
With call, apply, or bind: this is explicitly set.
As a constructor (with new): this is the newly created object.

Important Note
If we want to make an instance of an object and include all the prototypal methods and variable there then use object.create(obj.prototype) instead of just obj.

Q. What is a polyfill
A polyfill is a piece of JS code used to provide modern functionality on older browsers that do not natively support it. For example, Silverlight plugin polyfill can be used to mimic the functionality of an HTML Canvas element on Microsoft Internet Explorer 7.

Q. What is tree shaking
Tree shaking is a form of dead code elimination. It means that unused modules will not be included in the bundle during the build process and for that it relies on the static structure of ES2015 module syntax,( i.e. import and export). Initially this has been popularized by the ES2015 module bundler rollup.

Q. What is the need of tree shaking
Tree Shaking can significantly reduce the code size in any application. i.e, The less code we send over the wire the more performant the application will be. For example, if we just want to create a “Hello World” Application using SPA frameworks then it will take around a few MBs, but by tree shaking it can bring down the size to just a few hundred KBs. Tree shaking is implemented in Rollup and Webpack bundlers.

Top comments (0)