JavaScript Interview Questions Flashcards
study
To know the type of a JavaScript variable you use…
we can use the typeof operator.
What are the Primative Types
- String
- Number
- BigInt
- Boolean
- Undefined
6.Null
7.Symbol
Primitive data types can store only a single value.
String
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
Number
It represents a number and can be written with or without decimals.
var x = 3; //without decimal
var y = 3.6; //with decimal
BigInt
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;
Boolean
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
Undefined
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
Null
It represents a non-existent or a invalid value.
var z = null;
Symbol
It is a new data type introduced in the ES6 version of javascript. It is used to store an anonymous and unique value.
Non-primitive Types
To store multiple and complex values, non-primitive data types are used.
- Object
Note- It is important to remember that any data type that is not a primitive data type, is of Object type in javascript.
Object
// 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];
Explain Hoisting in javascript.
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 do you avoid hoisting in javascript?
To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:
whats the difference between variable initializations vs declarations?
Variable initializations are not hoisted, only variable declarations are hoisted:
Why do we use the word “debugger” in javascript?
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.
Difference between “ == “ and “ === “ operators.
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”
Difference between var and let keyword in javascript.
Some differences are:
- From the very beginning, the ‘var’ keyword was used in JavaScript programming whereas the keyword ‘let’ was just added in 2015.
- 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.
- 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.
Explain Implicit Type Coercion in javascript.
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.
String coercion
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
Boolean Coercion
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.
If statements:
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)
Logical operators:
Logical operators in javascript, unlike operators in other programming languages, do not return true or false. They always return one of the operands.
OR ( | | ) operator
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)
}
AND ( && ) operator
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)
}
Equality Coercion
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.
Is javascript a statically typed or a dynamically typed language?
JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to a statically typed language, where the type of a variable is checked during compile-time.
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!”;
What is NaN property in JavaScript?
NaN property represents the “Not-a-Number” value. It indicates a value that is not a legal number.
typeof of NaN will return a Number.
To check if a value is NaN, we use the isNaN() function,
Note- isNaN() function converts the given value to a Number type, and then equates to NaN.
isNaN(“Hello”) // Returns true
isNaN(345) // Returns false
isNaN(‘1’) // Returns false, since ‘1’ is converted to Number type which results in 0 ( a number)
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number)
isNaN(false) // Returns false
isNaN(undefined) // Returns true
Explain passed by value and passed by reference.
In JavaScript, primitive data types are passed by value and non-primitive data types are passed by reference.
what happens when we create a variable and assign a value to it?
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 does the assignment operator (=) behave with primitive types
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 does the assignment operator (=) behave with non-primitive types?
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).
What is an Immediately Invoked Function in JavaScript?
An Immediately Invoked Function ( known as IIFE and pronounced as IIFY) is a function that runs as soon as it is defined.
Syntax of IIFE :
(function(){
// Do something;
})();
To understand IIFE, we need to understand the two sets of parentheses that are added while creating an IIFE :
- 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.
- 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.
What do you mean by strict mode in javascript and characteristics of javascript strict-mode?
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
- Duplicate arguments are not allowed by developers.
- In strict mode, you won’t be able to use the JavaScript keyword as a parameter or function name.
- The ‘use strict’ keyword is used to define strict mode at the start of the script. Strict mode is supported by all browsers.
- Engineers will not be allowed to create global variables in ‘Strict Mode.
Explain Higher Order Functions in javascript.
Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.
Higher-order functions are a result of functions being first-class citizens in javascript.
Examples of higher-order functions:
function higherOrder(fn) {
fn();
}
higherOrder(function() { console.log(“Hello world”) });
function higherOrder2() {
return function() {
return “Do something”;
}
}
var x = higherOrder2();
x() // Returns “Do something”
Explain “this” keyword.
The “this” keyword refers to the object that the function is a property of.
The value of the “this” keyword will always depend on the object that is invoking the function.
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.
What do you mean by Self Invoking Functions?
Without being requested, a self-invoking expression is automatically invoked (initiated). If a function expression is followed by (), it will execute automatically. A function declaration cannot be invoked by itself.
Normally, we declare a function and call it, however, anonymous functions may be used to run a function automatically when it is described and will not be called again. And there is no name for these kinds of functions.
call()
It’s a predefined method in javascript.
This method invokes a method (function) by specifying the owner object.
apply()
The apply method is similar to the call() method. The only difference is that,
call() method takes arguments separately whereas, apply() method takes arguments as an array.
bind():
This method returns a new function, where the value of “this” keyword will be bound to the owner object, which is provided as a parameter.
What is the difference between exec () and test () methods in javascript?
- test () and exec () are RegExp expression methods used in javascript.
- We’ll use exec () to search a string for a specific pattern, and if it finds it, it’ll return the pattern directly; else, it’ll return an ‘empty’ result.
- We will use a test () to find a string for a specific pattern. It will return the Boolean value ‘true’ on finding the given text otherwise, it will return ‘false’.
What is currying in JavaScript?
Currying is an advanced technique to transform a function of arguments n, to n functions of one or fewer arguments.
Example of a curried function:
function add (a) {
return function(b){
return a + b;
}
}
add(3)(4)
By using the currying technique, we do not change the functionality of a function, we just change the way it is invoked.
What are some advantages of using External JavaScript?
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:
- It allows web designers and developers to collaborate on HTML and javascript files.
- We can reuse the code.
- Code readability is simple in external javascript.
Global Scope
Variables or functions declared in the global namespace have global scope, which means all the variables and functions having global scope can be accessed from anywhere inside the code.
Function Scope:
Any variables or functions declared inside a function have local/function scope, which means that all the variables and functions declared inside a function, can be accessed from within the function and not outside of it.
Block Scope:
Block scope is related to the variables declared using let and const. Variables declared with var do not have block scope. Block scope tells us that any variable declared inside a block { }, can be accessed only inside that block and cannot be accessed outside of it.
Scope Chain
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.
Explain Closures in JavaScript.
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.
Mention some advantages of javascript.
There are many advantages of javascript. Some of them are:
- 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.
- Javascript is a simple language to learn.
- Web pages now have more functionality because of Javascript.
- To the end-user, Javascript is quite quick.
What are object prototypes?
All javascript objects inherit properties from a prototype. For example,
- Date objects inherit properties from the Date prototype
- Math objects inherit properties from the Math prototype
- Array objects inherit properties from the Array prototype.
- On top of the chain is Object.prototype. Every prototype inherits properties and methods from the Object.prototype.
- A prototype is a blueprint of an object. The prototype allows us to use properties and methods on an object even if the properties and methods do not exist on the current object.
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.
What are callbacks?
A callback is a function that will be executed after another function gets executed. In javascript, functions are treated as first-class citizens, they can be used as an argument of another function, can be returned by another function, and can be used as a property of an object.
Functions that are used as an argument to another function are called callback functions.
——— example
function divideByHalf(sum){
console.log(Math.floor(sum / 2));
}
function multiplyBy2(sum){
console.log(sum * 2);
}
function operationOnSum(num1,num2,operation){
var sum = num1 + num2;
operation(sum);
}
operationOnSum(3, 3, divideByHalf); // Outputs 3
- 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.
What are the types of errors in javascript?
There are two types of errors in javascript.
- 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.
- 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.
What is memoization?
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.
What is recursion in a programming language?
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
What is the use of a constructor function in javascript?
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.
What is DOM?
- 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:
Which method is used to retrieve a character from a certain index?
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.
What do you mean by BOM?
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.
What is the distinction between client-side and server-side JavaScript?
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.
What is the biggest difference between arrow functions and the traditional function expression?
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.
What are arrow functions?
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.
What do mean by prototype design pattern?
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.
Differences between declaring variables using var, let and const.
- The variables declared with the let keyword in the global scope behave just like the variable declared with the var keyword in the global scope.
- Variables declared in the global scope with var and let keywords can be accessed from anywhere in the code.
- But, there is one difference! Variables that are declared with the var keyword in the global scope are added to the window/global object. Therefore, they can be accessed using window.variableName.
- Whereas, the variables declared with the let keyword are not added to the global object, therefore, trying to access such variables using window.variableName results in an error.
var vs let in functional scope
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.
What is a block in JavaScript?
In javascript, a block means the code written inside the curly braces {}.
var vs let in block scope
- Variables declared with var keyword do not have block scope. It means a variable declared in block scope {} with the var keyword is the same as declaring the variable in the global scope.
- Variables declared with let keyword inside the block scope cannot be accessed from outside of the block.
Const keyword
Variables with the const keyword behave exactly like a variable declared with the let keyword with only one difference, any variable declared with the const keyword cannot be reassigned.
——– example
const x = {name:”Vivek”};
x = {address: “India”}; // Throws an error
x.name = “Nikhil”; // No error is thrown
const y = 23;
y = 44; // Throws an error
In the code above, although we can change the value of a property inside the variable declared with const keyword, we cannot completely reassign the variable itself.
What is the rest parameter?
- 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:
Spread operator (…):
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’};
What are the key differences between rest parameter and spread operator?
- 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.
In JavaScript, how many different methods can you make an object?
In JavaScript, there are several ways to declare or construct an object.
- Object.
- using Class.
- create Method.
- Object Literals.
- using Function.
- Object Constructor.
What is the use of promises in javascript?
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 many states does a Promise object have?
Promise object has four states -
- Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.
- Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed.
- Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
- Settled - This state represents that the promise has been either rejected or fulfilled.
How is a promise created?
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 do you consume a promise?
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
What are classes in javascript?
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.
What are generator functions?
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.
Explain WeakSet in javascript.
In javascript, a Set is a collection of unique and ordered elements. Just like Set, WeakSet is also a collection of unique and ordered elements with some key differences:
- Weakset contains only objects and no other type.
- An object inside the weakset is referenced weakly. This means, that if the object inside the weakset does not have a reference, it will be garbage collected.
- ## Unlike Set, WeakSet only has three methods, add() , delete() and has() .const newSet = new Set([4, 5, 6, 7]);
console.log(newSet);// Outputs Set {4,5,6,7}
const newSet2 = new WeakSet([3, 4, 5]); //Throws an error
let obj1 = {message:”Hello world”};
const newSet3 = new WeakSet([obj1]);
console.log(newSet3.has(obj1)); // true
Why do we use callbacks?
A callback function is a method that is sent as an input to another function (now let us name this other function “thisFunction”), and it is performed inside the thisFunction after the function has completed execution.
JavaScript is a scripting language that is based on events. Instead of waiting for a reply before continuing, JavaScript will continue to run while monitoring for additional events. Callbacks are a technique of ensuring that a particular code does not run until another code has completed its execution.
Explain WeakMap in javascript.
In javascript, Map is used to store key-value pairs. The key-value pairs can be of both primitive and non-primitive types. WeakMap is similar to Map with key differences:
- The keys and values in weakmap should always be an object.
- If there are no references to the object, the object will be garbage collected.
const map1 = new Map();
map1.set(‘Value’, 1);
const map2 = new WeakMap();
map2.set(‘Value’, 2.3); // Throws an error
let obj = {name:”Vivek”};
const map3 = new WeakMap();
map3.set(obj, {age:23});
What is Object Destructuring?
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
Difference between prototypal and classical inheritance
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.
What is a Temporal Dead Zone?
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.
What do you mean by JavaScript Design Patterns?
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.
Creational Design Pattern:
The object generation mechanism is addressed by the JavaScript Creational Design Pattern. They aim to make items that are appropriate for a certain scenario.
Structural Design Pattern:
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.
Behavioral Design Pattern:
This design pattern highlights typical patterns of communication between objects in JavaScript. As a result, the communication may be carried out with greater freedom.
Is JavaScript a pass-by-reference or pass-by-value language?
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.
Difference between Async/Await and Generators usage to achieve the same functionality.
- 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.
What are the primitive data types in JavaScript?
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:
- Boolean
- Undefined
- Null
- Number
- String
What is the role of deferred scripts in JavaScript?
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.
What has to be done in order to put Lexical Scoping into practice?
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.
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;
}
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.
Guess the outputs of the following codes:
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 do you create an Object using literal syntax?
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 do you create an Object using constructor?
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 do you create an Object using the create method?
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 do you create an Object using the Function constructor?
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 do you create an Object using the Function constructor with prototype?
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 do you create an Object using the Object’s assign method?
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 do you create an Object using ES6 Class syntax?
ES6 introduces class feature to create objects.
class Person {
constructor(name) {
this.name = name;
}
}
var object = new Person(“Sudheer”);
How do you create an Object using the Singleton pattern?
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”;
})();
What is a prototype chain?
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.
What is the difference between Call, Apply and Bind?
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().
An example use of Call()
Call: The call() method invokes a function with a given this value and arguments provided one by one
An example use of Apply()
Apply: Invokes the function with a given this value and allows you to pass in arguments as an array
An example use of bind()
Bind: returns a new function, allowing you to pass any number of arguments
What is JSON and its common operations?
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
- Parsing: Converting a string to a native object
ex. –> JSON.parse(text); - Stringification: Converting a native object to a string so that it can be transmitted across the network
ex. –> JSON.stringify(object);
What is the purpose of the array slice method?
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,
What is the purpose of the array splice() method?
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]
What is the difference between slice and splice?
How do you compare Object and Map?
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:
- 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.
- 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.
- 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.
- 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.
- 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.
- A Map may perform better in scenarios involving frequent addition and removal of key pairs.
What is the difference between == and === operators?
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,
- Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
- Two numbers are strictly equal when they are numerically equal, i.e., having the same number value. There are two special cases in this,
- NaN is not equal to anything, including NaN.
- Positive and negative zeros are equal to one another. - Two Boolean operands are strictly equal if both are true or both are false.
- Two objects are strictly equal if they refer to the same Object.
- Null and Undefined types are not equal with ===, but equal with == . i.e, null===undefined –> false, but null==undefined –> true
Some of the example which covers the above cases:
What are lambda expressions or arrow functions?
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,
What is a first class function in JavaScript?
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);
What is a first order function in JavaScript?
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!”);
What is a higher order function in JavaScript?
A higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.
What is the currying function in JavaScript?
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,
What is a unary function in JavaScript?
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
What is a pure function in JavaScript?
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.
What is the purpose of the let keyword in JS?
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)
What is the difference between let and var? (tabular format)
What is the difference between let and var? (code example)
What is the reason to choose the name let as a keyword in JS?
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 do you redeclare variables in a switch block without an error in JS?
What is the Temporal Dead Zone in JS?
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;
}
What is an IIFE (Immediately Invoked Function Expression)
How do you decode or encode a URL in JavaScript?
What is memoization in JavaScript?
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,
What is Hoisting in JavaScript?
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.
What are classes in ES6?
What are closures in JavaScript?
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.
- Own scope where variables defined between its curly brackets
- Outer function’s variables
- Global variables
What are modules in JavaScript?
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
Why do you need modules in JavaScript?
Below are the list of benefits using modules in javascript ecosystem
- Maintainability
- Reusability
- Namespacing
What is scope in javascript?
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.
What is a service worker in javascript?
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 do you manipulate DOM using a service worker?
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 do you reuse information across service worker restarts?
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.
What is IndexedDB?
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.
What is web storage?
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.
What is a post message?
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).
What is a Cookie?
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,
Why do you need a Cookie?
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.
What are the options in a cookie?
There are few below options available for a cookie,
- 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”; - 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 do you delete a cookie?
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.
What are the differences between cookie, local storage and session storage?
What is the main difference between localStorage and sessionStorage?
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 do you access web storage?
What are the methods available on session storage?
What is a storage event and its event handler?
Why do you need web storage?
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 do you check web storage browser support?
How do you check web workers browser support?
Give an example of a web worker.
What are the restrictions of web workers on DOM?
WebWorkers don’t have access to below javascript objects since they are defined in an external files
- Window object
- Document object
- Parent object
What is a promise?
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));
Why do you need a promise?
Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing cleaner code.
What are the three states of promise?
Promises have three states:
- Pending: This is an initial state of the Promise before an operation begins
- Fulfilled: This state indicates that the specified operation was completed.
- Rejected: This state indicates that the operation did not complete. In this case an error value will be thrown.
What is a callback function?
Why do we need callbacks?
What is a callback hell?
What are server-sent events?
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 do you receive server-sent event notifications?
How do you check browser support for server-sent events?
What are the events available for server sent events?
What are the main rules of promise?
A promise must follow a specific set of rules:
- A promise is an object that supplies a standard-compliant .then() method
- A pending promise may transition into either fulfilled or rejected state
- A fulfilled or rejected promise is settled and it must not transition into any other state.
- Once a promise is settled, the value must not change.
What is callback in callback?
What is promise chaining?
What is promise.all?
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}
))
What is the purpose of the race method in promise?
What is a strict mode in javascript?
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.
Why do you need strict mode?
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 do you declare strict mode?
What is the purpose of double exclamation?
What is the purpose of the delete operator?
What is typeof operator in JS?
What is undefined property in JS?
What is null value in JS?
What is the difference between null and undefined?
What is eval?
What is the difference between window and document in JS?
How do you access history in javascript?
How do you detect caps lock key turned on or not?
What is isNaN?
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
What are the differences between undeclared and undefined variables in JS?
What are global variables in JS?
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
What are the problems with global variables?
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.
What is NaN property in JS?
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”);
What is the purpose of isFinite function in JS?
What is an event flow in JS?
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)
What is event bubbling in JS?
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.
What is event capturing in JS?
Event capturing is a type of event propagation where the event is first captured by the outermost element, and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the innermost DOM element.
How do you submit a form using JavaScript?
How do you find operating system details in JS?
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);
What is the difference between document load and DOMContentLoaded events?
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images).
What is the difference between native, host and user objects in JS?
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.
What are the tools or techniques used for debugging JavaScript code?
You can use below tools or techniques for debugging javascript
- Chrome Devtools
- debugger statement
- Good old console.log statement
What are the pros and cons of promises over callbacks?
What is the difference between an attribute and a property?
What is same-origin policy?
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).
What is the purpose of void 0 in JS?
Is JavaScript a compiled or interpreted language?
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.
Is JavaScript a case-sensitive language?
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.
Is there any relation between Java and JavaScript?
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).
What are events in JS?
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,
- Web page has finished loading
- Input field was changed
- Button was clicked
Who created javascript?
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.
What is the use of preventDefault method in JS?
What is the use of stopPropagation method in JS?
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)
What are the steps involved in return false usage in JS?
The return false statement in event handlers performs the below steps,
- First it stops the browser’s default action or behaviour.
- It prevents the event from propagating the DOM
- Stops callback execution and returns immediately when called.
What is BOM?
What is the use of setTimeout?
What is the use of setInterval?
Why is JavaScript treated as Single threaded?
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.
What is an event delegation in JS?
What is ECMAScript?
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.
What is JSON?
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.
What are the syntax rules of JSON?
Below are the list of syntax rules of JSON
- The data is in name/value pairs
- The data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
What is the purpose JSON stringify?
How do you parse JSON string?
Why do you need JSON?
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.
What are PWAs?
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.
What is the purpose of clearTimeout method?
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.
What is the purpose of clearInterval method?
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 do you redirect new page in javascript?
How do you check whether a string contains a substring?
How do you validate an email in javascript?
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 do you get the current url with javascript?
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
What are the various url properties of location object?
How do get query string values in javascript?
How do you check if a key exists in an object in JS?
How do you loop through or enumerate javascript object?
How do you test for an empty object?
- 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
- 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
- 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({});
}
What is an arguments object in JS?
How do you make first letter of the string in an uppercase in JS?
What are the pros and cons of for loop in JS?
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 do you display the current date in javascript?
How do you compare two date objects in JS?
How do you check if a string starts with another string in JS?
How do you trim a string in javascript?
How do you add a key value pair in javascript
Is the !– notation represents a special operator in JS?
No,that’s not a special operator. But it is a combination of 2 standard operators one after the other,
- A logical not (!)
- 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 do you assign default values to variables?
How do you define multiline strings in JS?
What is an app shell model?
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.
Can we define properties for functions in JS?