SlideShare a Scribd company logo
1 of 42
Download to read offline
Top 150 JavaScript Interview Questions
PART – 1
(30 Questions)
Top 150 JavaScript Interview Questions
Q1. Difference between Java and JavaScript?
Java JavaScript
• It is a Programming language • It is a Scripting language
• It is object-oriented programming
language
• It is object-based scripting language. (It
does not have class
• Java is a standalone language • JS is not a standalone language, as it
needs to be linked in a HTML program
for execution
• Strongly typed – user have to decide the
data type
• Loosely typed – user do not have to
decide the data type
• Needs to be complied before executing • Do not need to compile. It can be
executed after integrating into HTML
program
• It does not require web-browser to run
java program
• It requires a web-browser to run
javascript program
• Program files are saved with “.java”
extension
• Program files are saved with “.js”
extension
• Java is stored in host machine as the
“Byte” code
• JS is stored in host machine (Client
machine) as the “source” text.
Top 150 JavaScript Interview Questions
Q2. What are the data types supported by JavaScript?
• Undefined
• Null
• Boolean
• String
• Symbol
• Number
• BigInt
• Object
Q3. How do you create array in JavaScript?
• By using array literal
Syntax:
1. const array_name = [element1, element2, element3, ……];
2. const array_name = [];
array_name[0] = “element1”;
array_name[0] = “element2”;
• By using “new” keyword
Syntax:
const array_name = new Array(“element1”, “element2”,…);
Top 150 JavaScript Interview Questions
Q4. How do you create object in JavaScript?
• By using object literal
– Syntax:
const person = {
firstName: ‘Aditi’,
lastName: ‘Seal’
};
• By using “new” keyword
– Syntax:
1. Using built-in Object constructor function –
const person = new Object();
person.firstName = ‘Aditi’;
person.lastName = ‘Seal’;
• By using Object.create() method
– Used when we want to create object from other existing objects
– Syntax:
const companyObj = {company: ‘ABC’}; //existing object
const employee = Object.create(companyObj, {name: {value: ‘Aditi’}}); //new object which has all objects
of “companyObj” object.
2. Using user-defined constructor function –
function Person(fname,lname){
this.firstName = fname;
this.lastName = lname;
}
const personOne = new Person(‘firstname’,
‘lastname’);
Top 150 JavaScript Interview Questions
• By using Object.assign() method
– Used when we want properties from more than one object
– Syntax:
//two objects which already exists
const companyObj = {company: ‘ABC’}
const carObj = {car: ‘Ford’}
//now want to create another object which has properties of “companyObj” and “carObj”
const emp = Object.assign({}, companyObj, carObj);
• By using ES6 classes
– It is similar to constructor functions, but in ES6, constructor functions are replaced by
classes
– Syntax:
//creating class
class Person {
constructor(fname, lname){
this.firstName = fname;
this.lastName = lname;
}
}
//creating object
const person = new Person(‘fname’, ‘lname’);
Top 150 JavaScript Interview Questions
Q5. Difference between attributes and properties
Attributes Property
• Provides detais on an element like its
id, type, value, name, etc
• It is the value assigned to the
attributes
• Example:
<input id=“loginForm” type=“text”
></input>
id, type - attributes
• Example:
<input id=“loginForm” type=“text”
></input>
loginForm, text – property (or value)
Q6. List different ways an HTML element can be accessed in JS
• getElementById(“id_name”)
• getElementsByClass(“class_name”)
• getElemenetsByTagName(“tag_name”)
• querySelector()
Top 150 JavaScript Interview Questions
Q7. Difference between “var” and “let” keyword?
“var” “let”
• Function Scope • Block Scope
• Redeclared • Cannot be redeclared
• Global variables are added to
global object as properties
• Not added to global object
• Variables declared with “var”
keyword, gets hoisted on top of
function
• Variables does not get hoisted
• Syntax: var a = 5; • Syntax: let a = 5;
Top 150 JavaScript Interview Questions
Example:
1. Scope (var keyword) 1. Scope (let keyword)
Top 150 JavaScript Interview Questions
3. Variable hoisting
2. Global variables sent as parameters to global object
Top 150 JavaScript Interview Questions
4. Redeclaration
Top 150 JavaScript Interview Questions
Q8. Difference between = = and = = =?
“==” “===”
• Both are comparison operators
• == checks only value • === checks values as well as type
• Converts type of variable
(It will convert the right side
value to the type on the left
side)
• Does not convert type of variable
• Syntax: if(“2” == 2)
{
console.log(“true”);
}
else{
console.log(“false”);
}
• Syntax: if(“2” === 2)
{
console.log(“true”);
}
else{
console.log(“false”);
}
• OUTPUT: true • OUTPUT: false
Top 150 JavaScript Interview Questions
Q9. Difference between “let” and “const” keyword?
“let” “const”
• Can reassign value • Cannot reassign value, but can be
modified
• Example:
const a = [1,2,3];
a.push(5);
console.log(a);
• OUTPUT: [1,2,3,5]
• let variable can be declared without
initialization
• const variable cannot be declared
without initialization
• Example:
let b;
let a = 10;
a = 20;
console.log(a)
console.log(b)
• Example:
const b;
const a = 10;
a = 20;
console.log(a)
console.log(b)
• OUTPUT:
20
undefined
• OUTPUT: ERROR
Top 150 JavaScript Interview Questions
Q10. Difference between “undefined” and “null” keyword?
“undefined” “null”
• It indicates that no value is
assigned
• It indicates absence of value
• Both has value same, but type is different
Example:
Top 150 JavaScript Interview Questions
Example: Checking type of undefined and null
Top 150 JavaScript Interview Questions
Q11. Difference between “undeclared” and “undefined” keyword?
“undeclared” “undefined”
• Do not exist in the program • Variable exist in the program, but
no value is assigned
• Runtime error occurs • No error, undefined value is
returned
Q12. Difference between “window” and “document” object?
“window” “document”
• It is a global object which has
properties like variables,
functions, history, location and
many more
• It is also an object which comes
under window object and can be
considered as the property of the
window.
Top 150 JavaScript Interview Questions
Q13. What is Arrow functions and why should we use it?
• Arrow functions were introduced in ES6 (EcmaScript version 6).
• Arrow functions helps to write JavaScript functions in less
complex way, with minimum lines of code.
• These are anonymous functions. (No name, No identifier
required)
• Syntax:
(Normal Functions)
function Test(a,b)
{
console.log(a+b);
}
• Syntax:
(Arrow Functions)
• Function_Name = (parameters)
=> (function body)
• Test = (a,b) => a+b;
Top 150 JavaScript Interview Questions
Example:
1. With one parameter & one line of code (No return keyword required; it
automatically returns value) –
2. With multiple parameters & multiple lines of code –
You can put empty braces if there is no parameter :– y = () => {function body}
Top 150 JavaScript Interview Questions
Q14. Difference between function declaration & function expression?
Function Declaration Function Expression
• Syntax:
function Test()
{
body
}
• Syntax:
var a = function()
{
body
}
• Has function name  Test • Anonymous function. No function
name.
• Does not require variable assignment • Needs variable assignment
• Function declarations are hoisted • Function expressions are not hoisted
• Function declaration executes before
any code
• Function expression is executed when
the interpreter reaches the line of code
• Function can be called or accessed from
anywhere in the code (before or after
function declaration)
• Function can only be accessed after the
function definition
Function call:
Test();
Function call:
var ans = a();
Top 150 JavaScript Interview Questions
Example:
1. Accessing function –
FUNCTION DECLARATION FUNCTION EXPRESSION
Top 150 JavaScript Interview Questions
Q15. What are Closures?
• Closures are functions which have access to their parent scope,
even after they are closed.
• Closures helps in creating private variables (as there is no direct
way to create private variables).
Example:
Example:
Top 150 JavaScript Interview Questions
Q16. What are Promises in JavaScript?
• JavaScript promises are simply an object.
• It helps to deal with asynchronous code in a simpler way compared
to callbacks.
• Promises help to avoid Callback hell.
• A Promise has 3 states:
 pending – when the promise is not fulfilled or rejected
 fulfilled – when a promise is successful
 rejected – when a promise failed
• Promise Object:
 When Promise object is “pending”, result is undefined
 When Promise object is “fulfilled”, result is a value
 When Promise object is “rejected”, result is an error object
Top 150 JavaScript Interview Questions
Let's understand some terminologies to understand Promises:
• Promise – Fetch numbers
• Promise value – Did you fetch the numbers or not?
• Promise fulfilled – Yes, success
• Promise rejected – No, failure
• Success Callback – if success, then do addition
• Failure Callback – if failure, then show error message
Steps to create and use Promise:
• Create Promise Object
• Use Promise Constructor to pass a function, which will handle the
state; resolve or reject (resolve & reject both are functions)
• Create Callback functions and execute them based on the status
Top 150 JavaScript Interview Questions
Syntax and Example:
1. Creating object
2. For fulfilling or rejecting promise, we need Promise constructor, and need to pass
a callback function to it as an argument.
State changes from
pending to fulfilled
State changes from
pending to reject
Resolve function called Reject function called
Top 150 JavaScript Interview Questions
3. Based on status change, execute callback functions
• Callback functions:
• Callback functions are generally passed as arguments to other functions.
• So, the Promise object has two methods:
1. then()
2. catch()
• We pass the Callback functions in these functions of Promise object.
NOTE:
• If status is fulfilled, function passed in then() gets executed
• If status is rejected, function passed in catch() gets executed
Also, remember:
• The parameters passed in resolve function, is accepted in then() method
• The parameters passed in reject function, is accepted in catch() method
Top 150 JavaScript Interview Questions
Q17. What is the “Strict” mode in JS and how can it be enabled?
• Strict mode is a way in which any silent errors are eliminated.
• Suppose you used a variable which is not declared, then it will
show error
• Strict mode is used by using the keywords – “use strict”
• You can add ‘use strict’ at the beginning of file, program or a
function.
Example:
No ERROR
ERROR
Top 150 JavaScript Interview Questions
Q18. How to empty an Array in JS?
• Assigning again with empty brackets (original array remains
unchanged) –
arr = []
• Setting array length to 0 –
arr.length = 0;
• Using splice method –
arr.splice(0, arr.length);  splice(index, how_many, items….)
• Using pop() method –
while(arr.length)
{
arr.pop();
}
Top 150 JavaScript Interview Questions
Q19. What are event loops?
• It is a programming structure,
which handles the execution of
code, collecting & processing
events, executing queued sub-
tasks
• It basically pulls out stuffs from
queue and places it in function
execution stack when required.
Div1#grandparent
Div2#parent
Top 150 JavaScript Interview Questions
Q20. What is Event Bubbling?
• It is a method of event propagation in HTML DOM API, when one or
more element are nested inside of another element.
• Event Bubbling occurs in upward direction, i.e; from child element to
parent element
Div3#child
B
U
B
B
L
I
N
G
Top 150 JavaScript Interview Questions
Example:
HTML file JavaScript file
OUTPUT
Top 150 JavaScript Interview Questions
Q21. What is Event Capturing/Trickling?
Div1#grandparent
Div2#parent
• It is also a method of event propagation.
• It occurs in downward direction, i.e; from outermost element to
innermost element
• Event Capturing is also known as Trickling
Div3#child
C
A
P
T
U
R
I
N
G
Top 150 JavaScript Interview Questions
Example:
HTML file JavaScript file
OUTPUT
Top 150 JavaScript Interview Questions
Q22. How do you add an element at beginning & end o an array?
• Given array  arr = [1,2,3,4,5];
• Adding at beginning  arr.push(“end”);
• Adding at end  arr.unshift(“start”);
In ES6,
• Adding at beginning  arr = ["start", ...arr1];
• Adding at end  arr = [...arr1, "end"];
• Adding at beginning and end together  arr = ["start",...arr1,"end"];
Top 150 JavaScript Interview Questions
Q23. What will be the OUTPUT?
Top 150 JavaScript Interview Questions
OUTPUT:
EXPLANATION:
• var num = 15 is just distraction
• It will first go to outer() function definition
• Then it will redeclare num, as var keyword helps in hoisting
variable
• Then it will execute inner() function
• Inside inner() function, it will again declare num variable
and assign “5” to it
• Hence, it prints “5” as output.
NOTE: If you print out num outside of the outer() function, num
will still be 15, as the variable declared inside inner()
function will be destroyed once function ends.
Top 150 JavaScript Interview Questions
• typeof returns the type of variable
• typeof 1 is “number”
• typeof “number” is “string”
• Hence, typeof typeof 1 is “string”
OUTPUT:
EXPLANATION:
Q24. What will be the OUTPUT?
Top 150 JavaScript Interview Questions
• Empty array concatenated with another empty
array gives empty string
• First “[]” this will be converted to
string, and same with second empty array,
then it will concatenate
• You can see the output is empty, nothing is
printed, but there is actually an empty
string.
• You can find that by doing
console.log(typeof([]+[]))
OUTPUT:
EXPLANATION:
Q25. What will be the OUTPUT?
Top 150 JavaScript Interview Questions
OUTPUT:
Q26. What will be the OUTPUT? How can you make variable declared with var
keyword “block scoped”?
CODE:
Top 150 JavaScript Interview Questions
• let is blocked scope and var is function scope
• So, variable v can be accessed outside the block
• But variable l cannot be accessed outside the block, hence shows error
EXPLANATION:
To make variable v blocked scope, use function expression:
OUTPUT:
CODE:
Top 150 JavaScript Interview Questions
OUTPUT:
Q27. What will be the OUTPUT?
• 5<6 will give true
true<7 will convert “true” to 1, then it will give 1<7 is true
• 7>6 will give true
true>5 will convert “true” to 1, then it will give 1>5 is false
EXPLANATION:
Top 150 JavaScript Interview Questions
Q28. How many times or for how long “Hello” will be printed?
• setTimeout will not execute as the execution main thread is busy
executing while() loop.
• Hence, a will never become false and will never exit the while
loop
• setTimeout will keep on waiting in the queue and not be executed
• Hence, It will print “Hello” infinite times, until I stop the
execution manually.
OUTPUT:
EXPLANATION:
Top 150 JavaScript Interview Questions
Q29. What will happen after 2secs? What should you do to free the cursor after
executing the code?
OUTPUT:
CODE: It will print till 8 and then stop, but cursor is not free
To free the cursor:
• setTimeout() function made the value of a false,
but setInterval() function is still running
• setInterval() function is not executing if statement
as it is false, but setInterval function keeps
running.
• Hence, the cursor is not free.
• We need to stop setInterval() function
• So assign an id to it and pass that id in
clearInterval() function
• Code will exit after execution, and cursor
will be free
Top 150 JavaScript Interview Questions
Q30. What will be the OUTPUT?
• func `Hello` means, passing “Hello” as parameter to function func().
• This is a type of template we use to pass parameters
• But still the function func() prints “Hey”, because there is a return statement which gives “Hey”
EXPLANATION:
OUTPUT:

More Related Content

Similar to JavaScript Interview Questions Part - 1.pdf

Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
Intro to javascript (5:2)
Intro to javascript (5:2)Intro to javascript (5:2)
Intro to javascript (5:2)Thinkful
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
java in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyajava in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyaviratandodariya
 
JAVA in Artificial intelligent
JAVA in Artificial intelligentJAVA in Artificial intelligent
JAVA in Artificial intelligentVirat Andodariya
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsIntroduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsDaniel McGhan
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptxMattMarino13
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptxMattMarino13
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxMegha V
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React AppAll Things Open
 
javascriptPresentation.pdf
javascriptPresentation.pdfjavascriptPresentation.pdf
javascriptPresentation.pdfwildcat9335
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptxAlkanthiSomesh
 

Similar to JavaScript Interview Questions Part - 1.pdf (20)

JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Javascript
JavascriptJavascript
Javascript
 
Javascript
JavascriptJavascript
Javascript
 
Intro to javascript (5:2)
Intro to javascript (5:2)Intro to javascript (5:2)
Intro to javascript (5:2)
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Java script
Java scriptJava script
Java script
 
java in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyajava in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariya
 
JAVA in Artificial intelligent
JAVA in Artificial intelligentJAVA in Artificial intelligent
JAVA in Artificial intelligent
 
JS Essence
JS EssenceJS Essence
JS Essence
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsIntroduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
javascriptPresentation.pdf
javascriptPresentation.pdfjavascriptPresentation.pdf
javascriptPresentation.pdf
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
 
Unit 1
Unit 1Unit 1
Unit 1
 

Recently uploaded

Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 

Recently uploaded (20)

Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 

JavaScript Interview Questions Part - 1.pdf

  • 1. Top 150 JavaScript Interview Questions PART – 1 (30 Questions)
  • 2. Top 150 JavaScript Interview Questions Q1. Difference between Java and JavaScript? Java JavaScript • It is a Programming language • It is a Scripting language • It is object-oriented programming language • It is object-based scripting language. (It does not have class • Java is a standalone language • JS is not a standalone language, as it needs to be linked in a HTML program for execution • Strongly typed – user have to decide the data type • Loosely typed – user do not have to decide the data type • Needs to be complied before executing • Do not need to compile. It can be executed after integrating into HTML program • It does not require web-browser to run java program • It requires a web-browser to run javascript program • Program files are saved with “.java” extension • Program files are saved with “.js” extension • Java is stored in host machine as the “Byte” code • JS is stored in host machine (Client machine) as the “source” text.
  • 3. Top 150 JavaScript Interview Questions Q2. What are the data types supported by JavaScript? • Undefined • Null • Boolean • String • Symbol • Number • BigInt • Object Q3. How do you create array in JavaScript? • By using array literal Syntax: 1. const array_name = [element1, element2, element3, ……]; 2. const array_name = []; array_name[0] = “element1”; array_name[0] = “element2”; • By using “new” keyword Syntax: const array_name = new Array(“element1”, “element2”,…);
  • 4. Top 150 JavaScript Interview Questions Q4. How do you create object in JavaScript? • By using object literal – Syntax: const person = { firstName: ‘Aditi’, lastName: ‘Seal’ }; • By using “new” keyword – Syntax: 1. Using built-in Object constructor function – const person = new Object(); person.firstName = ‘Aditi’; person.lastName = ‘Seal’; • By using Object.create() method – Used when we want to create object from other existing objects – Syntax: const companyObj = {company: ‘ABC’}; //existing object const employee = Object.create(companyObj, {name: {value: ‘Aditi’}}); //new object which has all objects of “companyObj” object. 2. Using user-defined constructor function – function Person(fname,lname){ this.firstName = fname; this.lastName = lname; } const personOne = new Person(‘firstname’, ‘lastname’);
  • 5. Top 150 JavaScript Interview Questions • By using Object.assign() method – Used when we want properties from more than one object – Syntax: //two objects which already exists const companyObj = {company: ‘ABC’} const carObj = {car: ‘Ford’} //now want to create another object which has properties of “companyObj” and “carObj” const emp = Object.assign({}, companyObj, carObj); • By using ES6 classes – It is similar to constructor functions, but in ES6, constructor functions are replaced by classes – Syntax: //creating class class Person { constructor(fname, lname){ this.firstName = fname; this.lastName = lname; } } //creating object const person = new Person(‘fname’, ‘lname’);
  • 6. Top 150 JavaScript Interview Questions Q5. Difference between attributes and properties Attributes Property • Provides detais on an element like its id, type, value, name, etc • It is the value assigned to the attributes • Example: <input id=“loginForm” type=“text” ></input> id, type - attributes • Example: <input id=“loginForm” type=“text” ></input> loginForm, text – property (or value) Q6. List different ways an HTML element can be accessed in JS • getElementById(“id_name”) • getElementsByClass(“class_name”) • getElemenetsByTagName(“tag_name”) • querySelector()
  • 7. Top 150 JavaScript Interview Questions Q7. Difference between “var” and “let” keyword? “var” “let” • Function Scope • Block Scope • Redeclared • Cannot be redeclared • Global variables are added to global object as properties • Not added to global object • Variables declared with “var” keyword, gets hoisted on top of function • Variables does not get hoisted • Syntax: var a = 5; • Syntax: let a = 5;
  • 8. Top 150 JavaScript Interview Questions Example: 1. Scope (var keyword) 1. Scope (let keyword)
  • 9. Top 150 JavaScript Interview Questions 3. Variable hoisting 2. Global variables sent as parameters to global object
  • 10. Top 150 JavaScript Interview Questions 4. Redeclaration
  • 11. Top 150 JavaScript Interview Questions Q8. Difference between = = and = = =? “==” “===” • Both are comparison operators • == checks only value • === checks values as well as type • Converts type of variable (It will convert the right side value to the type on the left side) • Does not convert type of variable • Syntax: if(“2” == 2) { console.log(“true”); } else{ console.log(“false”); } • Syntax: if(“2” === 2) { console.log(“true”); } else{ console.log(“false”); } • OUTPUT: true • OUTPUT: false
  • 12. Top 150 JavaScript Interview Questions Q9. Difference between “let” and “const” keyword? “let” “const” • Can reassign value • Cannot reassign value, but can be modified • Example: const a = [1,2,3]; a.push(5); console.log(a); • OUTPUT: [1,2,3,5] • let variable can be declared without initialization • const variable cannot be declared without initialization • Example: let b; let a = 10; a = 20; console.log(a) console.log(b) • Example: const b; const a = 10; a = 20; console.log(a) console.log(b) • OUTPUT: 20 undefined • OUTPUT: ERROR
  • 13. Top 150 JavaScript Interview Questions Q10. Difference between “undefined” and “null” keyword? “undefined” “null” • It indicates that no value is assigned • It indicates absence of value • Both has value same, but type is different Example:
  • 14. Top 150 JavaScript Interview Questions Example: Checking type of undefined and null
  • 15. Top 150 JavaScript Interview Questions Q11. Difference between “undeclared” and “undefined” keyword? “undeclared” “undefined” • Do not exist in the program • Variable exist in the program, but no value is assigned • Runtime error occurs • No error, undefined value is returned Q12. Difference between “window” and “document” object? “window” “document” • It is a global object which has properties like variables, functions, history, location and many more • It is also an object which comes under window object and can be considered as the property of the window.
  • 16. Top 150 JavaScript Interview Questions Q13. What is Arrow functions and why should we use it? • Arrow functions were introduced in ES6 (EcmaScript version 6). • Arrow functions helps to write JavaScript functions in less complex way, with minimum lines of code. • These are anonymous functions. (No name, No identifier required) • Syntax: (Normal Functions) function Test(a,b) { console.log(a+b); } • Syntax: (Arrow Functions) • Function_Name = (parameters) => (function body) • Test = (a,b) => a+b;
  • 17. Top 150 JavaScript Interview Questions Example: 1. With one parameter & one line of code (No return keyword required; it automatically returns value) – 2. With multiple parameters & multiple lines of code – You can put empty braces if there is no parameter :– y = () => {function body}
  • 18. Top 150 JavaScript Interview Questions Q14. Difference between function declaration & function expression? Function Declaration Function Expression • Syntax: function Test() { body } • Syntax: var a = function() { body } • Has function name  Test • Anonymous function. No function name. • Does not require variable assignment • Needs variable assignment • Function declarations are hoisted • Function expressions are not hoisted • Function declaration executes before any code • Function expression is executed when the interpreter reaches the line of code • Function can be called or accessed from anywhere in the code (before or after function declaration) • Function can only be accessed after the function definition Function call: Test(); Function call: var ans = a();
  • 19. Top 150 JavaScript Interview Questions Example: 1. Accessing function – FUNCTION DECLARATION FUNCTION EXPRESSION
  • 20. Top 150 JavaScript Interview Questions Q15. What are Closures? • Closures are functions which have access to their parent scope, even after they are closed. • Closures helps in creating private variables (as there is no direct way to create private variables). Example: Example:
  • 21. Top 150 JavaScript Interview Questions Q16. What are Promises in JavaScript? • JavaScript promises are simply an object. • It helps to deal with asynchronous code in a simpler way compared to callbacks. • Promises help to avoid Callback hell. • A Promise has 3 states:  pending – when the promise is not fulfilled or rejected  fulfilled – when a promise is successful  rejected – when a promise failed • Promise Object:  When Promise object is “pending”, result is undefined  When Promise object is “fulfilled”, result is a value  When Promise object is “rejected”, result is an error object
  • 22. Top 150 JavaScript Interview Questions Let's understand some terminologies to understand Promises: • Promise – Fetch numbers • Promise value – Did you fetch the numbers or not? • Promise fulfilled – Yes, success • Promise rejected – No, failure • Success Callback – if success, then do addition • Failure Callback – if failure, then show error message Steps to create and use Promise: • Create Promise Object • Use Promise Constructor to pass a function, which will handle the state; resolve or reject (resolve & reject both are functions) • Create Callback functions and execute them based on the status
  • 23. Top 150 JavaScript Interview Questions Syntax and Example: 1. Creating object 2. For fulfilling or rejecting promise, we need Promise constructor, and need to pass a callback function to it as an argument. State changes from pending to fulfilled State changes from pending to reject Resolve function called Reject function called
  • 24. Top 150 JavaScript Interview Questions 3. Based on status change, execute callback functions • Callback functions: • Callback functions are generally passed as arguments to other functions. • So, the Promise object has two methods: 1. then() 2. catch() • We pass the Callback functions in these functions of Promise object. NOTE: • If status is fulfilled, function passed in then() gets executed • If status is rejected, function passed in catch() gets executed Also, remember: • The parameters passed in resolve function, is accepted in then() method • The parameters passed in reject function, is accepted in catch() method
  • 25. Top 150 JavaScript Interview Questions Q17. What is the “Strict” mode in JS and how can it be enabled? • Strict mode is a way in which any silent errors are eliminated. • Suppose you used a variable which is not declared, then it will show error • Strict mode is used by using the keywords – “use strict” • You can add ‘use strict’ at the beginning of file, program or a function. Example: No ERROR ERROR
  • 26. Top 150 JavaScript Interview Questions Q18. How to empty an Array in JS? • Assigning again with empty brackets (original array remains unchanged) – arr = [] • Setting array length to 0 – arr.length = 0; • Using splice method – arr.splice(0, arr.length);  splice(index, how_many, items….) • Using pop() method – while(arr.length) { arr.pop(); }
  • 27. Top 150 JavaScript Interview Questions Q19. What are event loops? • It is a programming structure, which handles the execution of code, collecting & processing events, executing queued sub- tasks • It basically pulls out stuffs from queue and places it in function execution stack when required.
  • 28. Div1#grandparent Div2#parent Top 150 JavaScript Interview Questions Q20. What is Event Bubbling? • It is a method of event propagation in HTML DOM API, when one or more element are nested inside of another element. • Event Bubbling occurs in upward direction, i.e; from child element to parent element Div3#child B U B B L I N G
  • 29. Top 150 JavaScript Interview Questions Example: HTML file JavaScript file OUTPUT
  • 30. Top 150 JavaScript Interview Questions Q21. What is Event Capturing/Trickling? Div1#grandparent Div2#parent • It is also a method of event propagation. • It occurs in downward direction, i.e; from outermost element to innermost element • Event Capturing is also known as Trickling Div3#child C A P T U R I N G
  • 31. Top 150 JavaScript Interview Questions Example: HTML file JavaScript file OUTPUT
  • 32. Top 150 JavaScript Interview Questions Q22. How do you add an element at beginning & end o an array? • Given array  arr = [1,2,3,4,5]; • Adding at beginning  arr.push(“end”); • Adding at end  arr.unshift(“start”); In ES6, • Adding at beginning  arr = ["start", ...arr1]; • Adding at end  arr = [...arr1, "end"]; • Adding at beginning and end together  arr = ["start",...arr1,"end"];
  • 33. Top 150 JavaScript Interview Questions Q23. What will be the OUTPUT?
  • 34. Top 150 JavaScript Interview Questions OUTPUT: EXPLANATION: • var num = 15 is just distraction • It will first go to outer() function definition • Then it will redeclare num, as var keyword helps in hoisting variable • Then it will execute inner() function • Inside inner() function, it will again declare num variable and assign “5” to it • Hence, it prints “5” as output. NOTE: If you print out num outside of the outer() function, num will still be 15, as the variable declared inside inner() function will be destroyed once function ends.
  • 35. Top 150 JavaScript Interview Questions • typeof returns the type of variable • typeof 1 is “number” • typeof “number” is “string” • Hence, typeof typeof 1 is “string” OUTPUT: EXPLANATION: Q24. What will be the OUTPUT?
  • 36. Top 150 JavaScript Interview Questions • Empty array concatenated with another empty array gives empty string • First “[]” this will be converted to string, and same with second empty array, then it will concatenate • You can see the output is empty, nothing is printed, but there is actually an empty string. • You can find that by doing console.log(typeof([]+[])) OUTPUT: EXPLANATION: Q25. What will be the OUTPUT?
  • 37. Top 150 JavaScript Interview Questions OUTPUT: Q26. What will be the OUTPUT? How can you make variable declared with var keyword “block scoped”? CODE:
  • 38. Top 150 JavaScript Interview Questions • let is blocked scope and var is function scope • So, variable v can be accessed outside the block • But variable l cannot be accessed outside the block, hence shows error EXPLANATION: To make variable v blocked scope, use function expression: OUTPUT: CODE:
  • 39. Top 150 JavaScript Interview Questions OUTPUT: Q27. What will be the OUTPUT? • 5<6 will give true true<7 will convert “true” to 1, then it will give 1<7 is true • 7>6 will give true true>5 will convert “true” to 1, then it will give 1>5 is false EXPLANATION:
  • 40. Top 150 JavaScript Interview Questions Q28. How many times or for how long “Hello” will be printed? • setTimeout will not execute as the execution main thread is busy executing while() loop. • Hence, a will never become false and will never exit the while loop • setTimeout will keep on waiting in the queue and not be executed • Hence, It will print “Hello” infinite times, until I stop the execution manually. OUTPUT: EXPLANATION:
  • 41. Top 150 JavaScript Interview Questions Q29. What will happen after 2secs? What should you do to free the cursor after executing the code? OUTPUT: CODE: It will print till 8 and then stop, but cursor is not free To free the cursor: • setTimeout() function made the value of a false, but setInterval() function is still running • setInterval() function is not executing if statement as it is false, but setInterval function keeps running. • Hence, the cursor is not free. • We need to stop setInterval() function • So assign an id to it and pass that id in clearInterval() function • Code will exit after execution, and cursor will be free
  • 42. Top 150 JavaScript Interview Questions Q30. What will be the OUTPUT? • func `Hello` means, passing “Hello” as parameter to function func(). • This is a type of template we use to pass parameters • But still the function func() prints “Hey”, because there is a return statement which gives “Hey” EXPLANATION: OUTPUT: