
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialWeb Development
4.6 Rating 164 Questions 55 mins read9 Readers

Let’s first understand what is an compiled language and interpreted language.
gcc hello.c -o hello
If no error it will generate an executable “hello” and we will run it by:
./hello
python hello.py
The above code does not need to be compiled first but it does require that python is installed on any machine that needs to run the script.
However there is a compilation step just before the interpretation step in JavaScript. So, JS is both compiled and interpreted language.
Let consider the below example. The compilation steps mainly looks at the var keyword. It is not bothered with what is assigned in these variables.
var a = 10; var b = 20; console.log(a+b)

When the compiler goes to line 1, it encounters var a and registers it in the global scope and then goes to line 3 and registers the var b. Line 5 is only a console and it doesn’t finds any var, so don’t do anything.
For the above example, the interpreter starts at line 1 and see a variable a and ask the compiler, if it have a variable “a” in Global scope and the compiler have it. So, it assigns the value 10 to it. Next the same step is repeated for line 3 and interpreter assigns 20 to variable “b”.
Now once the interpreter goes to line 5, it finds console. It first looks for console at global scope from the compiler but don’t find it. So, it checks in the JavaScript global and finds it. Inside the console there are variable a and b, which it finds at global scope. It then adds them using addition operator and display the result.
The variable “var” was since the beginning of JavaScript i.e. since 1997. So, if someone didn’t updated there browser since the beginning(or past 10 years) the keyword “var” will only work on there browser.
The variables "let” and “const” were introduced recently in ES6(In 2015). There were some design mistakes made with “var” and these were rectified with “let” and “const”.
The problem is that “var” is function scoped and it causes a lot of problems.
Consider the below example where we are using “var” inside a traditional “for” loop. But we are also able to access and update “i” outside of the “for” loop.
for(var i=0; i<5; i++) {
console.log(i); //Output- 0 1 2 3 4
}
i = i + 2;
console.log(i); //Output- 7Since, “var” is function scope so we can put our “for” loop inside a function and then “i” won’t be accessible outside.
function incrementI() {
for(var i=0; i<5; i++) {
console.log(i);
}
}
incrementI(); //Output- 0 1 2 3 4i = i + 2; console.log(i);
//Output-
/* Exception: ReferenceError: i is not defined @Scratchpad/6:9:1 */
Traditional languages like C, C++ and Java as they are blocked scope and it is what was desired from JavaScript. So, the variable “let” and “const” introduced in 2015 were made block scoped.
The “for” loop declared with “let” will also throw an error, when we try to access “i” outside of it. It is because the scope of “i” ends with the “for” loop.
for(let i=0; i<5; i++) {
console.log(i); //Output- 0 1 2 3 4
}
i = i + 2;
console.log(i); //Output-
/* Exception: ReferenceError: i is not defined @Scratchpad/6:6:1 */
We will understand “const” now. It is similar to “let” and have block scope. But it was created to declare constant variables in JavaScript. We cannot assign a new value to a variable after the initial declaration for primitive types like integers and strings.
const c = 12;
c = 14;
console.log('c is ', c);/*
Exception: TypeError: invalid assignment to const `c'
@Scratchpad/6:2:1
*/
But can add or update values for non-primitive like arrays and objects.
const arr = [1, 2, 3];
arr.push(4);
console.log('arr is ', arr); // [ 1, 2, 3, 4 ]
const obj = { name: 'Robin', skill: 'JS' };
obj.skill = 'React';
obj.profession = 'Developer';
console.log('obj is ', obj);
// { name: "Robin", skill: "React", profession: "Developer" }
This is one of the most frequently asked JavaScript interview questions for freshers in recent times.
JavaScript has both strict and type-converting equality comparison. For strict comparison we use === and for type-converting comparison we use == . Let’s look at each of it in details :
Strict Comparison(===)
For strict comparison the items been compared must be the same type.
console.log("Coder" === "Coder"); //true
console.log("Coder" === "coder"); //false
console.log(23 === 23); //true
console.log(NaN === NaN); //false
console.log(0 === -0); //true
console.log(true === true); //true
console.log(false === false); //true
var obj = {};
var newObj = obj;
console.log(newObj === obj); //true
console.log(null === undefined); //false
console.log(null == undefined); //true
Type-converting comparison
The == does a type conversion before comparing, if both items are of different types.
As you can see in the below example. String 1 is equal to numeric 1, when using ==. It is because the type of String 1 is converted to Number before comparison.
It is the similar case with “1 == true”. The 1 is converted into Boolean, which is true before comparison.
Same expressions are not true while using ===, as we know it doesn’t do any type conversion.
console.log('1' == 1); //true
console.log(1 == true); //true
console.log(1 === true); //false
console.log('1' === 1); //false
Both null and undefined represents empty values. Let’s understand them first and then we will see what is the difference.
undefined
To understand “undefined” we have to understand what is declaration and definition of variables. When we declare a variable as in below diagram by “var value”, the compiler makes space for a variable “value”. The definition means that we assign a value to the variable and it’s allocated in that space. You can also do these two together by
var value = 42;

So, every language have a way of handling the value of a variable between function declaration and definition.
In JavaScript that is handled by type “undefined”. The type undefined is a primitive type which have only one value possible i.e. undefined.
null
It is also similar to “undefined” and is a primitive type. It also have only one possible value i.e. null. It is also used to represent empty values, but is generally assigned by the users.
var a; console.log(a); //undefined a = null; console.log(a); //null
Function declaration is like most other traditional languages, but in JavaScript we use the keyword “function”.
In function expression we assign an anonymous function to an variable. They are very useful when we pass function as arguments to other function or return an function.
function funcDeclaration() {
console.log('Function declaration');
}
let funcExpression = function() {
console.log('Function expression');
}
console.log(funcDeclaration()); //Function declaration
console.log(funcExpression()); //Function expression One of the key difference is that, we can call a function declaration even before defining it but same is not true for function expression and it will give reference error. Let’s move both the function call to the top.
console.log(funcDeclaration()); //Function declaration
console.log(funcExpression()); //ReferenceError
function funcDeclaration() {
console.log('Function declaration');
}
let funcExpression = function() {
console.log('Function expression');
}/*
Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization
@Scratchpad/7:2:1
*/
But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we understood in Question 1.
The compiler runs first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration.
So, the function declaration call doesn’t give as any error.
But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t knows what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t know what is functionExpression.
This is one of the most frequently asked JavaScript interview questions for freshers in recent times. Be careful with the expression this one.
Let’s say the following is your array:
var a = [99, 150, 299, 340, 390, 450, 590, 600];
Now, get the length of the array:
var len = a.length;
Loop until the length of the array is more than 0. Use Math.random() to randomize the elements. Decrement the value of len (length) after every iteration for each element:
while (len > 0) {
index = Math.floor(Math.random() * len);
len--;
t = a[len];
a[len] = a[index];
a[index] = t;
} The following is an example that shuffles an array:
<html>
<body>
<script>
function show(a) {
var len = a.length;
var t, index;
while (len > 0) {
index = Math.floor(Math.random() * len);
len--;
t = a[len];
a[len] = a[index];
a[index] = t;
}
return a;
}
var a = [99, 150, 299, 340, 390, 450, 590, 600];
document.write("Array = "+a);
document.write("<br>Shuffling the array = "+show(a));
</script>
</body>
</html>The output:
Array = 99,150,299,340,390,450,590,600 Shuffling the array = 390,340,150,590,99,450,299,600
JavaScript provides a join() method to join the elements of an array. While joining, you can set the separator as well:
array.join(separator)
Here, separator is the resultant array would be specified by this separator. Comma is the default separator.
The return value is the strings as array elements separated by the separator.
Let us see an example wherein we have the following array:
var products = ["Shoes", "Cap", "TShirt", "Shirt", "Trousers"];
The example to convert array into comma-separated list:
<!DOCTYPE html>
<html>
<body>
<script>
var products = ["Shoes", "Cap", "TShirt", "Shirt", "Trousers"];
document.write(products.join());
</script>
</body>
</html>
The following is the output:
Shoes,Cap,TShirt,Shirt,Trousers
The var and let are used to declare a variable in JavaScript. The new way to define a variable in JavaScript is using the let statement. The ECMAScript 2015 introduced it. As you know that variables can also be declared with var, but the usage of var are scoped to the function block level.
Declare variables that are limited in scope to the block, statement, or expression using the let. Redeclaring a variable inside a block will not redeclare the variable outside the block.
Example of let
Let us see an example of let. The variable declared in the loop does not redeclare the variable outside the loop:
<!DOCTYPE html>
<html>
<body>
<h3>JavaScript let</h3>
<p id="myid"></p>
<script>
let i = 2;
for (let i = 0; i < 10; i++) {
document.write(i);
}
document.getElementById("myid").innerHTML = i;
</script>
</body>
</html>The output displays the value if i variable as 2:

Example of var
Let us see the same example and place var in place of let to work with variables:
<!DOCTYPE html>
<html>
<body>
<h3>JavaScript var</h3>
<p id="myid"></p>
<script>
var i = 2;
for (var i = 0; i < 10; i++) {
document.write(i);
}
document.getElementById("myid").innerHTML = i;
</script>
</body>
</html>The output displays the value of i variable as 10:
The Number object is for integers, floating-point numbers, etc. Let us now see how to create a Number object:
var val = new Number(10);
Let us now create an object with floating-point value:
var val = new Number(25.90);
An example here is to get the value of the specified Number object. We are creating a Number object:
<html>
<head>
<title>JavaScript Number Object</title>
</head>
<body>
<script>
var val = new Number(25.90);
document.write("Value = " + val.valueOf());
</script>
</body>
</html>The output:
Value = 25.9
Let us now create another Number object and represent it in String:
<html>
<head>
<title>JavaScript Number Object</title>
</head>
<body>
<script>
var val = new Number(40);
document.write("String: " + val.toString());
</script>
</body>
</html>The output:
String: 40
Don't be surprised if this question pops up as one of the top interview questions for JavaScript in your next interview.
The length property is used in JavaScript to get the length of a string:
The syntax:
string.length
Let’s say the following is our string:
var myStr = "This is an example!";
Now get the length of the string in a new variable:
var res = myStr.length;
The following is an example that displays the string length:
<html>
<head>
<title>JavaScript String Length</title>
</head>
<body>
<script>
var myStr = "This is an example!";
var res = myStr.length;
document.write("Length = " + res);
</script>
</body>
</html>The output:
Length = 19
Let us now see what we will get when we will try to find the length of an empty string:
<html>
<head>
<title>JavaScript String Length</title>
</head>
<body>
<script>
var myStr = "";
var res = myStr.length;
document.write("Length = " + res);
</script>
</body>
</html>The output displays 0 since it is an empty string:
Length = 0
Prototypal inheritance is to add new capabilities to a constructor function using Prototype.
Let’s first understand what are Constructor functions. They are basically JavaScript way to implement the concept of Classes.
Let’s consider the example below, where we have a “Car” constructor function. In it we have a “model”, which we are also returning by getModel(). Now we can create a new instance of it by using the “new” keyword. Each instance will have its own “this” and have its own getModel().
let Car = function(model) {
this.model = model;
this.getModel = function() {
return this.model;
}
}
let harryCar = new Car('toyota');
console.log(harryCar.getModel()); //toyota
let maryCar = new Car('nissan');
console.log(maryCar.getModel()); //nissan
Now, the problem is that every time we create a new instance we get a new copy of getModel(). Suppose we have 100 instances, then we will have 100 copies. Below console log shows the same thing.

We should somehow move the logic for getModel() outside our Constructor function and that is where the concept of Prototype helps.
In JavaScript as you know everything is an Object. Whenever a function is created there are two object one is the function object another is the prototype object. Now to access the Prototype object we have a property on the function object also known as “prototype”.

Every instance created from the function have access to the Prototype object. Now, let’s move our getModel() outside our Constructor function using prototype.
let Car = function(model) {
this.model = model;
}
Car.prototype.getModel = function() {
return this.model;
}
let harryCar = new Car('toyota');
console.log(harryCar.getModel()); //toyota
let maryCar = new Car('nissan');
console.log(maryCar.getModel()); //nissan
We get the same result and this is known as Prototypal Inheritance. Also, each new instance don’t have its own getModel(), which we can see in below console log.

JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time.
Many people think JavaScript is asynchronous because we can do async tasks like setTimeout, callbacks, promises in it. But the asynchronous behaviour of JavaScript(setTimeout, callbacks, promises) is not a part of JavaScript itself and built on top of JavaScript language in browser and accessed through browser APIs.
The browser have a Call Stack, Browser API and Message Queue and the order of their processing is called event loop.
We will see the working of the classic interview question to understand how the event loop and with it the asynchronous behaviour of JavaScript works.
function main() {
console.log('A');
setTimeout(function(){
console.log('B');
},0);
console.log('C');
}
main();
//Output
//A //C //B
The output will be A C B , even after the setTimeout() was set to display “b” after 0 ms. This happens because of the internal working of the browser. Let’s look into the step of execution.
The main() is pushed into Call Stack, which then console logs A. Then it is popped out and the setTimeout is pushed into Call Stack. Now the setTimeout() uses Browser API, so it is pushed there and the console log C is pushed into Call Stack.

This is how event loop works and the asynchronous, non-blocking part of JavaScript comes from.
Every function in JavaScript have call, apply and bind methods. These methods can be used to set the custom value of “this” to the execution context of the function.
call
Let’s say that we have an object called obj. It only has one property called num, which has a value of 3. Let’s also make a function called addNumbers.
Now, in addNumbers we have this.num. But how do we pass the value obj.num to it. We need to pass it a context, which means the value of “this”. We will do this my call method by passing a first argument as obj, so the “this” is the obj now.
let obj = {num: 3};
let addNumbers = function(a, b, c){
return this.num + a + b + c;
};
console.log(addNumbers.call(obj, 1, 4, 6)); //14 apply
It is totally similar to call, but the only difference is that we can pass array as the second argument. We will use the same code for apply also. But now we have an arr, to be passed as second argument.
let obj = {num: 3};
let addNumbers = function(a, b, c){
return this.num + a + b + c;
};
let arr = [7, 3, 8];
console.log(addNumbers.apply(obj, arr)); //21bind
Bind works in a bit different way then call and apply. It works by returning a copy of the function. We will take the returned function in bindFunc and then execute it in the next line.
let obj = {num: 3};
let addNumbers = function(a, b, c){
return this.num + a + b + c;
};
let bindFunc = addNumbers.bind(obj);
console.log(bindFunc(7, 3, 8)); //21There are four solutions to access “this” inside the innerFunc().
Solution 1Use a “that” variable in cleanRoom() for accessing “this” inside innerFunc(). Basically “that” is nothing but the outer “this”.
const cleanRoom = function(soap) {
let that = this;
const innerFunc = function(_soap) {
console.log(`Cleaning ${that.room} with ${_soap}`)
}
innerFunc(soap);
}
let harrysRoom = {
room: "Harry's room"
}
cleanRoom.call(harrysRoom, "Harpic");
//Output - Cleaning Harry’s room with Harpic
Solution 2Use call method to use the outer “this” inside the innerFunc().
const cleanRoom = function(soap) {
const innerFunc = function(_soap) {
console.log(`Cleaning ${this.room } with ${_soap}`)
}
innerFunc.call(this, soap);
}
let harrysRoom = {
room: "Harry's room"
}
cleanRoom.call(harrysRoom, "Harpic");
//Output - Cleaning Harry’s room with Harpic
Solution 3Use bind method to use the outer “this” inside the innerFunc().
const cleanRoom = function(soap) {
const innerFunc = function(_soap) {
console.log(`Cleaning ${this.room } with ${_soap}`)
}
innerFunc.bind(this)(soap);
}
let harrysRoom = {
room: "Harry's room"
}
cleanRoom.call(harrysRoom, "Harpic");
//Output - Cleaning Harry’s room with Harpic
Solution 4Use arrow function in the innerFunc(). Arrow functions have special meaning for “this” and it is that, it takes the value of “this” from the enclosing scope and is very useful in this case.
const cleanRoom = function(soap) {
const innerFunc = (_soap)=> {
console.log(`Cleaning ${this.room } with ${_soap}`)
}
innerFunc(soap);
}
let harrysRoom = {
room: "Harry's room"
}
cleanRoom.call(harrysRoom, "Harpic");
//Output - Cleaning Harry’s room with Harpic
One of the main use of “call” is to change an array like object to array.
There is an array like object arguments available for every normal function(not arrow function). It is very useful in functions, as we can get the number of arguments passed to it. Let’s convert the arguments into array, because arrays have a lots of functionality.
Consider the below example, where we console log arguments. If we expand it in dev console, it shows it’s not and array and it’s __proto__ doesn’t have array functionalities.
let sumNumbers = function() {
console.log(arguments);
}
sumNumbers(1, 2, 3, 4);
Now to convert it we will take an empty array and use it’s slice method. Then call it through call, by passing the argument Object. Now it is converted into array and the __proto__ have all array functionalities. So, we are using the array reduce method available to do the sum of the number of arguments passed to it.
let sumNumbers = function() {
const argsToArray = [].slice.call(arguments);
console.log(argsToArray);
return argsToArray.reduce((acc, curr) => acc + curr);
}
console.log(sumNumbers(1, 2, 3, 4)); //10
console.log(sumNumbers(1, 2, 3)); //6The second application of call is in inheritance , using constructor functions.
Consider the below example. Here in the Cat function, we called its parent Mammal using call method with “this” of Cat.
let Mammal = function(legs) {
this.legs = legs;
}
let Cat = function(legs, isDomesticated) {
Mammal.call(this, legs);
this.isDomesticated = isDomesticated;
}
let tiger = new Cat(4, false);
let homeCat = new Cat(4, true);
console.log(tiger); // { legs: 4, isDomesticated: false }
console.log(homeCat); // { legs: 4, isDomesticated: true } One of the practical use of apply is to pass an array to a function, which expects arguments only.
Consider the case of Math.max, which gives the maximum of the arguments passed. So, now to pass an array like in below code, we convert it through apply. Note the first argument is null because we are not passing any Object for “this” binding.
let arr = [20, 6, 29, 12]; console.log(Math.max(20, 6, 29, 12)); // 29 console.log(Math.max.apply(null, arr)); // 29
One of the practical use of bind is in React. In React whenever we call a function from render(), we have to bind it’s “this” in constructor.
Consider the below code. We bind the “this” of the event handler to the component instance in the constructor, we can pass it as a callback without worrying about it losing its context.
class Foo extends React.Component{
constructor( props ){
super( props );
this.state = {
text: ''
}this.handleChange = this.handleChange.bind(this);
}
handleChange(event){
this.setState({
text: event.target.value
})
}
render(){
return (
<input type="text" value={this.state.text}
onChange={this.handleChange} />
);
}
}
ReactDOM.render(
<Foo />,
document.getElementById("app")
);This is one of the most frequently asked JavaScript interview questions and answers for freshers in recent times.