JavaScript Interview Questions Flashcards

study

1
Q

To know the type of a JavaScript variable you use…

A

we can use the typeof operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the Primative Types

A
  1. String
  2. Number
  3. BigInt
  4. Boolean
  5. Undefined
    6.Null
    7.Symbol

Primitive data types can store only a single value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

String

A

It represents a series of characters and is written with quotes. A string can be represented using a single or a double quote.

var str = “Vivek Singh Bisht”; //using double quotes
var str2 = ‘John Doe’; //using single quotes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Number

A

It represents a number and can be written with or without decimals.

var x = 3; //without decimal
var y = 3.6; //with decimal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

BigInt

A

This data type is used to store numbers which are above the limitation of the Number data type. It can store large integers and is represented by adding “n” to an integer literal.

var bigInteger = 234567890123456789012345678901234567890;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Boolean

A

It represents a logical entity and can have only two values : true or false. Booleans are generally used for conditional testing.

var a = 2;
var b = 3;
var c = 2;
(a == b) // returns false
(a == c) //returns true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Undefined

A

When a variable is declared but not assigned, it has the value of undefined and it’s type is also undefined.

var x; // value of x is undefined
var y = undefined; // we can also set the value of a variable as undefined

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Null

A

It represents a non-existent or a invalid value.

var z = null;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Symbol

A

It is a new data type introduced in the ES6 version of javascript. It is used to store an anonymous and unique value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Non-primitive Types

A

To store multiple and complex values, non-primitive data types are used.

  1. Object

Note- It is important to remember that any data type that is not a primitive data type, is of Object type in javascript.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Object

A

// Collection of data in key-value pairs

var obj1 = {
x: 43,
y: “Hello world!”,
z: function(){
return this.x;
}
}

// Collection of data as an ordered list

var array1 = [5, “Hello”, true, 4.1];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Explain Hoisting in javascript.

A

Hoisting is the default behaviour of javascript where all the variable and function declarations are moved on top.

This means that irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global.

ex.1
hoistedVariable = 3;
console.log(hoistedVariable); // outputs 3 even when the variable is declared after it is initialized
var hoistedVariable;

ex.2
hoistedFunction(); // Outputs “ Hello world! “ even when the function is declared after calling

function hoistedFunction(){
console.log(“ Hello world! “);
}

ex.3
// Hoisting takes place in the local scope as well
function doSomething(){
x = 33;
console.log(x);
var x;
}

doSomething(); // Outputs 33 since the local variable “x” is hoisted inside the local scope

Note - Variable initializations are not hoisted, only variable declarations are hoisted:

var x;
console.log(x); // Outputs “undefined” since the initialization of “x” is not hoisted
x = 23;

Note - To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:

“use strict”;
x = 23; // Gives an error since ‘x’ is not declared
var x;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you avoid hoisting in javascript?

A

To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

whats the difference between variable initializations vs declarations?

A

Variable initializations are not hoisted, only variable declarations are hoisted:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Why do we use the word “debugger” in javascript?

A

The debugger for the browser must be activated in order to debug the code. Built-in debuggers may be switched on and off, requiring the user to report faults. The remaining section of the code should stop execution before moving on to the next line while debugging.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Difference between “ == “ and “ === “ operators.

A

Both are comparison operators. The difference between both the operators is that “==” is used to compare values whereas, “ === “ is used to compare both values and types.

var x = 2;
var y = “2”;
(x == y) // Returns true since the value of both x and y is the same
(x === y) // Returns false since the typeof x is “number” and typeof y is “string”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Difference between var and let keyword in javascript.

A

Some differences are:

  1. From the very beginning, the ‘var’ keyword was used in JavaScript programming whereas the keyword ‘let’ was just added in 2015.
  2. The keyword ‘Var’ has a function scope. Anywhere in the function, the variable specified using var is accessible but in ‘let’ the scope of a variable declared with the ‘let’ keyword is limited to the block in which it is declared. Let’s start with a Block Scope.
  3. In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in the block before the variable declaration results in a ReferenceError because the variable is in a “temporal dead zone” from the start of the block until the declaration is processed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Explain Implicit Type Coercion in javascript.

A

Implicit type coercion in javascript is the automatic conversion of value from one data type to another. It takes place when the operands of an expression are of different data types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

String coercion

A

String coercion takes place while using the ‘ + ‘ operator. When a number is added to a string, the number type is always converted to the string type.

ex.1
var x = 3;
var y = “3”;
x + y // Returns “33”

ex.2
var x = 24;
var y = “Hello”;
x + y // Returns “24Hello”;

Note - ‘ + ‘ operator when used to add two numbers, outputs a number. The same ‘ + ‘ operator when used to add two strings, outputs the concatenated string:

var name = “Vivek”;
var surname = “ Bisht”;
name + surname // Returns “Vivek Bisht”

Let’s understand both the examples where we have added a number to a string,

When JavaScript sees that the operands of the expression x + y are of different types ( one being a number type and the other being a string type ), it converts the number type to the string type and then performs the operation. Since after conversion, both the variables are of string type, the ‘ + ‘ operator outputs the concatenated string “33” in the first example and “24Hello” in the second example.

Note - Type coercion also takes place when using the ‘ - ‘ operator, but the difference while using ‘ - ‘ operator is that, a string is converted to a number and then subtraction takes place.

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Boolean Coercion

A

Boolean coercion takes place when using logical operators, ternary operators, if statements, and loop checks. To understand boolean coercion in if statements and operators, we need to understand truthy and falsy values.

Truthy values are those which will be converted (coerced) to true. Falsy values are those which will be converted to false.

All values except false, 0, 0n, -0, “”, null, undefined, and NaN are truthy values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

If statements:

A

var x = 0;
var y = 23;

if(x) { console.log(x) } // The code inside this block will not run since the value of x is 0(Falsy)

if(y) { console.log(y) } // The code inside this block will run since the value of y is 23 (Truthy)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Logical operators:

A

Logical operators in javascript, unlike operators in other programming languages, do not return true or false. They always return one of the operands.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

OR ( | | ) operator

A

If the first value is truthy, then the first value is returned. Otherwise, always the second value gets 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

if( x || z ){
console.log(“Code runs”); // This block runs because x || y returns 220(Truthy)
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

AND ( && ) operator

A

If both the values are truthy, always the second value is returned. If the first value is falsy then the first value is returned or if the second value is falsy then the second value is returned.

var x = 220;
var y = “Hello”;
var z = undefined;

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)
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Equality Coercion

A

Equality coercion takes place when using ‘ == ‘ operator. As we have stated before

The ‘ == ‘ operator compares values and not types.

While the above statement is a simple way to explain == operator, it’s not completely true

The reality is that while using the ‘==’ operator, coercion takes place.

The ‘==’ operator, converts both the operands to the same type and then compares them.

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.

Coercion does not take place when using the ‘===’ operator. Both operands are not converted to the same type in the case of ‘===’ operator.

var a = 226;
var b = “226”;

a === b // Returns false because coercion does not take place and the operands are of different types. Hence they are not equal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Is javascript a statically typed or a dynamically typed language?

A

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.

Since javascript is a loosely(dynamically) typed language, variables in JS are not associated with any type. A variable can hold the value of any data type.

For example, a variable that is assigned a number type can be converted to a string type:

var a = 23;
var a = “Hello World!”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is NaN property in JavaScript?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Explain passed by value and passed by reference.

A

In JavaScript, primitive data types are passed by value and non-primitive data types are passed by reference.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

what happens when we create a variable and assign a value to it?

A

var x = 2;

In the above example, we created a variable x and assigned it a value of “2”. In the background, the “=” (assign operator) allocates some space in the memory, stores the value “2” and returns the location of the allocated memory space. Therefore, the variable x in the above code points to the location of the memory space instead of pointing to the value 2 directly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

how does the assignment operator (=) behave with primitive types

A

primitive data types when passed to another variable, are passed by value. Instead of just assigning the same address to another variable, the value is passed and new space of memory is created

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

how does the assignment operator (=) behave with non-primitive types?

A

Non-primitive data types are always passed by reference.

var obj = { name: “Vivek”, surname: “Bisht” };
var obj2 = obj;

In the above example, the assign operator directly passes the location of the variable obj to the variable obj2. In other words, the reference of the variable obj is passed to the variable obj2.

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);

// Returns {name:”Akki”, surname:”Bisht”} since both the variables are pointing to the same address.

From the above example, we can see that while passing non-primitive data types, the assigned operator directly passes the address (reference).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is an Immediately Invoked Function in JavaScript?

A

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;
})();

To understand IIFE, we need to understand the two sets of parentheses that are added while creating an IIFE :

  1. The first set of parenthesis:

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

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.

  1. 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

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

A

In ECMAScript 5, a new feature called JavaScript Strict Mode allows you to write a code or a function in a “strict” operational environment. In most cases, this language is ‘not particularly severe’ when it comes to throwing errors. In ‘Strict mode,’ however, all forms of errors, including silent errors, will be thrown. As a result, debugging becomes a lot simpler. Thus programmer’s chances of making an error are lowered.

Characteristics of strict mode in javascript

  1. Duplicate arguments are not allowed by developers.
  2. In strict mode, you won’t be able to use the JavaScript keyword as a parameter or function name.
  3. The ‘use strict’ keyword is used to define strict mode at the start of the script. Strict mode is supported by all browsers.
  4. Engineers will not be allowed to create global variables in ‘Strict Mode.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Explain Higher Order Functions in javascript.

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Explain “this” keyword.

A

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.

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What do you mean by Self Invoking Functions?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

call()

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

apply()

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

bind():

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

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

A
  1. test () and exec () are RegExp expression methods used in javascript.
  2. 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.
  3. 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’.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What is currying in JavaScript?

A

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)

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What are some advantages of using External JavaScript?

A

External JavaScript is the JavaScript Code (script) written in a separate file with the extension.js, and then we link that file inside the <head> or <body> element of the HTML file where the code is to be placed.

Some advantages of external javascript are:

  1. It allows web designers and developers to collaborate on HTML and javascript files.
  2. We can reuse the code.
  3. Code readability is simple in external javascript.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Global Scope

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Function Scope:

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Block Scope:

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Scope Chain

A

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

As you can see in the code, 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Explain Closures in JavaScript.

A

Closures are an ability of a function to remember the variables and functions that are 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 function is executed

}
}

var initialiseClosure = randomFunc(); // Returns a function
initialiseClosure();
——
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

Mention some advantages of javascript.

A

There are many advantages of javascript. Some of them are:

  1. Javascript is executed on the client-side as well as server-side also. There are a variety of Frontend Frameworks that you may study and utilize. However, if you want to use JavaScript on the backend, you’ll need to learn NodeJS. It is currently the only JavaScript framework that may be used on the backend.
  2. Javascript is a simple language to learn.
  3. Web pages now have more functionality because of Javascript.
  4. To the end-user, Javascript is quite quick.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What are object prototypes?

A

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.

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What are callbacks?

A

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

  • In the code above, we are performing mathematical operations on the sum of two numbers. The operationOnSum function takes 3 arguments, the first number, the second number, and the operation that is to be performed on their sum (callback).
  • Both divideByHalf and multiplyBy2 functions are used as callback functions in the code above.
  • These callback functions will be executed only after the function operationOnSum is executed.
  • Therefore, a callback is a function that will be executed after another function gets executed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What are the types of errors in javascript?

A

There are two types of errors in javascript.

  1. Syntax error: Syntax errors are mistakes or spelling problems in the code that cause the program to not execute at all or to stop running halfway through. Error messages are usually supplied as well.
  2. Logical error: Reasoning mistakes occur when the syntax is proper but the logic or program is incorrect. The application executes without problems in this case. However, the output findings are inaccurate. These are sometimes more difficult to correct than syntax issues since these applications do not display error signals for logic faults.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What is memoization?

A

Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned.

Note- Although using memoization saves time, it results in larger consumption of memory since we are storing all the computed results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What is recursion in a programming language?

A

Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.

Example of a recursive function:

The following function calculates the sum of all the elements in an array by using recursion:

function computeSum(arr){
if(arr.length === 1){
return arr[0];
}
else{
return arr.pop() + computeSum(arr);
}
}
computeSum([7, 8, 9, 99]); // Returns 123

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

What is the use of a constructor function in javascript?

A

Constructor functions are used to create objects in javascript.

When do we use constructor functions?

If we want to create multiple objects having similar properties and methods, constructor functions are used.

Note- The name of a constructor function should always be written in Pascal Notation: every word should start with a capital letter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

What is DOM?

A
  • DOM stands for Document Object Model. DOM is a programming interface for HTML and XML documents.
  • When the browser tries to render an HTML document, it creates an object based on the HTML document called DOM. Using this DOM, we can manipulate or change various elements inside the HTML document.
  • Example of how HTML code gets converted to DOM:
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

Which method is used to retrieve a character from a certain index?

A

The charAt() function of the JavaScript string finds a char element at the supplied index. The index number begins at 0 and continues up to n-1, Here n is the string length. The index value must be positive, higher than, or the same as the string length.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

What do you mean by BOM?

A

Browser Object Model is known as BOM. It allows users to interact with the browser. A browser’s initial object is a window. As a result, you may call all of the window’s functions directly or by referencing the window. The document, history, screen, navigator, location, and other attributes are available in the window object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

What is the distinction between client-side and server-side JavaScript?

A

Client-side JavaScript is made up of two parts, a fundamental language and predefined objects for performing JavaScript in a browser. JavaScript for the client is automatically included in the HTML pages. At runtime, the browser understands this script.

Server-side JavaScript, involves the execution of JavaScript code on a server in response to client requests. It handles these requests and delivers the relevant response to the client, which may include client-side JavaScript for subsequent execution within the browser.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

What is the biggest difference between arrow functions and the traditional function expression?

A

The biggest difference between the traditional function expression and the arrow function is the handling of this keyword. By general definition, this keyword always refers to the object that is calling the function.

—- example
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
———

As you can see in the code above, obj1.valueOfThis() returns obj1 since this keyword refers to the object calling the function.

In the arrow functions, there is no binding of this keyword. This keyword inside an arrow function does not refer to the object calling it. It rather inherits its value from the parent scope which is the window object in this case. Therefore, in the code above, obj2.valueOfThis() returns the window object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

What are arrow functions?

A

Arrow functions were introduced in the ES6 version of javascript. They provide us with a new and shorter syntax for declaring functions. Arrow functions can only be used as a function expression.

Arrow functions are declared without the function keyword. If there is only one returning expression then we don’t need to use the return keyword as well in an arrow function as shown in the example above. Also, for functions having just one line of code, curly braces { } can be omitted.

If the function takes in only one argument, then the parenthesis () around the parameter can be omitted as shown in the code above.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

What do mean by prototype design pattern?

A

The Prototype Pattern produces different objects, but instead of returning uninitialized objects, it produces objects that have values replicated from a template – or sample – object. Also known as the Properties pattern, the Prototype pattern is used to create prototypes.

The introduction of business objects with parameters that match the database’s default settings is a good example of where the Prototype pattern comes in handy. The default settings for a newly generated business object are stored in the prototype object.

The Prototype pattern is hardly used in traditional languages, however, it is used in the development of new objects and templates in JavaScript, which is a prototypal language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

Differences between declaring variables using var, let and const.

A
  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

var vs let in functional scope

A

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.

——- example
function varVsLetFunction(){
let awesomeCar1 = “Audi”;
var awesomeCar2 = “Mercedes”;
}

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

{
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
——

  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What is a block in JavaScript?

A

In javascript, a block means the code written inside the curly braces {}.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

var vs let in block scope

A
  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

Const keyword

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

What is the rest parameter?

A
  • It provides an improved way of handling the parameters of a function.
  • Using the rest parameter syntax, we can create functions that can take a variable number of arguments.
  • Any number of arguments will be converted into an array using the rest parameter.
  • It also helps in extracting all or some parts of the arguments.
  • Rest parameters can be used by applying three dots (…) before the parameters.

**Note- Rest parameter should always be used at the last parameter of a function:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

Spread operator (…):

A

Although the syntax of the spread operator is exactly the same as the rest parameter, the spread operator is used to spreading an array, and object literals. We also use spread operators where one or more arguments are expected in a function call.

——— example
function addFourNumbers(num1,num2,num3,num4){
return num1 + num2 + num3 + num4;
}

let fourNumbers = [5, 6, 7, 8];
addFourNumbers(…fourNumbers);
// Spreads [5,6,7,8] as 5,6,7,8

let array1 = [3, 4, 5, 6];
let clonedArray1 = […array1];
// Spreads the array into 3,4,5,6
console.log(clonedArray1); // Outputs [3,4,5,6]

let obj1 = {x:’Hello’, y:’Bye’};
let clonedObj1 = {…obj1}; // Spreads and clones obj1
console.log(obj1);

let obj2 = {z:’Yes’, a:’No’};
let mergedObj = {…obj1, …obj2}; // Spreads both the objects and merges it
console.log(mergedObj);
// Outputs {x:’Hello’, y:’Bye’,z:’Yes’,a:’No’};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

What are the key differences between rest parameter and spread operator?

A
  • Rest parameter is used to take a variable number of arguments and turns them into an array while the spread operator takes an array or an object and spreads it
  • Rest parameter is used in function declaration whereas the spread operator is used in function calls.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

In JavaScript, how many different methods can you make an object?

A

In JavaScript, there are several ways to declare or construct an object.

  1. Object.
  2. using Class.
  3. create Method.
  4. Object Literals.
  5. using Function.
  6. Object Constructor.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

What is the use of promises in javascript?

A

Promises are used to handle asynchronous operations in javascript.

Before promises, callbacks were used to handle asynchronous operations. But due to the limited functionality of callbacks, using multiple callbacks to handle asynchronous code can lead to unmanageable code.

Promises are used to handle asynchronous operations like server requests, for ease of understanding, we are using an operation to calculate the sum of three elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

How many states does a Promise object have?

A

Promise object has four states -

  1. Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.
  2. Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed.
  3. Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
  4. Settled - This state represents that the promise has been either rejected or fulfilled.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

How is a promise created?

A

A promise is created using the Promise constructor which takes in a callback function with two parameters, resolve and reject respectively.

resolve is a function that will be called when the async operation has been successfully completed.

reject is a function that will be called, when the async operation fails or if some error occurs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

How do you consume a promise?

A

We can consume any promise by attaching then() and catch() methods to the consumer.

then() method is used to access the result when the promise is fulfilled.

catch() method is used to access the result/error when the promise is rejected. In the code below, we are consuming the promise:

—– example
sumOfThreeElements(4, 5, 6)
.then(result=> console.log(result))
.catch(error=> console.log(error));
// In the code above, the promise is fulfilled so the then() method gets executed

sumOfThreeElements(7, 0, 33, 41)
.then(result => console.log(result))
.catch(error=> console.log(error));
// In the code above, the promise is rejected hence the catch() method gets executed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

What are classes in javascript?

A

Introduced in the ES6 version, classes are nothing but syntactic sugars for constructor functions. They provide a new way of declaring constructor functions in javascript. Below are the examples of how classes are declared and used:

Key points to remember about classes:

  • Unlike functions, classes are not hoisted. A class cannot be used before it is declared.
  • A class can inherit properties and methods from other classes by using the extend keyword.
  • All the syntaxes inside the class must follow the strict mode(‘use strict’) of javascript. An error will be thrown if the strict mode rules are not followed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

What are generator functions?

A

Introduced in the ES6 version, generator functions are a special class of functions.

They can be stopped midway and then continue from where they had stopped.

Generator functions are declared with the function* keyword instead of the normal function keyword:

function normalFunc(){
return 22;
console.log(2); // This line of code does not get executed
}
—–
In the case of generator functions, when called, they do not execute the code, instead, they return a generator object. This generator object handles the execution.
——
function* genFunc(){
yield 3;
yield 4;
}
genFunc(); // Returns Object [Generator] {}
——
The generator object consists of a method called next(), this method when called, executes the code until the nearest yield statement, and returns the yield value.

genFunc().next(); // Returns {value: 3, done:false}
—-
As one can see the next method returns an object consisting of a value and done properties. Value property represents the yielded value. Done property tells us whether the function code is finished or not. (Returns true if finished).

function* iteratorFunc() {
let count = 0;
for (let i = 0; i < 2; i++) {
count++;
yield i;
}
return count;
}

let iterator = iteratorFunc();
console.log(iterator.next()); // {value:0,done:false}
console.log(iterator.next()); // {value:1,done:false}
console.log(iterator.next()); // {value:2,done:true}
—-
As you can see in the code above, the last line returns done:true, since the code reaches the return statement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

Explain WeakSet in javascript.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

Why do we use callbacks?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

Explain WeakMap in javascript.

A

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});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

What is Object Destructuring?

A

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

const classStrength = classDetails.strength;
const classBenches = classDetails.benches;
const classBlackBoard = classDetails.blackBoard;
—-
AFTER intro of Object Destructuring in ES6

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

Difference between prototypal and classical inheritance

A

Programers build objects, which are representations of real-time entities, in traditional OO programming. Classes and objects are the two sorts of abstractions. A class is a generalization of an object, whereas an object is an abstraction of an actual thing. A Vehicle, for example, is a specialization of a Car. As a result, automobiles (class) are descended from vehicles (object).

Classical inheritance differs from prototypal inheritance in that classical inheritance is confined to classes that inherit from those remaining classes, but prototypal inheritance allows any object to be cloned via an object linking method. Despite going into too many specifics, a prototype essentially serves as a template for those other objects, whether they extend the parent object or not.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

What is a Temporal Dead Zone?

A

Temporal Dead Zone is a behaviour that occurs with variables declared using let and const keywords. It is a behaviour where we try to access a variable before it is initialized. Examples of temporal dead zone:

x = 23; // Gives reference error

let x;

function anotherRandomFunc(){
message = “Hello”; // Throws a reference error

let message;
}
anotherRandomFunc();

In the code above, both in the global scope and functional scope, we are trying to access variables that have not been declared yet. This is called the Temporal Dead Zone.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

What do you mean by JavaScript Design Patterns?

A

JavaScript design patterns are repeatable approaches for errors that arise sometimes when building JavaScript browser applications. They truly assist us in making our code more stable.

They are divided mainly into 3 categories

Creational Design Pattern
Structural Design Pattern
Behavioral Design Pattern.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

Creational Design Pattern:

A

The object generation mechanism is addressed by the JavaScript Creational Design Pattern. They aim to make items that are appropriate for a certain scenario.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
85
Q

Structural Design Pattern:

A

The JavaScript Structural Design Pattern explains how the classes and objects we’ve generated so far can be combined to construct bigger frameworks. This pattern makes it easier to create relationships between items by defining a straightforward way to do so.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
86
Q

Behavioral Design Pattern:

A

This design pattern highlights typical patterns of communication between objects in JavaScript. As a result, the communication may be carried out with greater freedom.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
87
Q

Is JavaScript a pass-by-reference or pass-by-value language?

A

The variable’s data is always a reference for objects, hence it’s always pass by value. As a result, if you supply an object and alter its members inside the method, the changes continue outside of it. It appears to be pass by reference in this case. However, if you modify the values of the object variable, the change will not last, demonstrating that it is indeed passed by value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

Difference between Async/Await and Generators usage to achieve the same functionality.

A
  • Generator functions are run by their generator yield by yield which means one output at a time, whereas Async-await functions are executed sequentially one after another.
  • Async/await provides a certain use case for Generators easier to execute.
  • The output result of the Generator function is always value: X, done: Boolean, but the return value of the Async function is always an assurance or throws an error.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

What are the primitive data types in JavaScript?

A

A primitive is a data type that isn’t composed of other data types. It’s only capable of displaying one value at a time. By definition, every primitive is a built-in data type (the compiler must be knowledgeable of them) nevertheless, not all built-in datasets are primitives. In JavaScript, there are 5 different forms of basic data. The following values are available:

  1. Boolean
  2. Undefined
  3. Null
  4. Number
  5. String
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q

What is the role of deferred scripts in JavaScript?

A

The processing of HTML code while the page loads are disabled by nature till the script hasn’t halted. Your page will be affected if your network is a bit slow, or if the script is very hefty. When you use Deferred, the script waits for the HTML parser to finish before executing it. This reduces the time it takes for web pages to load, allowing them to appear more quickly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

What has to be done in order to put Lexical Scoping into practice?

A

To support lexical scoping, a JavaScript function object’s internal state must include not just the function’s code but also a reference to the current scope chain.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
92
Q

What is the purpose of the following JavaScript code?

var scope = “global scope”;
function check()
{
var scope = “local scope”;
function f()
{
return scope;
}
return f;
}

A

Every executing function, code block, and script as a whole in JavaScript has a related object known as the Lexical Environment. The preceding code line returns the value in scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

Guess the outputs of the following codes:

A

Answers:

Code 1 - Outputs 2 and 12. Since, even though let variables are not hoisted, due to the async nature of javascript, the complete function code runs before the setTimeout function. Therefore, it has access to both x and y.

Code 2 - Outputs 3, three times since variable declared with var keyword does not have block scope. Also, inside the for loop, the variable i is incremented first and then checked.

Code 3 - Output in the following order:
2
4
3
1 // After two seconds
Even though the second timeout function has a waiting time of zero seconds, the javascript engine always evaluates the setTimeout function using the Web API, and therefore, the complete function executes before the setTimeout function can execute.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
94
Q

How do you create an Object using literal syntax?

A

The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.

var object = {
name: “Sudheer”,
age: 34
};

Object literal property values can be of any data type, including array, function, and nested object.
*Note: This is one of the easiest ways to create an object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
95
Q

How do you create an Object using constructor?

A

The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.

var object = new Object();

The Object() is a built-in constructor function so “new” keyword is not required. The above code snippet can be re-written as:

var object = Object();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
96
Q

How do you create an Object using the create method?

A

The create method of Object is used to create a new object by passing the specificied prototype object and properties as arguments, i.e., this pattern is helpful to create new objects based on existing objects. The second argument is optional and it is used to create properties on a newly created object.

The following code creates a new empty object whose prototype is null.

var object = Object.create(null);

The following example creates an object along with additional new properties.

let vehicle = {
wheels: ‘4’,
fuelType: ‘Gasoline’,
color: ‘Green’
}
let carProps = {
type: {
value: ‘Volkswagen’
},
model: {
value: ‘Golf’
}
}

var car = Object.create(vehicle, carProps);
console.log(car);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
97
Q

How do you create an Object using the Function constructor?

A

In this approach, create any function and apply the new operator to create object instances.

function Person(name) {
this.name = name;
this.age = 21;
}
var object = new Person(“Sudheer”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q

How do you create an Object using the Function constructor with prototype?

A

This is similar to function constructor but it uses prototype for their properties and methods,

function Person() {}
Person.prototype.name = “Sudheer”;
var object = new Person();

This is equivalent to creating an instance with Object.create method with a function prototype and then calling that function with an instance and parameters as arguments.

function func() {}
new func(x, y, z);

(OR)

// Create a new instance using function prototype.
var newInstance = Object.create(func.prototype)

// Call the function
var result = func.call(newInstance, x, y, z),

// If the result is a non-null object then use it otherwise just use the new instance.
console.log(result && typeof result === ‘object’ ? result : newInstance);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
99
Q

How do you create an Object using the Object’s assign method?

A

The Object.assign method is used to copy all the properties from one or more source objects and stores them into a target object.

The following code creates a new staff object by copying properties of his working company and the car he owns.

const orgObject = { company: ‘XYZ Corp’};
const carObject = { name: ‘Toyota’};
const staff = Object.assign({}, orgObject, carObject);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
100
Q

How do you create an Object using ES6 Class syntax?

A

ES6 introduces class feature to create objects.

class Person {
constructor(name) {
this.name = name;
}
}

var object = new Person(“Sudheer”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
101
Q

How do you create an Object using the Singleton pattern?

A

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

var object = new (function () {
this.name = “Sudheer”;
})();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
102
Q

What is a prototype chain?

A

Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language.

The prototype on object instance is available through Object.getPrototypeOf(object) or __proto__ property whereas prototype on constructors function is available through Object.prototype.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
103
Q

What is the difference between Call, Apply and Bind?

A

Call: The call() method invokes a function with a given this value and arguments provided one by one

Apply: Invokes the function with a given this value and allows you to pass in arguments as an array

Bind: returns a new function, allowing you to pass any number of arguments

Call and Apply are pretty much interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma separated list of arguments. You can remember by treating Call is for comma (separated list) and Apply is for Array.

Bind creates a new function that will have this set to the first parameter passed to bind().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
104
Q

An example use of Call()

A

Call: The call() method invokes a function with a given this value and arguments provided one by one

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
105
Q

An example use of Apply()

A

Apply: Invokes the function with a given this value and allows you to pass in arguments as an array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
106
Q

An example use of bind()

A

Bind: returns a new function, allowing you to pass any number of arguments

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
107
Q

What is JSON and its common operations?

A

JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. It is useful when you want to transmit data across a network. It is basically just a text file with an extension of .json, and a MIME type of application/json

  1. Parsing: Converting a string to a native object
    ex. –> JSON.parse(text);
  2. Stringification: Converting a native object to a string so that it can be transmitted across the network
    ex. –> JSON.stringify(object);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
108
Q

What is the purpose of the array slice method?

A

The slice() method returns the selected elements in an array as a new array object. It selects the elements starting at the given start argument, and ends at the given optional end argument without including the last element. If you omit the second argument then it selects till the end of the array.

*Note: Slice method doesn’t mutate the original array but it returns the subset as a new array.

Some of the examples of this method are,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
109
Q

What is the purpose of the array splice() method?

A

The splice() method adds/removes items to/from an array, and then returns the removed item. The first argument specifies the array position/index for insertion or deletion whereas the optional second argument indicates the number of elements to be deleted. Each additional argument is added to the array.

*Note: Splice method modifies the original array and returns the deleted array.

let arrayIntegersOriginal1 = [1, 2, 3, 4, 5];
let arrayIntegersOriginal2 = [1, 2, 3, 4, 5];
let arrayIntegersOriginal3 = [1, 2, 3, 4, 5];

let arrayIntegers1 = arrayIntegersOriginal1.splice(0, 2); // returns [1, 2]; original array: [3, 4, 5]

let arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array: [1, 2, 3]

let arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, “a”, “b”, “c”); //returns [4]; original array: [1, 2, 3, “a”, “b”, “c”, 5]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
110
Q

What is the difference between slice and splice?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
111
Q

How do you compare Object and Map?

A

Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Due to this reason, Objects have been used as Maps historically. But there are important differences that make using a Map preferable in certain cases:

  1. The keys of an Object can be Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
  2. The keys in a Map are ordered while keys added to Object are not. Thus, when iterating over it, a Map object returns keys in the order of insertion.
  3. You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
  4. A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.
  5. An Object has a prototype, so there are default keys in an object that could collide with your keys if you’re not careful. As of ES5 this can be bypassed by creating an object(which can be called a map) using Object.create(null), but this practice is seldom done.
  6. A Map may perform better in scenarios involving frequent addition and removal of key pairs.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
112
Q

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

A

JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators take 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,

  1. Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  2. 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.
  3. Two Boolean operands are strictly equal if both are true or both are false.
  4. Two objects are strictly equal if they refer to the same Object.
  5. Null and Undefined types are not equal with ===, but equal with == . i.e, null===undefined –> false, but null==undefined –> true
    Some of the example which covers the above cases:
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
113
Q

What are lambda expressions or arrow functions?

A

An arrow function is a shorter/concise syntax for a function expression and does not have its own this, arguments, super, or new.target. These functions are best suited for non-method functions, and they cannot be used as constructors.

Some of the examples of arrow functions are listed as below,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
114
Q

What is a first class function in JavaScript?

A

In Javascript, functions are first class objects. First-class functions means when functions in that language are treated like any other variable.

For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. For example, in the below example, handler functions assigned to a listener:

const handler = () => console.log(“This is a click handler function”);
document.addEventListener(“click”, handler);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
115
Q

What is a first order function in JavaScript?

A

A first-order function is a function that doesn’t accept another function as an argument and doesn’t return a function as its return value.

const firstOrder = () => console.log(“I am a first order function!”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
116
Q

What is a higher order function in JavaScript?

A

A higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
117
Q

What is the currying function in JavaScript?

A

Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Currying is named after a mathematician Haskell Curry. By applying currying, an n-ary function turns into a unary function.

Curried functions are great to improve code reusability and functional composition.

Let’s take an example of n-ary function and how it turns into a currying function,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
118
Q

What is a unary function in JavaScript?

A

A unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for a single argument accepted by a function.

Let us take an example of unary function:

const unaryFunction = (a) => console.log(a + 10); // Add 10 to the given argument and display the value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
119
Q

What is a pure function in JavaScript?

A

A Pure function is a function where the return value is only determined by its arguments without any side effects. i.e, If you call a function with the same arguments ‘n’ number of times and ‘n’ number of places in the application then it will always return the same value.

As per the attached code snippets, the Push function is impure itself by altering the array and returning a push number index independent of the parameter value, whereas Concat on the other hand takes the array and concatenates it with the other array producing a whole new array without side effects. Also, the return value is a concatenation of the previous array.

Remember that Pure functions are important as they simplify unit testing without any side effects and no need for dependency injection. They also avoid tight coupling and make it harder to break your application by not having any side effects. These principles are coming together with the Immutability concept of ES6: giving preference to const over let usage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
120
Q

What is the purpose of the let keyword in JS?

A

The let statement declares a block scope local variable. Hence the variables defined with let keyword are limited in scope to the block, statement, or expression on which it is used. Whereas variables declared with the var keyword used to define a variable globally, or locally to an entire function regardless of block scope.

Let’s take an example to demonstrate the usage,

let counter = 30;
if (counter === 30) {
let counter = 31;
console.log(counter); // 31
}
console.log(counter); // 30 (because the variable in if block won’t exist here)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
121
Q

What is the difference between let and var? (tabular format)

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
122
Q

What is the difference between let and var? (code example)

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
123
Q

What is the reason to choose the name let as a keyword in JS?

A

let is a mathematical statement that was adopted by early programming languages like Scheme and Basic. It has been borrowed from dozens of other languages that use let already as a traditional keyword as close to var as possible.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
124
Q

How do you redeclare variables in a switch block without an error in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
125
Q

What is the Temporal Dead Zone in JS?

A

The Temporal Dead Zone(TDZ) is a specific period or area of a block where a variable is inaccessible until it has been intialized with a value. This behavior in JavaScript that occurs when declaring a variable with the let and const keywords, but not with var. In ECMAScript 6, accessing a let or const variable before its declaration (within its scope) causes a ReferenceError.

Let’s see this behavior with an example,

function somemethod() {
console.log(counter1); // undefined
console.log(counter2); // ReferenceError
var counter1 = 1;
let counter2 = 2;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
126
Q

What is an IIFE (Immediately Invoked Function Expression)

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
127
Q

How do you decode or encode a URL in JavaScript?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
128
Q

What is memoization in JavaScript?

A

Memoization is a functional programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache. Let’s take an example of adding function with memoization,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
129
Q

What is Hoisting in JavaScript?

A

Hoisting is a JavaScript mechanism where variables, function declarations and classes are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialisation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
130
Q

What are classes in ES6?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
131
Q

What are closures in JavaScript?

A

A closure is the combination of a function and the lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables, functions and other data even after the outer function has finished its execution. The closure has three scope chains.

  1. Own scope where variables defined between its curly brackets
  2. Outer function’s variables
  3. Global variables
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
132
Q

What are modules in JavaScript?

A

Modules refer to small units of independent, reusable code and also act as the foundation of many JavaScript design patterns. Most of the JavaScript modules export an object literal, a function, or a constructor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
133
Q

Why do you need modules in JavaScript?

A

Below are the list of benefits using modules in javascript ecosystem

  1. Maintainability
  2. Reusability
  3. Namespacing
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
134
Q

What is scope in javascript?

A

Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
135
Q

What is a service worker in javascript?

A

A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don’t need a web page or user interaction. Some of the major features of service workers are Rich offline experiences(offline first web application development), periodic background syncs, push notifications, intercept and handle network requests and programmatically managing a cache of responses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
136
Q

How do you manipulate DOM using a service worker?

A

Service worker can’t access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
137
Q

How do you reuse information across service worker restarts?

A

The problem with service worker is that it gets terminated when not in use, and restarted when it’s next needed, so you cannot rely on global state within a service worker’s onfetch and onmessage handlers. In this case, service workers will have access to IndexedDB API in order to persist and reuse across restarts.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
138
Q

What is IndexedDB?

A

IndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
139
Q

What is web storage?

A

Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user’s browser, in a much more intuitive fashion than using cookies. The web storage provides two mechanisms for storing data on the client.

Local storage: It stores data for current origin with no expiration date.

Session storage: It stores data for one session and the data is lost when the browser tab is closed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
140
Q

What is a post message?

A

Post message is a method that enables cross-origin communication between Window objects.(i.e, between a page and a pop-up that it spawned, or between a page and an iframe embedded within it).

Generally, scripts on different pages are allowed to access each other if and only if the pages follow same-origin policy(i.e, pages share the same protocol, port number, and host).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
141
Q

What is a Cookie?

A

A cookie is a piece of data that is stored on your computer to be accessed by your browser. Cookies are saved as key/value pairs. For example, you can create a cookie named username as below,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
142
Q

Why do you need a Cookie?

A

Cookies are used to remember information about the user profile(such as username). It basically involves two steps,

When a user visits a web page, the user profile can be stored in a cookie.
Next time the user visits the page, the cookie remembers the user profile.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
143
Q

What are the options in a cookie?

A

There are few below options available for a cookie,

  1. By default, the cookie is deleted when the browser is closed but you can change this behavior by setting expiry date (in UTC time).
    ex.
    document.cookie = “username=John; expires=Sat, 8 Jun 2019 12:00:00 UTC”;
  2. By default, the cookie belongs to a current page. But you can tell the browser what path the cookie belongs to using a path parameter.
    ex.
    document.cookie = “username=John; path=/services”;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
144
Q

How do you delete a cookie?

A

You can delete a cookie by setting the expiry date as a passed date. You don’t need to specify a cookie value in this case. For example, you can delete a username cookie in the current page as below.
ex.
document.cookie =
“username=; expires=Fri, 07 Jun 2019 00:00:00 UTC; path=/;”;

Note: You should define the cookie path option to ensure that you delete the right cookie. Some browsers doesn’t allow to delete a cookie unless you specify a path parameter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
145
Q

What are the differences between cookie, local storage and session storage?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
146
Q

What is the main difference between localStorage and sessionStorage?

A

LocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets cleared when the page session ends.?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
147
Q

How do you access web storage?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
148
Q

What are the methods available on session storage?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
149
Q

What is a storage event and its event handler?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
150
Q

Why do you need web storage?

A

Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Also, the information is never transferred to the server. Hence this is a more recommended approach than Cookies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
151
Q

How do you check web storage browser support?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
152
Q

How do you check web workers browser support?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
153
Q

Give an example of a web worker.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
154
Q

What are the restrictions of web workers on DOM?

A

WebWorkers don’t have access to below javascript objects since they are defined in an external files

  1. Window object
  2. Document object
  3. Parent object
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
155
Q

What is a promise?

A

A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it’s not resolved(for example, network error). It will be in one of the 3 possible states: fulfilled, rejected, or pending.

The syntax of Promise creation looks like below,

const promise = new Promise(function (resolve, reject) {
// promise description
});

The usage of a promise would be as below,

const promise = new Promise(
(resolve) => {
setTimeout(() => {
resolve(“I’m a Promise!”);
}, 5000);
},
(reject) => {}
);

promise.then((value) => console.log(value));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
156
Q

Why do you need a promise?

A

Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing cleaner code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
157
Q

What are the three states of promise?

A

Promises have three states:

  1. Pending: This is an initial state of the Promise before an operation begins
  2. Fulfilled: This state indicates that the specified operation was completed.
  3. Rejected: This state indicates that the operation did not complete. In this case an error value will be thrown.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
158
Q

What is a callback function?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
159
Q

Why do we need callbacks?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
160
Q

What is a callback hell?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
161
Q

What are server-sent events?

A

Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only. This has been used in Facebook/Twitter updates, stock price updates, news feeds etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
162
Q

How do you receive server-sent event notifications?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
163
Q

How do you check browser support for server-sent events?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
164
Q

What are the events available for server sent events?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
165
Q

What are the main rules of promise?

A

A promise must follow a specific set of rules:

  1. A promise is an object that supplies a standard-compliant .then() method
  2. A pending promise may transition into either fulfilled or rejected state
  3. A fulfilled or rejected promise is settled and it must not transition into any other state.
  4. Once a promise is settled, the value must not change.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
166
Q

What is callback in callback?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
167
Q

What is promise chaining?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
168
Q

What is promise.all?

A

Promise.all is a promise that takes an array of promises as an input (an iterable), and it gets resolved when all the promises get resolved or any one of them gets rejected. For example, the syntax of promise.all method is below.

*Note: Remember that the order of the promises(output the result) is maintained as per input order.

Promise.all([Promise1, Promise2, Promise3]) .then(result) => { console.log(result) }) .catch(error => console.log(Error in promises ${error}))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
169
Q

What is the purpose of the race method in promise?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
170
Q

What is a strict mode in javascript?

A

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This way it prevents certain actions from being taken and throws more exceptions. The literal expression “use strict”; instructs the browser to use the javascript code in the Strict mode.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
171
Q

Why do you need strict mode?

A

Strict mode is useful to write “secure” JavaScript by notifying “bad syntax” into real errors. For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
172
Q

How do you declare strict mode?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
173
Q

What is the purpose of double exclamation?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
174
Q

What is the purpose of the delete operator?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
175
Q

What is typeof operator in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
176
Q

What is undefined property in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
177
Q

What is null value in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
178
Q

What is the difference between null and undefined?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
179
Q

What is eval?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
180
Q

What is the difference between window and document in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
181
Q

How do you access history in javascript?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
182
Q

How do you detect caps lock key turned on or not?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
183
Q

What is isNaN?

A

The isNaN() function is used to determine whether a value is an illegal number (Not-a-Number) or not. i.e, This function returns true if the value equates to NaN. Otherwise it returns false.

isNaN(“Hello”); //true
isNaN(“100”); //false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
184
Q

What are the differences between undeclared and undefined variables in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
185
Q

What are global variables in JS?

A

Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable

msg = “Hello”; // var is missing, it becomes global variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
186
Q

What are the problems with global variables?

A

The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
187
Q

What is NaN property in JS?

A

The NaN property is a global property that represents “Not-a-Number” value. i.e, It indicates that a value is not a legal number. It is very rare to use NaN in a program but it can be used as return value for few cases

Math.sqrt(-1);
parseInt(“Hello”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
188
Q

What is the purpose of isFinite function in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
189
Q

What is an event flow in JS?

A

Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event for each of its parent elements first, starting at the top with the global window object. There are two ways of event flow

Top to Bottom(Event Capturing)
Bottom to Top (Event Bubbling)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
190
Q

What is event bubbling in JS?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
191
Q

What is event capturing in JS?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
192
Q

How do you submit a form using JavaScript?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
193
Q

How do you find operating system details in JS?

A

The window.navigator object contains information about the visitor’s browser OS details. Some of the OS properties are available under platform property,

console.log(navigator.platform);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
194
Q

What is the difference between document load and DOMContentLoaded events?

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
195
Q

What is the difference between native, host and user objects in JS?

A

Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification. For example, String, Math, RegExp, Object, Function etc core objects defined in the ECMAScript spec.

Host objects are objects provided by the browser or runtime environment (Node). For example, window, XmlHttpRequest, DOM nodes etc are considered as host objects.

User objects are objects defined in the javascript code. For example, User objects created for profile information.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
196
Q

What are the tools or techniques used for debugging JavaScript code?

A

You can use below tools or techniques for debugging javascript

  1. Chrome Devtools
  2. debugger statement
  3. Good old console.log statement
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
197
Q

What are the pros and cons of promises over callbacks?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
198
Q

What is the difference between an attribute and a property?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
199
Q

What is same-origin policy?

A

The same-origin policy is a policy that prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. If you enable this policy then it prevents a malicious script on one page from obtaining access to sensitive data on another web page using Document Object Model(DOM).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
200
Q

What is the purpose of void 0 in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
201
Q

Is JavaScript a compiled or interpreted language?

A

JavaScript is an interpreted language, not a compiled language. An interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. Nowadays modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
202
Q

Is JavaScript a case-sensitive language?

A

Yes, JavaScript is a case sensitive language. The language keywords, variables, function & object names, and any other identifiers must always be typed with a consistent capitalization of letters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
203
Q

Is there any relation between Java and JavaScript?

A

No, they are entirely two different programming languages and have nothing to do with each other. But both of them are Object Oriented Programming languages and like many other languages, they follow similar syntax for basic features(if, else, for, switch, break, continue etc).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
204
Q

What are events in JS?

A

Events are “things” that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can react on these events. Some of the examples of HTML events are,

  1. Web page has finished loading
  2. Input field was changed
  3. Button was clicked
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
205
Q

Who created javascript?

A

JavaScript was created by Brendan Eich in 1995 during his time at Netscape Communications. Initially it was developed under the name Mocha, but later the language was officially called LiveScript when it first shipped in beta releases of Netscape.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
206
Q

What is the use of preventDefault method in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
207
Q

What is the use of stopPropagation method in JS?

A

The stopPropagation method is used to stop the event from bubbling up the event chain. For example, the below nested divs with stopPropagation method prevents default event propagation when clicking on nested div(Div1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
208
Q

What are the steps involved in return false usage in JS?

A

The return false statement in event handlers performs the below steps,

  1. First it stops the browser’s default action or behaviour.
  2. It prevents the event from propagating the DOM
  3. Stops callback execution and returns immediately when called.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
209
Q

What is BOM?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
210
Q

What is the use of setTimeout?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
211
Q

What is the use of setInterval?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
212
Q

Why is JavaScript treated as Single threaded?

A

JavaScript is a single-threaded language. Because the language specification does not allow the programmer to write code so that the interpreter can run parts of it in parallel in multiple threads or processes. Whereas languages like java, go, C++ can make multi-threaded and multi-process programs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
213
Q

What is an event delegation in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
214
Q

What is ECMAScript?

A

ECMAScript is the scripting language that forms the basis of JavaScript. ECMAScript standardized by the ECMA International standards organization in the ECMA-262 and ECMA-402 specifications. The first edition of ECMAScript was released in 1997.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
215
Q

What is JSON?

A

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language in the way objects are built in JavaScript.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
216
Q

What are the syntax rules of JSON?

A

Below are the list of syntax rules of JSON

  1. The data is in name/value pairs
  2. The data is separated by commas
  3. Curly braces hold objects
  4. Square brackets hold arrays
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
217
Q

What is the purpose JSON stringify?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
218
Q

How do you parse JSON string?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
219
Q

Why do you need JSON?

A

When exchanging data between a browser and a server, the data can only be text. Since JSON is text only, it can easily be sent to and from a server, and used as a data format by any programming language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
220
Q

What are PWAs?

A

Progressive web applications (PWAs) are a type of mobile app delivered through the web, built using common web technologies including HTML, CSS and JavaScript. These PWAs are deployed to servers, accessible through URLs, and indexed by search engines.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
221
Q

What is the purpose of clearTimeout method?

A

The clearTimeout() function is used in javascript to clear the timeout which has been set by setTimeout()function before that. i.e, The return value of setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
222
Q

What is the purpose of clearInterval method?

A

The clearInterval() function is used in javascript to clear the interval which has been set by setInterval() function. i.e, The return value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
223
Q

How do you redirect new page in javascript?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
224
Q

How do you check whether a string contains a substring?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
225
Q

How do you validate an email in javascript?

A

You can validate an email in javascript using regular expressions. It is recommended to do validations on the server side instead of the client side. Because the javascript can be disabled on the client side.

function validateEmail(email) {
var re =
/^(([^<>()[]\.,;:\s@”]+(.[^<>()[]\.,;:\s@”]+)*)|(“.+”))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
226
Q

How do you get the current url with javascript?

A

You can use window.location.href expression to get the current url path and you can use the same expression for updating the URL too. You can also use document.URL for read-only purposes but this solution has issues in FF.

console.log(“location.href”, window.location.href); // Returns full URL

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
227
Q

What are the various url properties of location object?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
228
Q

How do get query string values in javascript?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
229
Q

How do you check if a key exists in an object in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
230
Q

How do you loop through or enumerate javascript object?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
231
Q

How do you test for an empty object?

A
  1. Using Object entries(ECMA 7+): You can use object entries length along with constructor type.

Object.entries(obj).length === 0 && obj.constructor === Object; // Since date object length is 0, you need to check constructor check as well

  1. Using Object keys(ECMA 5+): You can use object keys length along with constructor type.

Object.keys(obj).length === 0 && obj.constructor === Object; // Since date object length is 0, you need to check constructor check as well

  1. Using for-in with hasOwnProperty(Pre-ECMA 5): You can use a for-in loop along with hasOwnProperty.

function isEmpty(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}

return JSON.stringify(obj) === JSON.stringify({});
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
232
Q

What is an arguments object in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
233
Q

How do you make first letter of the string in an uppercase in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
234
Q

What are the pros and cons of for loop in JS?

A

The for-loop is a commonly used iteration syntax in javascript. It has both pros and cons

Pros
1. Works on every environment
2. You can use break and continue flow control statements

Cons
1. Too verbose
2. Imperative
3. You might face one-by-off errors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
235
Q

How do you display the current date in javascript?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
236
Q

How do you compare two date objects in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
237
Q

How do you check if a string starts with another string in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
238
Q

How do you trim a string in javascript?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
239
Q

How do you add a key value pair in javascript

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
240
Q

Is the !– notation represents a special operator in JS?

A

No,that’s not a special operator. But it is a combination of 2 standard operators one after the other,

  1. A logical not (!)
  2. A prefix decrement (–)

At first, the value decremented by one and then tested to see if it is equal to zero or not for determining the truthy/falsy value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
241
Q

How do you assign default values to variables?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
242
Q

How do you define multiline strings in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
243
Q

What is an app shell model?

A

An application shell (or app shell) architecture is one way to build a Progressive Web App that reliably and instantly loads on your users’ screens, similar to what you see in native applications. It is useful for getting some initial HTML to the screen fast without a network.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
244
Q

Can we define properties for functions in JS?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
245
Q

What is the way to find the number of parameters expected by a function?

A
246
Q

What is a polyfill?

A

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.

247
Q

What are break and continue statements in JS?

A
248
Q

What are js labels?

A
249
Q

What are the benefits of keeping declarations at the top in JS?

A

It is recommended to keep all declarations at the top of each script or function. The benefits of doing this are,

  1. Gives cleaner code
  2. It provides a single place to look for local variables
  3. Easy to avoid unwanted global variables
  4. It reduces the possibility of unwanted re-declarations
250
Q

What are the benefits of initializing variables in JS?

A

It is recommended to initialize variables because of the below benefits,

  1. It gives cleaner code
  2. It provides a single place to initialize variables
  3. Avoid undefined values in the code
251
Q

What are the recommendations to create new object in JS?

A

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.

  1. Assign {} instead of new Object()
  2. Assign “” instead of new String()
  3. Assign 0 instead of new Number()
  4. Assign false instead of new Boolean()
  5. Assign [] instead of new Array()
  6. Assign /()/ instead of new RegExp()
  7. Assign function (){} instead of new Function()
252
Q

How do you define JSON arrays?

A
253
Q

How do you generate random integers in JS?

A

You can use Math.random() with Math.floor() to return random integers. For example, if you want generate random integers between 1 to 10, the multiplication factor should be 10,

Math.floor(Math.random() * 10) + 1; // returns a random integer from 1 to 10

Math.floor(Math.random() * 100) + 1; // returns a random integer from 1 to 100

Note: Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)

254
Q

Can you write a random integers function to print integers with in a range in JS?

A
255
Q

What is tree shaking in JS?

A

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.

256
Q

What is the need of tree shaking in JS?

A

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.

257
Q

Is it recommended to use eval in JS?

A

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.

258
Q

What is a Regular Expression in JS?

A
259
Q

What are the string methods available in Regular expression in JS?

A
260
Q

What are modifiers in regular expression in JS?

A
261
Q

What are regular expression patterns?

A
262
Q

[abc]:

A

Used to find any of the characters between the brackets(a,b,c)

263
Q

[0-9]:

A

Used to find any of the digits between the brackets

264
Q

(a|b):

A

Used to find any of the alternatives separated with |

265
Q

\d:

A

Used to find a digit

266
Q

\s:

A

Used to find a whitespace character

267
Q

\b:

A

Used to find a match at the beginning or ending of a word

268
Q

n+:

A

Used to find matches for any string that contains at least one n

269
Q

n*:

A

Used to find matches for any string that contains zero or more occurrences of n

270
Q

n?:

A

Used to find matches for any string that contains zero or one occurrences of n

271
Q

What is a RegExp object in JS?

A
272
Q

How do you search a string for a pattern in JS?

A
273
Q

What is the purpose of exec method in JS?

A

The purpose of exec method is similar to test method but it executes a search for a match in a specified string and returns a result array, or null instead of returning true/false.

var pattern = /you/;
console.log(pattern.exec(“How are you?”)); //[“you”, index: 8, input: “How are you?”, groups: undefined]

274
Q

How do you change the style of a HTML element in JS?

A
275
Q

What would be the result of 1+2+’3’ in JS?

A

The output is going to be 33. Since 1 and 2 are numeric values, the result of the first two digits is going to be a numeric value 3. The next digit is a string type value because of that the addition of numeric value 3 and string type value 3 is just going to be a concatenation value 33.

276
Q

What is a debugger statement in JS?

A

The debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect. For example, in the below function a debugger statement has been inserted. So execution is paused at the debugger statement just like a breakpoint in the script source.

function getProfile() {
// code goes here
debugger;
// code goes here
}

277
Q

What is the purpose of breakpoints in debugging in JS?

A

You can set breakpoints in the javascript code once the debugger statement is executed and the debugger window pops up. At each breakpoint, javascript will stop executing, and let you examine the JavaScript values. After examining values, you can resume the execution of code using the play button.

278
Q

Can I use reserved words as identifiers in JS?

A

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

279
Q

How do you detect a mobile browser in JS?

A

You can use regex which returns a true or false value depending on whether or not the user is browsing with a mobile.

window.mobilecheck = function () {
var mobileCheck = false;
(function (a) {
if (
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
a
) ||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| ||a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
a.substr(0, 4)
)
)
mobileCheck = true;
})(navigator.userAgent || navigator.vendor || window.opera);
return mobileCheck;
};

280
Q

How do you detect a mobile browser without regexp in JS?

A

You can detect mobile browsers by simply running through a list of devices and checking if the useragent matches anything. This is an alternative solution for RegExp usage,

281
Q

How do you get the image width and height using JS?

A

You can programmatically get the image and check the dimensions(width and height) using Javascript.

282
Q

How do you make synchronous HTTP request in JS?

A
283
Q

How do you make asynchronous HTTP request in JS?

A
284
Q

How do you convert date to another timezone in javascript?

A

You can use the toLocaleString() method to convert dates in one timezone to another. For example, let’s convert current date to British English timezone as below,

console.log(event.toLocaleString(“en-GB”, { timeZone: “UTC” })); //29/06/2019, 09:56:00

285
Q

What are the properties used to get size of window in JS?

A

You can use innerWidth, innerHeight, clientWidth, clientHeight properties of windows, document element and document body objects to find the size of a window. Let’s use them combination of these properties to calculate the size of a window or document,

286
Q

What is a conditional operator in javascript?

A

The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statements.

var isAuthenticated = false;
console.log(
isAuthenticated ? “Hello, welcome” : “Sorry, you are not authenticated”
); //Sorry, you are not authenticated

287
Q

Can you apply chaining on conditional operator in JS?

A

Yes, you can apply chaining on conditional operators similar to if … else if … else if … else chain. The syntax is going to be as below,

288
Q

What are the ways to execute javascript after page load?

A
289
Q

What is the difference between proto and prototype in JS?

A

The __proto__ object is the actual object that is used in the lookup chain to resolve methods, etc. Whereas prototype is the object that is used to build __proto__ when you create an object with new.

new Employee().__proto__ === Employee.prototype;

new Employee().prototype === undefined;

290
Q

Give an example where do you really need semicolon in JS.

A
291
Q

What is a freeze method in JS?

A
292
Q

What is the purpose of freeze method in JS?

A

Below are the main benefits of using freeze method,

  1. It is used for freezing objects and arrays.
  2. It is used to make an object immutable.
293
Q

Why do I need to use freeze method in JS?

A

In the Object-oriented paradigm, an existing API contains certain elements that are not intended to be extended, modified, or re-used outside of their current context. Hence it works as the final keyword which is used in various languages.

294
Q

How do you detect a browser language preference in JS?

A

You can use navigator object to detect a browser language preference as below,

var language =
(navigator.languages && navigator.languages[0]) || // Chrome / Firefox
navigator.language || // All browsers
navigator.userLanguage; // IE <= 10

console.log(language);

295
Q

How to convert string to title case with javascript?

A

Title case means that the first letter of each word is capitalized. You can convert a string to title case using the below function,

function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase();
});
}
toTitleCase(“good morning john”); // Good Morning John

296
Q

How do you detect javascript disabled in the page?

A

You can use the <noscript> tag to detect javascript disabled or not. The code block inside <noscript> gets executed when JavaScript is disabled, and is typically used to display alternative content when the page generated in JavaScript.</noscript></noscript>

<script>
// JS related code goes here
</script>

<noscript>
<a>JavaScript is disabled in the page. Please click Next Page</a>
</noscript>

297
Q

What are various operators supported by javascript?

A

An operator is capable of manipulating(mathematical and logical computations) a certain value or operand. There are various operators supported by JavaScript as below,

298
Q

What is a rest parameter in JS?

A
299
Q

What happens if you do not use rest parameter as a last argument in JS?

A

The rest parameter should be the last argument, as its job is to collect all the remaining arguments into an array. For example, if you define a function like below it doesn’t make any sense and will throw an error.

function someFunc(a,…b,c){
//You code goes here
return;
}

300
Q

What are the bitwise operators available in javascript?

A
301
Q

What is a spread operator in JS?

A

Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. Let’s take an example to see this behavior,

function calculateSum(x, y, z) {
return x + y + z;
}

const numbers = [1, 2, 3];

console.log(calculateSum(…numbers)); // 6

302
Q

How do you determine whether object is frozen or not in JS?

A

Object.isFrozen() method is used to determine if an object is frozen or not.An object is frozen if all of the below conditions hold true,

  1. If it is not extensible.
  2. If all of its properties are non-configurable.
  3. If all its data properties are non-writable. The usage is going to be as follows,

const object = {
property: “Welcome JS world”,
};
Object.freeze(object);
console.log(Object.isFrozen(object));

303
Q

How do you determine two values same or not using object in JS?

A
304
Q

What is the purpose of using object is method in JS?

A

Some of the applications of Object’s is method are follows,

  1. It is used for comparison of two strings.
  2. It is used for comparison of two numbers.
  3. It is used for comparing the polarity of two numbers.
  4. It is used for comparison of two objects.
305
Q

How do you copy properties from one object to other in JS?

A
306
Q

What are the applications of Object assign method in JS?

A

Below are the some of main applications of Object.assign() method,

  1. It is used for cloning an object.
  2. It is used to merge objects with the same properties.
307
Q

What is a proxy object in JS?

A
308
Q

What is the purpose of Object.seal() method in JS?

A
309
Q

What are the applications of Object.seal method in JS?

A

Below are the main applications of Object.seal() method,

  1. It is used for sealing objects and arrays.
  2. It is used to make an object immutable.
310
Q

What are the differences between freeze and seal methods for Objects in JS?

A

If an object is frozen using the Object.freeze() method then its properties become immutable and no changes can be made in them whereas if an object is sealed using the Object.seal() method then the changes can be made in the existing properties of the object.

311
Q

How do you determine if an object is sealed or not?

A
312
Q

How do you get enumerable key and value pairs from objects in JS?

A
313
Q

What is the main difference between Object.values and Object.entries method?

A
314
Q

How can you get the list of keys of any object in JS?

A
315
Q

How do you create an object with prototype in JS?

A

The Object.create() method is used to create a new object with the specified prototype object and properties. i.e, It uses an existing object as the prototype of the newly created object. It returns a new object with the specified prototype object and properties.

const user = {
name: “John”,
printInfo: function () {
console.log(My name is ${this.name}.);
},
};

const admin = Object.create(user);

admin.name = “Nick”; // Remember that “name” is a property set on “admin” but not on “user” object

admin.printInfo(); // My name is Nick

316
Q

What is a WeakSet in JS?

A
317
Q

What are the differences between WeakSet and Set?

A

The main difference is that references to objects in Set are strong while references to objects in WeakSet are weak. i.e, An object in WeakSet can be garbage collected if there is no other reference to it. Other differences are,

  1. Sets can store any value Whereas WeakSets can store only collections of objects
  2. WeakSet does not have size property unlike Set
  3. WeakSet does not have methods such as clear, keys, values, entries, forEach.
  4. WeakSet is not iterable.
318
Q

List down the collection of methods available on WeakSet.

A
319
Q

What is a WeakMap in JS?

A
320
Q

What are the differences between WeakMap and Map?

A

The main difference is that references to key objects in Map are strong while references to key objects in WeakMap are weak. i.e, A key object in WeakMap can be garbage collected if there is no other reference to it. Other differences are,

  1. Maps can store any key type Whereas WeakMaps can store only collections of key objects
  2. WeakMap does not have size property unlike Map
  3. WeakMap does not have methods such as clear, keys, values, entries, forEach.
  4. WeakMap is not iterable.
321
Q

List down the collection of methods available on WeakMap.

A
321
Q

What is the purpose of uneval?

A
322
Q

How do you encode an URL in JS?

A

The encodeURI() function is used to encode complete URI which has special characters except (, / ? : @ & = + $ #) characters.

var uri = “https://mozilla.org/?x=шеллы”;
var encoded = encodeURI(uri);
console.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B

323
Q

How do you decode an URL in JS?

A

The decodeURI() function is used to decode a Uniform Resource Identifier (URI) previously created by encodeURI().

var uri = “https://mozilla.org/?x=шеллы”;
var encoded = encodeURI(uri);
console.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B
try {
console.log(decodeURI(encoded)); // “https://mozilla.org/?x=шеллы”
} catch (e) {
// catches a malformed URI
console.error(e);
}

324
Q

How do you print the contents of web page in JS?

A
325
Q

What is the difference between uneval and eval in JS?

A
326
Q

What is an anonymous function in JS?

A

An anonymous function is a function without a name! Anonymous functions are commonly assigned to a variable name or used as a callback function. The syntax would be as below,

function (optionalParameters) {
//do something
}

const myFunction = function(){ //Anonymous function assigned to a variable
//do something
};

[1, 2, 3].map(function(element){ //Anonymous function used as a callback function
//do something
});

Let’s see the above anonymous function in an example,

var x = function (a, b) {
return a * b;
};
var z = x(5, 10);
console.log(z); // 50

327
Q

What is the precedence order between local and global variables in JS?

A

A local variable takes precedence over a global variable with the same name. Let’s see this behavior in an example.

var msg = “Good morning”;
function greeting() {
msg = “Good Evening”;
console.log(msg); // Good Evening
}
greeting();

328
Q

What are javascript accessors?

A

ECMAScript 5 introduced javascript object accessors or computed properties through getters and setters. Getters uses the get keyword whereas Setters uses the set keyword.

329
Q

How do you define property on Object constructor in JS?

A

The Object.defineProperty() static method is used to define a new property directly on an object, or modify an existing property on an object, and returns the object. Let’s see an example to know how to define property,

const newObject = {};

Object.defineProperty(newObject, “newProperty”, {
value: 100,
writable: false,
});

console.log(newObject.newProperty); // 100

newObject.newProperty = 200; // It throws an error in strict mode due to writable setting

330
Q

What is the difference between get and defineProperty in JS?

A

Both have 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.

331
Q

What are the advantages of Getters and Setters in JS?

A

Below are the list of benefits of Getters and Setters,

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

Can I add getters and setters using defineProperty method in jS?

A

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

333
Q

What is the purpose of switch-case in JS?

A
334
Q

What are the conventions to be followed for the usage of switch case in JS?

A
335
Q

What are primitive data types in JS?

A
336
Q

What are the different ways to access object properties in JS?

A
337
Q

What are the function parameter rules in JS?

A
338
Q

What is an error object in JS?

A
339
Q

When you get a syntax error in JS?

A

A SyntaxError is thrown if you try to evaluate code with a syntax error. For example, the below missing quote for the function parameter throws a syntax error

try {
eval(“greeting(‘welcome)”); // Missing ‘ will produce an error
} catch (err) {
console.log(err.name);
}

340
Q

What are the different error names from error object?

A
341
Q

What are the various statements in error handling in JS?

A
342
Q

What are the two types of loops in javascript?

A
  1. Entry Controlled loops: In this kind of loop type, the test condition is tested before entering the loop body. For example, For Loop and While Loop comes under this category.
  2. Exit Controlled Loops: In this kind of loop type, the test condition is tested or evaluated at the end of the loop body. i.e, the loop body will execute at least once irrespective of test condition true or false. For example, do-while loop comes under this category.
343
Q

What is nodejs?

A

Node.js is a server-side platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications. It is an event-based, non-blocking, asynchronous I/O runtime that uses Google’s V8 JavaScript engine and libuv library.

344
Q

What is an Intl object in JS?

A

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. It provides access to several constructors and language sensitive functions.

345
Q

How do you perform language specific date and time formatting in JS?

A

You can use the Intl.DateTimeFormat object which is a constructor for objects that enable language-sensitive date and time formatting. Let’s see this behavior with an example,

var date = new Date(Date.UTC(2019, 07, 07, 3, 0, 0));
console.log(new Intl.DateTimeFormat(“en-GB”).format(date)); // 07/08/2019
console.log(new Intl.DateTimeFormat(“en-AU”).format(date)); // 07/08/2019

346
Q

What is an Iterator in JS?

A

An iterator is an object which defines a sequence and a return value upon its termination. It implements the Iterator protocol with a next() method which returns an object with two properties: value (the next value in the sequence) and done (which is true if the last value in the sequence has been consumed).

347
Q

How does synchronous iteration work in JS?

A
348
Q

What is an event loop in JS?

A

The event loop is a process that continuously monitors both the call stack and the event queue and checks whether or not the call stack is empty. If the call stack is empty and there are pending events in the event queue, the event loop dequeues the event from the event queue and pushes it to the call stack. The call stack executes the event, and any additional events generated during the execution are added to the end of the event queue.

Note: The event loop allows Node.js to perform non-blocking I/O operations, even though JavaScript is single-threaded, by offloading operations to the system kernel whenever possible. Since most modern kernels are multi-threaded, they can handle multiple operations executing in the background.

349
Q

What is call stack in JS?

A

Call Stack is a data structure for javascript interpreters to keep track of function calls(creates execution context) in the program. It has two major actions,

Whenever you call a function for its execution, you are pushing it to the stack.
Whenever the execution is completed, the function is popped out of the stack.

350
Q

What is an event queue in JS

A

The event queue follows the queue data structure. It stores async callbacks to be added to the call stack. It is also known as the Callback Queue or Macrotask Queue.

Whenever the call stack receives an async function, it is moved into the Web API. Based on the function, Web API executes it and awaits the result. Once it is finished, it moves the callback into the event queue (the callback of the promise is moved into the microtask queue).

The event loop constantly checks whether or not the call stack is empty. Once the call stack is empty and there is a callback in the event queue, the event loop moves the callback into the call stack. But if there is a callback in the microtask queue as well, it is moved first. The microtask queue has a higher priority than the event queue.

351
Q

What is a decorator in JS?

A

A decorator is an expression that evaluates to a function and that takes the target, name, and decorator descriptor as arguments. Also, it optionally returns a decorator descriptor to install on the target object. Let’s define admin decorator for user class at design time,

352
Q

What are the properties of Intl object in JS?

A
353
Q

What is an Unary operator in JS?

A

The unary(+) operator is used to convert a variable to a number.If the variable cannot be converted, it will still become a number but with the value NaN. Let’s see this behavior in an action.

354
Q

How do you sort elements in an array in JS?

A

The sort() method is used to sort the elements of an array in place and returns the sorted array. The example usage would be as below,

var months = [“Aug”, “Sep”, “Jan”, “June”];
months.sort();
console.log(months); // [“Aug”, “Jan”, “June”, “Sep”]

354
Q

What is the purpose of compareFunction while sorting arrays in JS?

A

The compareFunction is used to define the sort order. If omitted, the array elements are converted to strings, then sorted according to each character’s Unicode code point value. Let’s take an example to see the usage of compareFunction,

355
Q

How do you reverse an array in JS?

A

You can use the reverse() method to reverse the elements in an array. This method is useful to sort an array in descending order. Let’s see the usage of reverse() method in an example,

356
Q

How do you find min and max value in an array in JS?

A

You can use Math.min and Math.max methods on array variables to find the minimum and maximum elements within an array. Let’s create two functions to find the min and max value with in an array,

357
Q

How do you find min and max values without Math functions in JS?

A

You can write functions which loop through an array comparing each value with the lowest value or highest value to find the min and max values. Let’s create those functions to find min and max values,

358
Q

What is an empty statement and purpose of it in JS?

A

The empty statement is a semicolon (;) indicating that no statement will be executed, even if JavaScript syntax requires one. Since there is no action with an empty statement you might think that it’s usage is quite less, but the empty statement is occasionally useful when you want to create a loop that has an empty body. For example, you can initialize an array with zero values as below,

// Initialize an array a
for (let i = 0; i < a.length; a[i++] = 0);

359
Q

How do you get metadata of a module in JS?

A

You can use the import.meta object which is a meta-property exposing context-specific meta data to a JavaScript module. It contains information about the current module, such as the module’s URL. In browsers, you might get different meta data than NodeJS.


;
console.log(import.meta); // { url: “file:///home/user/welcome-module.js” }

360
Q

What is a comma operator in JS?

A

The comma operator is used to evaluate each of its operands from left to right and returns the value of the last operand. This is totally different from comma usage within arrays, objects, and function arguments and parameters. For example, the usage for numeric expressions would be as below,

var x = 1;
x = (x++, x);

console.log(x); // 2

361
Q

What is the advantage of a comma operator in jS?

A

It is normally used to include multiple expressions in a location that requires a single expression. One of the common usages of this comma operator is to supply multiple parameters in a for loop. For example, the below for loop uses multiple expressions in a single location using comma operator,

362
Q

What is typescript?

A

TypeScript is a typed superset of JavaScript created by Microsoft that adds optional types, classes, async/await, and many other features, and compiles to plain JavaScript. Angular built entirely in TypeScript and used as a primary language. You can install it globally as

363
Q

What are the differences between javascript and typescript?

A
364
Q

What are the advantages of typescript over javascript?

A

Below are some of the advantages of typescript over javascript,

  1. TypeScript is able to find compile time errors at the development time only and it makes sures less runtime errors. Whereas javascript is an interpreted language.
  2. TypeScript is strongly-typed or supports static typing which allows for checking type correctness at compile time. This is not available in javascript.
  3. TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 unlike ES6 features of javascript which may not be supported in some browsers.
365
Q

What is an object initializer in JS?

A

An object initializer is an expression that describes the initialization of an Object. The syntax for this expression is represented as a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). This is also known as literal notation. It is one of the ways to create an object.

var initObject = { a: “John”, b: 50, c: {} };

console.log(initObject.a); // John

366
Q

What is a constructor method in JS?

A

The constructor method is a special method for creating and initializing an object created within a class. If you do not specify a constructor method, a default constructor is used. The example usage of constructor would be as below,

367
Q

What happens if you write constructor more than once in a class in JS?

A

The “constructor” in a class is a special method and it should be defined only once in a class. i.e, If you write a constructor method more than once in a class it will throw a SyntaxError error.

368
Q

How do you call the constructor of a parent class in JS?

A

You can use the super keyword to call the constructor of a parent class. Remember that super() must be called before using ‘this’ reference. Otherwise it will cause a reference error. Let’s the usage of it,

368
Q

How do you get the prototype of an object in JS?

A

You can use the Object.getPrototypeOf(obj) method to return the prototype of the specified object. i.e. The value of the internal prototype property. If there are no inherited properties then null value is returned.

const newPrototype = {};
const newObject = Object.create(newPrototype);

console.log(Object.getPrototypeOf(newObject) === newPrototype); // true

369
Q

What happens If I pass string type for getPrototype method?

A

In ES5, it will throw a TypeError exception if the obj parameter isn’t an object. Whereas in ES2015, the parameter will be coerced to an Object.

// ES5
Object.getPrototypeOf(“James”); // TypeError: “James” is not an object
// ES2015
Object.getPrototypeOf(“James”); // String.prototype

370
Q

How do you set prototype of one object to another in JS?

A

You can use the Object.setPrototypeOf() method that sets the prototype (i.e., the internal Prototype property) of a specified object to another object or null. For example, if you want to set prototype of a square object to rectangle object would be as follows,

371
Q

How do you check whether an object can be extendable or not in JS?

A
372
Q

How do you prevent an object to extend?

A
373
Q

What are the different ways to make an object non-extensible in JS?

A

You can mark an object non-extensible in 3 ways,

Object.preventExtensions
Object.seal
Object.freeze

var newObject = {};

Object.preventExtensions(newObject); // Prevent objects are non-extensible
Object.isExtensible(newObject); // false

var sealedObject = Object.seal({}); // Sealed objects are non-extensible
Object.isExtensible(sealedObject); // false

var frozenObject = Object.freeze({}); // Frozen objects are non-extensible
Object.isExtensible(frozenObject); // false

374
Q

How do you define multiple properties on an object in JS?

A

The Object.defineProperties() method is used to define new or modify existing properties directly on an object and returning the object. Let’s define multiple properties on an empty object,

const

375
Q

What is MEAN in javascript?

A

The MEAN (MongoDB, Express, AngularJS, and Node.js) stack is the most popular open-source JavaScript software tech stack available for building dynamic web apps where you can write both the server-side and client-side halves of the web project entirely in JavaScript.

376
Q

What Is Obfuscation in javascript?

A

Obfuscation is the deliberate act of creating obfuscated javascript code(i.e, source or machine code) that is difficult for humans to understand. It is something similar to encryption, but a machine can understand the code and execute it. Let’s see the below function before Obfuscation,

377
Q

Why do you need Obfuscation in JS?

A

Below are the few reasons for Obfuscation,

  1. The Code size will be reduced. So data transfers between server and client will be fast.
  2. It hides the business logic from outside world and protects the code from others
  3. Reverse engineering is highly difficult
  4. The download time will be reduced
378
Q

What is Minification in JS?

A

Minification is the process of removing all unnecessary characters(empty spaces are removed) and variables will be renamed without changing it’s functionality. It is also a type of obfuscation .

379
Q

What are the advantages of minification?

A

Normally it is recommended to use minification for heavy traffic and intensive requirements of resources. It reduces file sizes with below benefits,

  1. Decreases loading times of a web page
  2. Saves bandwidth usages
380
Q

What are the differences between Obfuscation and Encryption?

A
381
Q

What are the common tools used for minification?

A

There are many online/offline tools to minify the javascript files,

  1. Google’s Closure Compiler
  2. UglifyJS2
  3. jsmin
  4. javascript-minifier.com/
  5. prettydiff.com
382
Q

How do you perform form validation using javascript?

A

JavaScript can be used to perform HTML form validation. For example, if the form field is empty, the function needs to notify, and return false, to prevent the form being submitted. Lets’ perform user login in an html form,

383
Q

How do you perform form validation without javascript?

A

You can perform HTML form validation automatically without using javascript. The validation enabled by applying the required attribute to prevent form submission when the input is empty.

<form>
<input></input>
<input></input>
</form>

Note: Automatic form validation does not work in Internet Explorer 9 or earlier.

384
Q

What are the DOM methods available for constraint validation?

A
385
Q

What are the available constraint validation DOM properties?

A

Below are the list of some of the constraint validation DOM properties available,

  1. validity: It provides a list of boolean properties related to the validity of an input element.
  2. validationMessage: It displays the message when the validity is false.
  3. willValidate: It indicates if an input element will be validated or not.
386
Q

What are the list of validity properties?

A
387
Q

Give an example usage of rangeOverflow property?

A
388
Q

Is enums feature available in javascript?

A

No, javascript does not natively support enums. But there are different kinds of solutions to simulate them even though they may not provide exact equivalents. For example, you can use freeze or seal on object,

var DaysEnum = Object.freeze({“monday”:1, “tuesday”:2, “wednesday”:3, …})

389
Q

What is an enum?

A

An enum is a type restricting variables to one value from a predefined set of constants. JavaScript has no enums but typescript provides built-in enum support.

enum Color {
RED, GREEN, BLUE
}

390
Q

How do you list all properties of an object?

A

You can use the Object.getOwnPropertyNames() method which returns an array of all properties found directly in a given object. Let’s the usage of it in an example,

391
Q

How do you get property descriptors of an object?

A

You can use the Object.getOwnPropertyDescriptors() method which returns all own property descriptors of a given object. The example usage of this method is below,

392
Q

What are the attributes provided by a property descriptor?

A
393
Q

How do you extend classes in JS?

A
394
Q

How do I modify the url without reloading the page?

A

The window.location.href property will be helpful to modify the url but it reloads the page. HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you to add and modify history entries, respectively. For example, you can use pushState as below,

window.history.pushState(“page2”, “Title”, “/page2.html”);

395
Q

How do you check whether an array includes a particular value or not in JS?

A
396
Q

How do you compare scalar arrays in JS?

A

You can use length and every method of arrays to compare two scalar(compared directly using ===) arrays. The combination of these expressions can give the expected result,

397
Q

How to get the value from get parameters in JS?

A

The new URL() object accepts the url string and searchParams property of this object can be used to access the get parameters. Remember that you may need to use polyfill or window.location to access the URL in older browsers(including IE).

let urlString = “http://www.some-domain.com/about.html?x=1&y=2&z=3”; //window.location.href
let url = new URL(urlString);
let parameterZ = url.searchParams.get(“z”);
console.log(parameterZ); // 3

398
Q

How do you print numbers with commas as thousand separators in JS?

A

You can use the Number.prototype.toLocaleString() method which returns a string with a language-sensitive representation such as thousand separator,currency etc of this number.

function convertToThousandFormat(x) {
return x.toLocaleString(); // 12,345.679
}

console.log(convertToThousandFormat(12345.6789));

399
Q

What is the difference between java and javascript?

A
400
Q

Does JavaScript supports namespace?

A

JavaScript doesn’t support namespace by default. So if you create any element(function, method, object, variable) then it becomes global and pollutes the global namespace. Let’s take an example of defining two functions without any namespace,

function func1() {
console.log(“This is a first definition”);
}
function func1() {
console.log(“This is a second definition”);
}
func1(); // This is a second definition

It always calls the second function definition. In this case, namespace will solve the name collision problem.

401
Q

How do you declare namespace in JS?

A

Even though JavaScript lacks namespaces, we can use Objects , IIFE to create namespaces.

  1. Using Object Literal Notation: Let’s wrap variables and functions inside an Object literal which acts as a namespace. After that you can access them using object notation
  2. Using IIFE (Immediately invoked function expression): The outer pair of parentheses of IIFE creates a local scope for all the code inside of it and makes the anonymous function a function expression. Due to that, you can create the same function in two different function expressions to act as a namespace.
  3. Using a block and a let/const declaration: In ECMAScript 6, you can simply use a block and a let declaration to restrict the scope of a variable to a block.
402
Q

Give an example of declaring a namespace using Object Literal Notation.

A

Using Object Literal Notation: Let’s wrap variables and functions inside an Object literal which acts as a namespace. After that you can access them using object notation

403
Q

Give an example of declaring a namespace using IIFE.

A

Using IIFE (Immediately invoked function expression): The outer pair of parentheses of IIFE creates a local scope for all the code inside of it and makes the anonymous function a function expression. Due to that, you can create the same function in two different function expressions to act as a namespace.

404
Q

Give an example of declaring a namespace using a block and a let/const declaration.

A

Using a block and a let/const declaration: In ECMAScript 6, you can simply use a block and a let declaration to restrict the scope of a variable to a block.

405
Q

How do you invoke javascript code in an iframe from parent page?

A

Initially iFrame needs to be accessed using either document.getElementBy or window.frames. After that contentWindow property of iFrame gives the access for targetFunction

document.getElementById(“targetFrame”).contentWindow.targetFunction();

window.frames[0].frameElement.contentWindow.targetFunction(); // Accessing iframe this way may not work in latest versions chrome and firefox

406
Q

How do get the timezone offset from date in JS?

A

You can use the getTimezoneOffset method of the date object. This method returns the time zone difference, in minutes, from current locale (host system settings) to UTC

var offset = new Date().getTimezoneOffset();
console.log(offset); // -480

407
Q

How do you load CSS and JS files dynamically?

A
408
Q

What are the different methods to find HTML elements in DOM?

A

If you want to access any element in an HTML page, you need to start with accessing the document object. Later you can use any of the below methods to find the HTML element,

  1. document.getElementById(id): It finds an element by Id

2.document.getElementsByTagName(name): It finds an element by tag name

3.document.getElementsByClassName(name): It finds an element by class name

409
Q

What is jQuery?

A

jQuery is a popular cross-browser JavaScript library that provides Document Object Model (DOM) traversal, event handling, animations and AJAX interactions by minimizing the discrepancies across browsers. It is widely famous with its philosophy of “Write less, do more”. For example, you can display welcome message on the page load using jQuery as below,

$(document).ready(function () {
// It selects the document and apply the function on page load
alert(“Welcome to jQuery world”);
});

Note: You can download it from jquery’s official site or install it from CDNs, like google.

410
Q

What is V8 JavaScript engine?

A

V8 is an open source high-performance JavaScript engine used by the Google Chrome browser, written in C++. It is also being used in the node.js project. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors. Note: It can run standalone, or can be embedded into any C++ application.

411
Q

Why do we call javascript as dynamic language?

A

JavaScript is a loosely typed or a dynamic language because variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned/reassigned with values of all types.

let age = 50; // age is a number now
age = “old”; // age is a string now
age = true; // age is a boolean

412
Q

What is a void operator in JS?

A
413
Q

How to set the cursor to wait in JS?

A
414
Q

How do you create an infinite loop in JS?

A

You can create infinite loops using for and while loops without using any expressions. The for loop construct or syntax is better approach in terms of ESLint and code optimizer tools,

for (;;) {}
while (true) {}

415
Q

Why do you need to avoid with statement in JS?

A
416
Q

What is the output of below for loops?

A

The output of the above for loops is 4 4 4 4 and 0 1 2 3

Explanation: Due to the event queue/loop of javascript, the setTimeout callback function is called after the loop has been executed. Since the variable i is declared with the var keyword it became a global variable and the value was equal to 4 using iteration when the time setTimeout function is invoked. Hence, the output of the first loop is 4 4 4 4.

Whereas in the second loop, the variable i is declared as the let keyword it becomes a block scoped variable and it holds a new value(0, 1 ,2 3) for each iteration. Hence, the output of the first loop is 0 1 2 3.

417
Q

List down some of the features of ES6?

A
418
Q

What is ES6?

A

ES6 is the sixth edition of the javascript language and it was released in June 2015. It was initially known as ECMAScript 6 (ES6) and later renamed to ECMAScript 2015. Almost all the modern browsers support ES6 but for the old browsers there are many transpilers, like Babel.js etc.

419
Q

Can I redeclare let and const variables?

A
420
Q

Does the const variable make the value immutable?

A

No, the const variable doesn’t make the value immutable. But it disallows subsequent assignments(i.e, You can declare with assignment but can’t assign another value later)

const userList = [];
userList.push(“John”); // Can mutate even though it can’t re-assign
console.log(userList); // [‘John’]

421
Q

What are default parameters in JS?

A

In ES5, we need to depend on logical OR operators to handle default values of function parameters. Whereas in ES6, Default function parameters feature allows parameters to be initialized with default values if no value or undefined is passed. Let’s compare the behavior with an examples,

422
Q

What are template literals in JS?

A

Template literals or template strings are string literals allowing embedded expressions. These are enclosed by the back-tick (`) character instead of double or single quotes. In ES6, this feature enables using dynamic expressions as below,

423
Q

How do you write multi-line strings in template literals?

A
424
Q

What are nesting templates in JS?

A
425
Q

What are tagged templates in JS?

A
426
Q

What are raw strings in JS?

A
427
Q

What is destructuring assignment in JS?

A
428
Q

What are default values in destructuring assignment?

A
429
Q

How do you swap variables in destructuring assignment?

A

If you don’t use destructuring assignment, swapping two values requires a temporary variable. Whereas using a destructuring feature, two variable values can be swapped in one destructuring expression. Let’s swap two number variables in array destructuring assignment,

var x = 10,
y = 20;

[x, y] = [y, x];
console.log(x); // 20
console.log(y); // 10

430
Q

What are enhanced object literals?

A
431
Q

What are dynamic imports?

A

The dynamic imports using import() function syntax allows us to load modules on demand by using promises or the async/await syntax. Currently this feature is in stage4 proposal. The main advantage of dynamic imports is reduction of our bundle’s sizes, the size/payload response of our requests and overall improvements in the user experience. The syntax of dynamic imports would be as below,

import(“./Module”).then((Module) => Module.method());

432
Q

What are the use cases for dynamic imports?

A
433
Q

What are typed arrays in JS?

A
434
Q

What are the advantages of module loaders?

A

The module loaders provides the below features,

  1. Dynamic loading
  2. State isolation
  3. Global namespace isolation
  4. Compilation hooks
  5. Nested virtualization
435
Q

What is collation in JS?

A

Collation is used for sorting a set of strings and searching within a set of strings. It is parameterized by locale and aware of Unicode. Let’s take comparison and sorting features,

  1. Comparison:

var list = [“ä”, “a”, “z”]; // In German, “ä” sorts with “a” Whereas in Swedish, “ä” sorts after “z”
var l10nDE = new Intl.Collator(“de”);
var l10nSV = new Intl.Collator(“sv”);
console.log(l10nDE.compare(“ä”, “z”) === -1); // true
console.log(l10nSV.compare(“ä”, “z”) === +1); // true

  1. Sorting:
    var list = [“ä”, “a”, “z”]; // In German, “ä” sorts with “a” Whereas in Swedish, “ä” sorts after “z”
    var l10nDE = new Intl.Collator(“de”);
    var l10nSV = new Intl.Collator(“sv”);
    console.log(list.sort(l10nDE.compare)); // [ “a”, “ä”, “z” ]
    console.log(list.sort(l10nSV.compare)); // [ “a”, “z”, “ä” ]
436
Q

What is for…of statement in JS?

A

The for…of statement creates a loop iterating over iterable objects or elements such as built-in String, Array, Array-like objects (like arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. The basic usage of for…of statement on arrays would be as below,

437
Q

What is the output of below spread operator array?

[…“John Resig”];

A

The output of the array is [‘J’, ‘o’, ‘h’, ‘n’, ‘’, ‘R’, ‘e’, ‘s’, ‘i’, ‘g’] Explanation: The string is an iterable type and the spread operator within an array maps every character of an iterable to one element. Hence, each character of a string becomes an element within an Array.

438
Q

Is PostMessage secure?

A

Yes, postMessages can be considered very secure as long as the programmer/developer is careful about checking the origin and source of an arriving message. But if you try to send/receive a message without verifying its source will create cross-site scripting attacks.

439
Q

What are the problems with postmessage target origin as wildcard?

A

The second argument of postMessage method specifies which origin is allowed to receive the message. If you use the wildcard “*” as an argument then any origin is allowed to receive the message. In this case, there is no way for the sender window to know if the target window is at the target origin when sending the message. If the target window has been navigated to another origin, the other origin would receive the data. Hence, this may lead to XSS vulnerabilities.

targetWindow.postMessage(message, “*”);

440
Q

How do you avoid receiving postMessages from attackers?

A

Since the listener listens for any message, an attacker can trick the application by sending a message from the attacker’s origin, which gives an impression that the receiver received the message from the actual sender’s window. You can avoid this issue by validating the origin of the message on the receiver’s end using the “message.origin” attribute. For examples, let’s check the sender’s origin http://www.some-sender.com on receiver side www.some-receiver.com,

//Listener on http://www.some-receiver.com/
window.addEventListener(“message”, function(message){
if(/^http://www.some-sender.com$/.test(message.origin)){
console.log(‘You received the data from valid sender’, message.data);
}
});

441
Q

Can I avoid using postMessages completely in JS?

A

You cannot avoid using postMessages completely(or 100%). Even though your application doesn’t use postMessage considering the risks, a lot of third party scripts use postMessage to communicate with the third party service. So your application might be using postMessage without your knowledge.

442
Q

Is postMessages synchronous?

A

The postMessages are synchronous in IE8 browser but they are asynchronous in IE9 and all other modern browsers (i.e, IE9+, Firefox, Chrome, Safari).Due to this asynchronous behaviour, we use a callback mechanism when the postMessage is returned.

443
Q

What paradigm is Javascript?

A

JavaScript is a multi-paradigm language, supporting imperative/procedural programming, Object-Oriented Programming and functional programming. JavaScript supports Object-Oriented Programming with prototypical inheritance.

444
Q

What is the difference between internal and external javascript?

A

Internal JavaScript: It is the source code within the script tag.

External JavaScript: The source code is stored in an external file(stored with .js extension) and referred with in the tag.

445
Q

Is JavaScript faster than server side script?

A

Yes, JavaScript is faster than server side scripts. Because JavaScript is a client-side script it does not require any web server’s help for its computation or calculation. So JavaScript is always faster than any server-side script like ASP, PHP, etc.

446
Q

How do you get the status of a checkbox in JS?

A

You can apply the checked property on the selected checkbox in the DOM. If the value is true it means the checkbox is checked, otherwise it is unchecked. For example, the below HTML checkbox element can be access using javascript as below:

<input></input> Agree the
conditions<br></br>

console.log(document.getElementById(‘checkboxname’).checked); // true or false

447
Q

What is the purpose of double tilde operator in JS?

A

The double tilde operator(~~) is known as double NOT bitwise operator. This operator is a slightly quicker substitute for Math.floor().

448
Q

How do you convert character to ASCII code in JS?

A
449
Q

What is ArrayBuffer in JS?

A
450
Q

What is the output of below string expression?

console.log(“Welcome to JS world”[0]);

A

The output of the above expression is “W”. Explanation: The bracket notation with specific index on a string returns the character at a specific location. Hence, it returns the character “W” of the string. Since this is not supported in IE7 and below versions, you may need to use the .charAt() method to get the desired result.

451
Q

What is the purpose of Error object?

A
452
Q

What is the purpose of EvalError object?

A

// “Eval function error”, “EvalError”, “someFile.js”

453
Q

What are the list of cases error thrown from non-strict mode to strict mode?

A
454
Q

Do all objects have prototypes in JS?

A

No. All objects have prototypes except for the base object which is created by the user, or an object that is created using the new keyword.

455
Q

What is the difference between a parameter and an argument in JS?

A

Parameter is the variable name of a function definition whereas an argument represents the value given to a function when it is invoked. Let’s explain this with a simple function

456
Q

What is the purpose of some() method in arrays in jS?

A

The some() method is used to test whether at least one element in the array passes the test implemented by the provided function. The method returns a boolean value. Let’s take an example to test for any odd elements,

457
Q

How do you combine two or more arrays in JS?

A
458
Q

What is a Shallow Copy re: objects?

A

There are two ways to copy an object,

Shallow Copy: Shallow copy is a bitwise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

459
Q

What is a Deep Copy re: objects?

A

Deep copy: A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

460
Q

How do you create specific number of copies of a string in JS?

A

The repeat() method is used to construct and return a new string which contains the specified number of copies of the string on which it was called, concatenated together. Remember that this method has been added to the ECMAScript 2015 specification. Let’s take an example of Hello string to repeat it 4 times,

“Hello”.repeat(4); // ‘HelloHelloHelloHello’

461
Q

How do you return all matching strings against a regular expression in JS?

A

The matchAll() method can be used to return an iterator of all results matching a string against a regular expression. For example, the below example returns an array of matching string results against a regular expression,

462
Q

How do you trim a string at the beginning or ending in JS?

A

The trim method of string prototype is used to trim on both sides of a string. But if you want to trim especially at the beginning or ending of the string then you can use trimStart/trimLeft and trimEnd/trimRight methods. Let’s see an example of these methods on a greeting message,

463
Q

What is the output of below console statement with unary operator?
ex. console.log(+”Hello”);

A

The output of the above console log statement returns NaN. Because the element is prefixed by the unary operator and the JavaScript interpreter will try to convert that element into a number type. Since the conversion fails, the value of the statement results in NaN value.

464
Q

Does javascript use mixins?

A

Mixin is a generic object-oriented programming term - is a class containing methods that can be used by other classes without a need to inherit from it. In JavaScript we can only inherit from a single object. ie. There can be only one [[prototype]] for an object.

But sometimes we require to extend more than one, to overcome this we can use Mixin which helps to copy methods to the prototype of another class.

Say for instance, we’ve two classes User and CleanRoom. Suppose we need to add CleanRoom functionality to User, so that user can clean the room at demand. Here’s where concept called mixins comes into picture.

465
Q

What is a thunk function?

A

A thunk is just a function which delays the evaluation of the value. It doesn’t take any arguments but gives the value whenever you invoke the thunk. i.e, It is used not to execute now but it will be sometime in the future. Let’s take a synchronous example,

466
Q

What are asynchronous thunks?

A
467
Q

What is the output of below function calls?

A

Output:

The output is 40 and NaN. Remember that diameter is a regular function, whereas the value of perimeter is an arrow function. The this keyword of a regular function(i.e, diameter) refers to the surrounding scope which is a class(i.e, Shape object). Whereas this keyword of perimeter function refers to the surrounding scope which is a window object. Since there is no radius property on window objects it returns an undefined value and the multiple of number value returns NaN value.

468
Q

How to remove all line breaks from a string in JS?

A

The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.

469
Q

What is the difference between reflow and repaint

A

A repaint occurs when changes are made which affect the visibility of an element, but not its layout. Examples of this include outline, visibility, or background color. A reflow involves changes that affect the layout of a portion of the page (or the whole page). Resizing the browser window, changing the font, content changing (such as user typing text), using JavaScript methods involving computed styles, adding or removing elements from the DOM, and changing an element’s classes are a few of the things that can trigger reflow. Reflow of an element causes the subsequent reflow of all child and ancestor elements as well as any elements following it in the DOM.

470
Q

What happens with negating an array in JS?

A

Negating an array with ! character will coerce the array into a boolean. Since Arrays are considered to be truthy So negating it will return false.

console.log(![]); // false

471
Q

What happens if we add two arrays in JS?

A

If you add two arrays together, it will convert them both to strings and concatenate them. For example, the result of adding arrays would be as below,

472
Q

What is the output of prepend additive operator on falsy values?

A
473
Q

How do you create self string using special characters in jS?

A
474
Q

How do you remove falsy values from an array in JS?

A

You can apply the filter method on the array by passing Boolean as a parameter. This way it removes all falsy values(0, undefined, null, false and “”) from the array.

const myArray = [false, null, 1, 5, undefined];
myArray.filter(Boolean); // [1, 5] // is same as myArray.filter(x => x);

475
Q

How do you get unique values of an array in JS?

A

You can get unique values of an array with the combination of Set and rest expression/spread(…) syntax.

console.log([…new Set([1, 2, 4, 4, 3])]); // [1, 2, 4, 3]

476
Q

What is destructuring aliases in JS?

A

Sometimes you would like to have a destructured variable with a different name than the property name. In that case, you’ll use a : newName to specify a name for the variable. This process is called destructuring aliases.

477
Q

How do you map the array values without using map method in JS?

A
478
Q

How do you empty an array in JS?

A
479
Q

How do you rounding numbers to certain decimals in JS?

A

You can round numbers to a certain number of decimals using toFixed method from native javascript.

let pie = 3.141592653;
pie = pie.toFixed(3); // 3.142

480
Q

What is the easiest way to convert an array to an object in JS?

A

You can convert an array to an object with the same data using spread(…) operator.

var fruits = [“banana”, “apple”, “orange”, “watermelon”];
var fruitsObject = { …fruits };
console.log(fruitsObject); // {0: “banana”, 1: “apple”, 2: “orange”, 3: “watermelon”}

481
Q

How do you create an array with some data in JS?

A

You can create an array with some data or an array with the same values using fill method.

var newArray = new Array(5).fill(“0”);
console.log(newArray); // [“0”, “0”, “0”, “0”, “0”]

482
Q

What are the placeholders from console object?

A

Below are the list of placeholders available from console object,

%o — It takes an object,
%s — It takes a string,
%d — It is used for a decimal or integer These placeholders can be represented in the console.log as below

const user = { name: “John”, id: 1, city: “Delhi” };
console.log(
“Hello %s, your details %o are available in the object form”,
“John”,
user
); // Hello John, your details {name: “John”, id: 1, city: “Delhi”} are available in object

483
Q

Is it possible to add CSS to console messages?

A

Yes, you can apply CSS styles to console messages similar to html text on the web page.

484
Q

What is the purpose of dir method of console object?

A
485
Q

Is it possible to debug HTML elements in console?

A
486
Q

How do you display data in a tabular format using console object?

A
487
Q

How do you verify that an argument is a Number or not?

A
488
Q

How do you create copy to clipboard button?

A
489
Q

What is the shortcut to get timestamp?

A
490
Q

How do you flatten multi dimensional arrays?

A

Flattening bi-dimensional arrays is trivial with Spread operator.

const biDimensionalArr = [11, [22, 33], [44, 55], [66, 77], 88, 99];
const flattenArr = [].concat(…biDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]

But you can make it work with multi-dimensional arrays by recursive calls,

function flattenMultiArray(arr) {
const flattened = [].concat(…arr);
return flattened.some((item) => Array.isArray(item))
? flattenMultiArray(flattened)
: flattened;
}
const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]

Also you can use the flat method of Array.

const arr = [1, [2, 3], 4, 5, [6, 7]];
const fllattenArr = arr.flat(); // [1, 2, 3, 4, 5, 6, 7]

// And for multiDemensional arrays
const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
const oneStepFlat = multiDimensionalArr.flat(1); // [11, 22, 33, 44, [55, 66, [77, [88]], 99]]
const towStep = multiDimensionalArr.flat(2); // [11, 22, 33, 44, 55, 66, [77, [88]], 99]
const fullyFlatArray = multiDimensionalArr.flat(Infinity); // [11, 22, 33, 44, 55, 66, 77, 88, 99]

491
Q

What is the easiest multi condition checking?

A
492
Q

How do you capture browser back button?

A

NOTE: In the preceeding code, When the box element clicked, its background color appears in blue color and changed to while color upon clicking the browser back button using popstate event handler. The state property of popstate contains the copy of history entry’s state object.

⬆ Back to Top

493
Q

How do you disable right click in the web page?

A

The right click on the page can be disabled by returning false from the oncontextmenu attribute on the body element.

<body></body>

494
Q

What are wrapper objects?

A

Primitive Values like string,number and boolean don’t have properties and methods but they are temporarily converted or coerced to an object(Wrapper object) when you try to perform actions on them. For example, if you apply toUpperCase() method on a primitive string value, it does not throw an error but returns uppercase of the string.

let name = “john”;

console.log(name.toUpperCase()); // Behind the scenes treated as console.log(new String(name).toUpperCase());

i.e, Every primitive except null and undefined have Wrapper Objects and the list of wrapper objects are String,Number,Boolean,Symbol and BigInt.

495
Q

What is AJAX?

A

AJAX stands for Asynchronous JavaScript and XML and it is a group of related technologies(HTML, CSS, JavaScript, XMLHttpRequest API etc) used to display data asynchronously. i.e. We can send data to the server and get data from the server without reloading the web page.

496
Q

What are the different ways to deal with Asynchronous Code in JS?

A

Below are the list of different ways to deal with Asynchronous code.

  1. Callbacks
  2. Promises
  3. Async/await
  4. Third-party libraries such as async.js,bluebird etc
497
Q

How to cancel a fetch request?

A
498
Q

What is web speech API?

A
499
Q

What is minimum timeout throttling?

A

Both browser and NodeJS javascript environments throttles with a minimum delay that is greater than 0ms. That means even though setting a delay of 0ms will not happen instantaneously. Browsers: They have a minimum delay of 4ms. This throttle occurs when successive calls are triggered due to callback nesting(certain depth) or after a certain number of successive intervals. Note: The older browsers have a minimum delay of 10ms. Nodejs: They have a minimum delay of 1ms. This throttle happens when the delay is larger than 2147483647 or less than 1. The best example to explain this timeout throttling behavior is the order of below code snippet.

500
Q

How do you implement zero timeout in modern browsers?

A

You can’t use setTimeout(fn, 0) to execute the code immediately due to minimum delay of greater than 0ms. But you can use window.postMessage() to achieve this behavior.

501
Q

What are tasks in event loop?

A

A task is any javascript code/program which is scheduled to be run by the standard mechanisms such as initially starting to run a program, run an event callback, or an interval or timeout being fired. All these tasks are scheduled on a task queue. Below are the list of use cases to add tasks to the task queue,

  1. When a new javascript program is executed directly from console or running by the
     element, the task will be added to the task queue.
  2. When an event fires, the event callback added to task queue
  3. When a setTimeout or setInterval is reached, the corresponding callback added to task queue
502
Q

What is microtask?

A

Microtask is the javascript code which needs to be executed immediately after the currently executing task/microtask is completed. They are kind of blocking in nature. i.e, The main thread will be blocked until the microtask queue is empty. The main sources of microtasks are Promise.resolve, Promise.reject, MutationObservers, IntersectionObservers etc

Note: All of these microtasks are processed in the same turn of the event loop.

503
Q

What are different event loops?

A

In JavaScript, there are multiple event loops that can be used depending on the context of your application. The most common event loops are:

The Browser Event Loop
The Node.js Event Loop

  • Browser Event Loop: The Browser Event Loop is used in client-side JavaScript applications and is responsible for handling events that occur within the browser environment, such as user interactions (clicks, keypresses, etc.), HTTP requests, and other asynchronous actions.
  • The Node.js Event Loop is used in server-side JavaScript applications and is responsible for handling events that occur within the Node.js runtime environment, such as file I/O, network I/O, and other asynchronous actions.

⬆ Back to Top

504
Q

What is the purpose of queueMicrotask?

A
505
Q

How do you use javascript libraries in typescript file?

A
506
Q

What are the differences between promises and observables?

A
507
Q

What is heap?

A

Heap(Or memory heap) is the memory location where objects are stored when we define variables. i.e, This is the place where all the memory allocations and de-allocation take place. Both heap and call-stack are two containers of JS runtime. Whenever runtime comes across variables and function declarations in the code it stores them in the Heap.

508
Q

What is an event table?

A

Event Table is a data structure that stores and keeps track of all the events which will be executed asynchronously like after some time interval or after the resolution of some API requests. i.e Whenever you call a setTimeout function or invoke async operation, it is added to the Event Table. It doesn’t not execute functions on it’s own. The main purpose of the event table is to keep track of events and send them to the Event Queue as shown in the below diagram.

509
Q

What is a microTask queue?

A

Microtask Queue is the new queue where all the tasks initiated by promise objects get processed before the callback queue. The microtasks queue are processed before the next rendering and painting jobs. But if these microtasks are running for a long time then it leads to visual degradation.

510
Q

What is the difference between shim and polyfill?

A

A shim is a library that brings a new API to an older environment, using only the means of that environment. It isn’t necessarily restricted to a web application. For example, es5-shim.js is used to emulate ES5 features on older browsers (mainly pre IE9). Whereas polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. In a simple sentence, A polyfill is a shim for a browser API.

511
Q

How do you detect primitive or non primitive value type?

A
512
Q

What is babel?

A

Babel is a JavaScript transpiler to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Some of the main features are listed below,

  1. Transform syntax
  2. Polyfill features that are missing in your target environment (using @babel/polyfill)
  3. Source code transformations (or codemods)
513
Q

Is Node.js completely single threaded?

A

Node is a single thread, but some of the functions included in the Node.js standard library(e.g, fs module functions) are not single threaded. i.e, Their logic runs outside of the Node.js single thread to improve the speed and performance of a program.

514
Q

What are the common use cases of observables?

A

Some of the most common use cases of observables are web sockets with push notifications, user input changes, repeating intervals, etc

515
Q

What is RxJS?

A

RxJS (Reactive Extensions for JavaScript) is a library for implementing reactive programming using observables that makes it easier to compose asynchronous or callback-based code. It also provides utility functions for creating and working with observables.

516
Q

What is the difference between Function constructor and function declaration?

A

The functions which are created with Function constructor do not create closures to their creation contexts but they are always created in the global scope. i.e, the function can access its own local variables and global scope variables only. Whereas function declarations can access outer function variables(closures) too.

517
Q

What is the easiest way to resize an array?

A
518
Q

What is a Short circuit condition?

A
519
Q

What is an observable?

A

An Observable is basically a function that can return a stream of values either synchronously or asynchronously to an observer over time. The consumer can get the value by calling subscribe() method. Let’s look at a simple example of an Observable

520
Q

What is the difference between function and class declarations?

A
521
Q

What is an async function in JS?

A
522
Q

How do you prevent promises swallowing errors?

A

While using asynchronous code, JavaScript’s ES6 promises can make your life a lot easier without having callback pyramids and error handling on every second line. But Promises have some pitfalls and the biggest one is swallowing errors by default.

  1. Add catch block at the end of each chain
  2. Add done method
  3. Extend ES6 Promises by Bluebird
523
Q

How do you prevent the following code from swallowing errors using catch block?

A
524
Q

How do you prevent the following code from swallowing errors using done method?

A
525
Q

How do you prevent the following code from swallowing errors using ES6 Promises by Bluebird ?

A
526
Q

What is deno?

A

Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 JavaScript engine and the Rust programming language.

527
Q

How do you make an object iterable in javascript?

A

By default, plain objects are not iterable. But you can make the object iterable by defining a Symbol.iterator property on it.

528
Q

What is a Proper Tail Call?

A

First, we should know about tail call before talking about “Proper Tail Call”. A tail call is a subroutine or function call performed as the final action of a calling function. Whereas Proper tail call(PTC) is a technique where the program or code will not create additional stack frames for a recursion when the function call is a tail call.

For example, the below classic or head recursion of factorial function relies on stack for each step. Each step need to be processed upto n * factorial(n - 1)

529
Q

How do you check an object is a promise or not?

A
530
Q

How to detect if a function is called as constructor?

A
531
Q

What are the differences between arguments object and rest parameter?

A
532
Q

What are the differences between spread operator and rest parameter?

A

Rest parameter collects all remaining elements into an array. Whereas Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. i.e, Rest parameter is opposite to the spread operator.

533
Q

What are the different kinds of generators?

A

There are five kinds of generators:

  1. Generator function declaration:
  2. Generator function expressions:
  3. Generator method definitions in object literals:
  4. Generator method definitions in class:
  5. Generator as a computed property:
534
Q

Example of a Generator function declaration:

A
535
Q

Example of a Generator function expressions

A
536
Q

Example of a Generator method definitions in class:

A
537
Q

Example of a Generator method definitions in object literals:

A
538
Q

Example of a Generator as a computed property

A
539
Q

What are the built-in iterables

A
540
Q

What are the differences between for…of and for…in statements?

A
541
Q

How do you define instance and non-instance properties

A
542
Q

What is the difference between isNaN and Number.isNaN?

A
543
Q

How to invoke an IIFE without any extra brackets?

A
544
Q

Is that possible to use expressions in switch cases?

A
545
Q

What is the easiest way to ignore promise errors?

A
546
Q

How do style the console output using CSS?

A
547
Q

What is nullish coalescing operator (??)?

A
548
Q

How do you group and nest console output?

A
549
Q

What is the difference between dense and sparse arrays?

A
550
Q

What are the different ways to create sparse arrays?

A
551
Q

What is the difference between setTimeout, setImmediate and process.nextTick?

A
552
Q

How do you reverse an array without modifying original array?

A
553
Q

How do you create custom HTML element?

A
554
Q

What is global execution context?

A
555
Q

What is function execution context?

A

Whenever a function is invoked, the JavaScript engine creates a different type of Execution Context known as a Function Execution Context (FEC) within the Global Execution Context (GEC) to evaluate and execute the code within that function.

556
Q

What is debouncing?

A

Debouncing is a programming pattern that allows delaying execution of some piece of code until a specified time to avoid unnecessary CPU cycles, API calls and improve performance. The debounce function make sure that your code is only triggered once per user input. The common usecases are Search box suggestions, text-field auto-saves, and eliminating double-button clicks.

557
Q

What is throttling?

A
558
Q

What is optional chaining?

A
559
Q

What is an environment record?

A
560
Q

How to verify if a variable is an array?

A
561
Q

What is pass by value and pass by reference?

A
562
Q

What are the differences between primitives and non-primitives?

A
563
Q

How do you create your own bind method using either call or apply method?

A
564
Q

What are the differences between pure and impure functions?

A
565
Q

What is referential transparency?

A
566
Q

What are the possible side-effects in javascript?

A
567
Q

What are compose and pipe functions?

A

The “compose” and “pipe” are two techniques commonly used in functional programming to simplify complex operations and make code more readable. They are not native to JavaScript and higher-order functions. the compose() applies right to left any number of functions to the output of the previous function

568
Q

What is module pattern?

A
569
Q

What is Function Composition?

A
570
Q

How to use await outside of async function prior to ES2022?

A
571
Q

What is the purpose of the this keyword in JavaScript?

A
572
Q

What is the output of below code

A
573
Q

What is the output of below code:

A
574
Q

What is the output of below code:

A
575
Q

What is the output of below equality check:

A
576
Q

What is the output of below code:

A
577
Q

What is the output of below code:

A
578
Q

What is the output of below code

A
579
Q

What is the output of below code in latest Chrome:

A
580
Q

What is the output of below code:

A
581
Q

What is the output of below code:

A
582
Q

What is the output of below code in non-strict mode:

A
583
Q

What is the output of below code:

A
584
Q

What is the output of below code:

A
585
Q

What is the output of below code:

A
586
Q

What is the output of below code:

A
587
Q

What is the output of below code:

A
588
Q

What is the output of below code:

A
589
Q

What is the output of below code:

A
590
Q

What is the output of below code:

A
591
Q

What is the output of below code:

A
592
Q

What is the output of below code:

A
593
Q

What is the output of below code:

A
594
Q

What is the output of below code:

A
595
Q

What is the output of below code:

A
596
Q

What is the output of below code:

A
597
Q

What is the output of below code:

A
598
Q

What is the output of below code:

A
599
Q

What is the output of below code:

A
600
Q

What is the output of below code:

A
601
Q

What is the output of below code:

A
602
Q

What is the output of below code:

A
603
Q

What is the output of below code:

A
604
Q

What is the output of below code:

A
605
Q

What is the output of below code:

A
606
Q

What is the output of below code

A
607
Q

What is the output of below code:

A
608
Q

What is the output of below code:

A