Java Script
Java Script
development languages. It was designed to build dynamic web pages at first. A script
is a JS program that may be added to the HTML of any web page. When the page
loads, these scripts execute automatically.
A language that was originally designed to build dynamic web pages may now be run
on the server and on almost any device that has the JavaScript Engine installed.
After HTML and CSS, JavaScript is the third biggest web technology. JavaScript is a
scripting language that may be used to construct online and mobile apps, web
servers, games, and more. JavaScript is an object-oriented programming language
that is used to generate websites and applications. It was created with the intention of
being used in a browser. Even today, the server-side version of JavaScript known as
[Link] may be used to create online and mobile apps, real-time applications, online
streaming applications, and videogames. Javascript frameworks, often known as
inbuilt libraries, may be used to construct desktop and mobile programs. Developers
may save a lot of time on monotonous programming jobs by using these code
libraries, allowing them to focus on the production work of development.
Play
The InterviewBit team has compiled a thorough collection of top Javascript Interview
Questions and Answers to assist you in acing your interview and landing your
desired job as a Javascript Developer.
To know the type of a JavaScript variable, we can use the typeof operator.
1. Primitive types
String - It represents a series of characters and is written with quotes. A string can be
represented using a single or a double quote.
Example :
Example :
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.
Example :
Boolean - It represents a logical entity and can have only two values : true or false.
Booleans are generally used for conditional testing.
Example :
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.
Example :
Example :
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.
Example :
2. Non-primitive types
Primitive data types can store only a single value. To store multiple and complex
values, non-primitive data types are used.
Object - Used to store collection of data.
Example:
var obj1 = {
x: 43,
y: "Hello world!",
z: function(){
return this.x;
}
}
Note- It is important to remember that any data type that is not a primitive data
type, is of Object type in javascript.
Real-Life Problems
Create My Plan
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.
Example 1:
hoistedVariable = 3;
[Link](hoistedVariable); // outputs 3 even when the variable is
declared after it is initialized
var hoistedVariable;
Example 2:
hoistedFunction(); // Outputs " Hello world! " even when the function is
declared after calling
function hoistedFunction(){
[Link](" Hello world! ");
}
Example 3:
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;
[Link](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;
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.
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.
Example:
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"
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.
6. 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.
Example 1:
var x = 3;
var y = "3";
x + y // Returns "33"
Example 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:
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:
Example:
var x = 0;
var y = 23;
if(x) { [Link](x) } // The code inside this block will not run since
the value of x is 0(Falsy)
if(y) { [Link](y) } // The code inside this block will run since the
value of y is 23 (Truthy)
Logical operators:
OR ( | | ) operator - If the first value is truthy, then the first value is returned.
Otherwise, always the second value gets returned.
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.
Example:
var x = 220;
var y = "Hello";
var z = undefined;
if( x && y ){
[Link]("Code runs" ); // This block runs because x && y returns
"Hello" (Truthy)
}
if( x || z ){
[Link]("Code runs"); // This block runs because x || y returns
220(Truthy)
}
Equality Coercion
Equality coercion takes place when using ‘ == ‘ operator. As we have stated before
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.
Example:
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.
Example:
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.
For example, a variable that is assigned a number type can be converted to a string
type:
var a = 23;
var a = "Hello World!";
Topic Buckets
Mock Assessments
Reading Material
View Tracks
NaN property represents the “Not-a-Number” value. It indicates a value that is not a
legal number.
Note- isNaN() function converts the given value to a Number type, and then equates
to NaN.
In JavaScript, primitive data types are passed by value and non-primitive data
types are passed by reference.
For understanding passed by value and passed by reference, we need to understand
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.
Assign operator behaves differently when dealing with primitive and non-primitive data
types,
var y = 234;
var z = y;
In the above example, the assign operator knows that the value assigned to y is a
primitive type (number type in this case), so when the second line code executes,
where the value of y is assigned to z, the assign operator takes the value of y (234)
and allocates a new space in the memory and returns the address. Therefore, variable
z is not pointing to the location of variable y, instead, it is pointing to a new location in
the memory.
var z = y;
From the above example, we can see that 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.
[Link] = "Akki";
[Link](obj2);
From the above example, we can see that while passing non-primitive data types, the
assigned operator directly passes the address (reference).
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 :
(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.
To remove this error, we add the first set of parenthesis that tells the compiler that the
function is not a function declaration, instead, it’s a function expression.
(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;
})
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.
function higherOrder(fn) {
fn();
}
Interview Process
Try It Out
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.\
function doSomething() {
[Link](this);
}
doSomething();
What do you think the output of the above code will be?
The “this” keyword refers to the object that the function is a property of.
Since the function is invoked in the global context, the function is a property of the
global object.
Therefore, the output of the above code will be the global object. Since we ran the
above code inside the browser, the global object is the window object.
Example 2:
var obj = {
name: "vivek",
getName: function(){
[Link]([Link]);
}
}
[Link]();
In the above code, at the time of invocation, the getName function is a property of the
object obj , therefore, this keyword will refer to the object obj, and hence the output
will be “vivek”.
Example 3:
var obj = {
name: "vivek",
getName: function(){
[Link]([Link]);
}
Although the getName function is declared inside the object obj, at the time of
invocation, getName() is a property of obj2, therefore the “this” keyword will refer
to obj2.
The silly way to understand the “this” keyword is, whenever the function is invoked,
check the object before the dot. The value of this . keyword will always be the object
before the dot.
If there is no object before the dot-like in example1, the value of this keyword will be
the global object.
Example 4:
var obj1 = {
address : "Mumbai,India",
getAddress: function(){
[Link]([Link]);
}
}
Although in the code above, this keyword refers to the object obj2, obj2 does not have
the property “address”‘, hence the getAddress function throws an error.
Normally, we declare a function and call it, however, anonymous functions may be
used to run a function automatically when it is described and will not be called again.
And there is no name for these kinds of functions.
1. call():
function sayHello(){
return "Hello " + [Link];
}
var obj = {name: "Sandy"};
[Link](obj);
call() method allows an object to use the method (function) of another object.
Example 2:
var person = {
age: 23,
getAge: function(){
return [Link];
}
}
var person2 = {age: 54};
[Link](person2);
// Returns 54
function saySomething(message){
return [Link] + " is " + message;
}
var person4 = {name: "John"};
[Link](person4, "awesome");
// Returns "John is awesome"
apply()
The apply method is similar to the call() method. The only difference is that,
function saySomething(message){
return [Link] + " is " + message;
}
var person4 = {name: "John"};
[Link](person4, ["awesome"]);
2. bind():
This method returns a new function, where the value of “this” keyword will be bound
to the owner object, which is provided as a parameter.
Example with arguments:
var bikeDetails = {
displayDetails: function(registrationNumber,brandName){
return [Link]+ " , "+ "bike details: "+ registrationNumber + " , " +
brandName;
}
}
detailsOfPerson1();
//Returns Vivek, bike details: TS0122, Bullet
add(3)(4)
For Example, if we have a function f(a,b), then the function after currying, will be
transformed to f(a)(b).
function multiply(a,b){
return a*b;
}
function currying(fn){
return function(a){
return function(b){
return fn(a,b);
}
}
}
As one can see in the code above, we have transformed the function multiply(a,b) to
a function curriedMultiply , which takes in one parameter at a time.
External JavaScript is the JavaScript Code (script) written in a separate file with the
[Link], and then we link that file inside the <head> or <body> element of the
HTML file where the code is to be placed.
In general terms, the scope will let us know at a given part of code, what are variables
and functions we can or cannot access.
Global Scope
Local or Function Scope
Block Scope
Global Scope: Variables or functions declared in the global namespace have global
scope, which means all the variables and functions having global scope can be
accessed from anywhere inside the code.
function awesomeFunction(){
var a = 2;
Block Scope: Block scope is related to the variables declared using let and const.
Variables declared with var do not have block scope. Block scope tells us that any
variable declared inside a block { }, can be accessed only inside that block and cannot
be accessed outside of it.
{
let x = 45;
}
Scope Chain: JavaScript engine also uses Scope to find variables. Let’s understand
that using an example:
var y = 24;
function favFunction(){
var x = 667;
var anotherFavFunction = function(){
[Link](x); // Does not find x inside anotherFavFunction, so looks
for variable inside favFunction, outputs 667
}
anotherFavFunction();
yetAnotherFavFunction();
}
favFunction();
As you can see in the code above, if the javascript engine does not find the
variable in local scope, it tries to check for the variable in the outer scope. If the
variable does not exist in the outer scope, it tries to find the variable in the
global scope.
If the variable is not found in the global space as well, a reference error is thrown.
Closures are an ability of a function to remember the variables and functions that are
declared in its outer scope.
[Link] = function(){
return name;
}
}
function randomFunc(){
var obj1 = {name:"Vivian", age:45};
return function(){
[Link]([Link] + " is "+ "awesome"); // Has access to obj1 even
when the randomFunc function is executed
}
}
The function randomFunc() gets executed and returns a function when we assign it to
a variable:
initialiseClosure();
The line of code above outputs “Vivian is awesome” and this is possible because of
closure.
When the function randomFunc() runs, it seems that the returning function is using the
variable obj1 inside it:
This ability of a function to store a variable for further reference even after it is
executed is called Closure.
In the code above, as one can see, we have not defined any property or method called
push on the array “arr” but the javascript engine does not throw an error.
The reason is the use of prototypes. As we discussed before, Array objects inherit
properties from the Array prototype.
The javascript engine sees that the method push does not exist on the current array
object and therefore, looks for the method push inside the Array prototype and it finds
the method.
Whenever the property or method is not found on the current object, the javascript
engine will always try to look in its prototype and if it still does not exist, it looks inside
the prototype's prototype and so on.
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){
[Link]([Link](sum / 2));
}
function multiplyBy2(sum){
[Link](sum * 2);
}
function operationOnSum(num1,num2,operation){
var sum = num1 + num2;
operation(sum);
}
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.
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.
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.
Let’s understand memoization, by converting a simple function to a memoized
function:
Note- Memoization is used for expensive function calls but in the following example,
we are considering a simple function for understanding the concept of memoization
better.
function addTo256(num){
return num + 256;
}
addTo256(20); // Returns 276
addTo256(40); // Returns 296
addTo256(20); // Returns 276
In the code above, we have written a function that adds the parameter to 256 and
returns it.
When we are calling the function addTo256 again with the same parameter (“20” in
the case above), we are computing the result again for the same parameter.
Computing the result with the same parameter, again and again, is not a big deal in
the above case, but imagine if the function does some heavy-duty work, then,
computing the result again and again with the same parameter will lead to wastage of
time.
This is where memoization comes in, by using memoization we can store(cache) the
computed results based on the parameters. If the same parameter is used again while
invoking the function, instead of computing the result, we directly return the stored
(cached) value.
function memoizedAddTo256(){
var cache = {};
return function(num){
if(num in cache){
[Link]("cached value");
return cache[num]
}
else{
cache[num] = num + 256;
return cache[num];
}
}
}
var memoizedFunc = memoizedAddTo256();
In the code above, if we run the memoizedFunc function with the same parameter,
instead of computing the result again, it returns the cached result.
function add(number) {
if (number <= 0) {
return 0;
} else {
return number + add(number - 1);
}
}
add(3) => 3 + add(2)
3 + 2 + add(1)
3 + 2 + 1 + add(0)
3 + 2 + 1 + 0 = 6
The following function calculates the sum of all the elements in an array by using
recursion:
function computeSum(arr){
if([Link] === 1){
return arr[0];
}
else{
return [Link]() + computeSum(arr);
}
}
computeSum([7, 8, 9, 99]); // Returns 123
Example:
function Person(name,age,gender){
[Link] = name;
[Link] = age;
[Link] = gender;
}
In the code above, we have created a constructor function named Person. Whenever
we want to create a new object of the type Person, We need to create it using the new
keyword:
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:
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.
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.
Let’s compare the normal function declaration and the arrow function declaration in
detail:
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.
var obj1 = {
valueOfThis: function(){
return this;
}
}
var obj2 = {
valueOfThis: ()=>{
return this;
}
}
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. As you can see in the code
above, [Link]() 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, [Link]() returns the window object.
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.
Before the ES6 version of javascript, only the keyword var was used to declare
variables. With the ES6 Version, keywords let and const were introduced to declare
variables.
function catchValues(){
[Link](variable1);
[Link](variable2);
// Both the variables can be accessed anywhere since they are declared in
the global scope
}
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 [Link].
Whereas, the variables declared with the let keyword are not added to the global
object, therefore, trying to access such variables using [Link] results
in an error.
function varVsLetFunction(){
let awesomeCar1 = "Audi";
var awesomeCar2 = "Mercedes";
}
Variables are declared in a functional/local scope using var and let keywords behave
exactly the same, meaning, they cannot be accessed from outside of the scope.
{
var variable3 = [1, 2, 3, 4];
}
{
let variable4 = [6, 55, -1, 2];
}
[Link](j) // Outputs 2
In javascript, a block means the code written inside the curly braces {}.
Variables declared with var keyword do not have block scope. It means a variable
declared in block scope {} with the var keyword is the same as declaring the variable
in the global scope.
Variables declared with let keyword inside the block scope cannot be accessed from
outside of the block.
Const keyword
Variables with the const keyword behave exactly like a variable declared with the let
keyword with only one difference, any variable declared with the const keyword
cannot be reassigned.
Example:
const x = {name:"Vivek"};
const y = 23;
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.
Both rest parameter and spread operator were introduced in the ES6 version of
javascript.
Rest parameter ( … ):
function extractingArgs(...args){
return args[1];
}
// extractingArgs(8,9,1); // Returns 9
function addAllArgs(...args){
let sumOfArgs = 0;
let i = 0;
while(i < [Link]){
sumOfArgs += args[i];
i++;
}
return sumOfArgs;
}
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.
function addFourNumbers(num1,num2,num3,num4){
return num1 + num2 + num3 + num4;
}
addFourNumbers(...fourNumbers);
// Spreads [5,6,7,8] as 5,6,7,8
1. Object.
2. using Class.
3. create Method.
4. Object Literals.
5. using Function.
6. Object Constructor.
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.
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.
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.
Example of a promise:
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.
function sumOfThreeElements(...elements){
return new Promise((resolve,reject)=>{
if([Link] > 3 ){
reject("Only three elements or less are allowed");
}
else{
let sum = 0;
let i = 0;
while(i < [Link]){
sum += elements[i];
i++;
}
resolve("Sum has been calculated: "+sum);
}
})
}
In the code above, we are calculating the sum of three elements, if the length of the
elements array is more than 3, a promise is rejected, or else the promise is resolved
and the sum is returned.
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:
sumOfThreeElements(4, 5, 6)
.then(result=> [Link](result))
.catch(error=> [Link](error));
// In the code above, the promise is fulfilled so the then() method gets
executed
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:
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.
8. 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* genFunc(){
// Perform operation
}
In normal functions, we use the return keyword to return a value and as soon as the
return statement gets executed, the function execution stops:
function normalFunc(){
return 22;
[Link](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.
Generator functions are used to return iterators. Let’s see an example where an
iterator is returned:
function* iteratorFunc() {
let count = 0;
for (let i = 0; i < 2; i++) {
count++;
yield i;
}
return count;
}
As you can see in the code above, the last line returns done:true, since the code
reaches the return statement.
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:
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.
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:
const classDetails = {
strength: 78,
benches: 39,
blackBoard:1
}
const classDetails = {
strength: 78,
benches: 39,
blackBoard:1
}
const {strength:classStrength,
benches:classBenches,blackBoard:classBlackBoard} = classDetails;
[Link](classStrength); // Outputs 78
[Link](classBenches); // Outputs 39
[Link](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:
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.
15. 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.
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.
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.
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
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.
20. 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.
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.
Ans.
1
2
3
4
5
6
7
8
9
10
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
Conclusion
It is preferable to keep the JavaScript, CSS, and HTML in distinct Separate 'javascript'
files. Dividing the code and HTML sections will make them easier to understand and
deal with. This strategy is also simpler for several programmers to use at the same
time. JavaScript code is simple to update. Numerous pages can utilize the same group
of JavaScript Codes. If we utilize External JavaScript scripts and need to alter the
code, we must do it just once. So that we may utilize a number and maintain it much
more easily. Remember that professional experience and expertise are only one
aspect of recruitment. Previous experience and personal skills are both vital in landing
(or finding the ideal applicant for the job.
Remember that many JavaScript structured interviews are free and have no one
proper answer. Interviewers would like to know why you answered the way you did,
not if you remembered the answer. Explain your answer process and be prepared to
address it. If you're looking to further enhance your JavaScript skills, consider
enrolling in this free JavaScript course by Scaler Topics to gain hands-on experience
and improve your problem-solving abilities.
4. Write the code given If two strings are anagrams of one another, then
return true.
var firstWord = "Deepak";
var secondWord = "Aman";
// Sort the strings, then combine the array to a string. Examine the
outcomes.
a = [Link]("").sort().join("");
b = [Link]("").sort().join("");
return a === b;
}
Example:
return [4,5,7,2,3]
Answer:
function rotateRight(arr,rotations){
if(rotations == 0) return arr;
for(let i = 0; i < rotations;i++){
let element = [Link]();
[Link](element);
}
return arr;
}
rotateRight([2, 3, 4, 5, 7], 3); // Return [4,5,7,2,3]
rotateRight([44, 1, 22, 111], 5); // Returns [111,44,1,22]
// Code 1
(function(a){
return (function(){
[Link](a);
a = 23;
})()
})(45);
// Code 2
function bigFunc(element){
let newArray = new Array(700).fill('♥');
return newArray[element];
}
// Code 3
// The following code outputs 2 and 2 after waiting for one second
// Modify the code to output 0 and 1 after one second.
function randomFunc(){
for(var i = 0; i < 2; i++){
setTimeout(()=> [Link](i),1000);
}
}
randomFunc();
Answers -
Even though a is defined in the outer function, due to closure the inner functions have
access to it.
function bigFunc(){
let newArray = new Array(700).fill('♥');
return (element) => newArray[element];
}
function randomFunc(){
for(let i = 0; i < 2; i++){
setTimeout(()=> [Link](i),1000);
}
}
randomFunc();
Using closure:
function randomFunc(){
for(var i = 0; i < 2; i++){
(function(i){
setTimeout(()=>[Link](i),1000);
})(i);
}
}
randomFunc();
let hero = {
powerLevel: 99,
getPower(){
return [Link];
}
}
// Code 2
const a = function(){
[Link](this);
const b = {
func1: function(){
[Link](this);
}
}
const c = {
func2: ()=>{
[Link](this);
}
}
b.func1();
c.func2();
}
a();
// Code 3
const b = {
name:"Vivek",
f: function(){
var self = this;
[Link]([Link]);
(function(){
[Link]([Link]);
[Link]([Link]);
})();
}
}
b.f();
Answers:
undefined
42
Reason - The first output is undefined since when the function is invoked, it is
invoked referencing the global object:
[Link]() = getPower();
global/window object
object "b"
global/window object
Since we are using the arrow function inside func2, this keyword refers to the global
object.
Only in the IIFE inside the function f, this keyword refers to the global/window object.
(function(){
var x = 43;
(function random(){
x++;
[Link](x);
var x = 21;
})();
})();
Answer:
Output is NaN.
random() function has functional scope since x is declared and hoisted in the
functional scope.
Rewriting the random function will give a better idea about the output:
function random(){
var x; // x is hoisted
x++; // x is not a number since it is not initialized yet
[Link](x); // Outputs NaN
x = 21; // Initialization of x
}
// Code 2:
function runFunc(){
[Link]("1" + 1);
[Link]("A" - 1);
[Link](2 + "-2" + "2");
[Link]("Hello" - "World" + 78);
[Link]("Hello"+ "78");
}
runFunc();
// Code 3:
let a = 0;
let b = false;
[Link]((a == b));
[Link]((a === b));
Answers:
11
Nan
2-22
NaN
Hello78
true
false
function func1(){
setTimeout(()=>{
[Link](x);
[Link](y);
},3000);
var x = 2;
let y = 12;
}
func1();
// Code 2:
function func2(){
for(var i = 0; i < 3; i++){
setTimeout(()=> [Link](i),2000);
}
}
func2();
// Code 3:
(function(){
setTimeout(()=> [Link](1),2000);
[Link](2);
setTimeout(()=> [Link](3),0);
[Link](4);
})();
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.
Coding Problems
0/2
Easy Problems
Js Introduction
Extras
var vs let vs const
Easy
15.40 Mins
Solve
12.0 Mins
Solve
0/3
Intermediate Problems
Extras
OOPs
JavaScript MCQ
1.
Argument class is