SlideShare a Scribd company logo
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:
Ad

More Related Content

What's hot (20)

Infografico do Scrum 2020
Infografico do Scrum 2020 Infografico do Scrum 2020
Infografico do Scrum 2020
Alvaro Junqueira
 
JavaFX: A nova biblioteca gráfica da plataforma Java
JavaFX: A nova biblioteca gráfica da plataforma JavaJavaFX: A nova biblioteca gráfica da plataforma Java
JavaFX: A nova biblioteca gráfica da plataforma Java
jesuinoPower
 
Scrum introduction
Scrum introductionScrum introduction
Scrum introduction
Martin Gasparovic
 
Scrum Values
Scrum ValuesScrum Values
Scrum Values
Sanjay Saini
 
Planejamento de testes em um mundo ágil
Planejamento de testes em um mundo ágilPlanejamento de testes em um mundo ágil
Planejamento de testes em um mundo ágil
Ariane Izac
 
Scrum - Fundamentos, teorias e práticas!
Scrum - Fundamentos, teorias e práticas!Scrum - Fundamentos, teorias e práticas!
Scrum - Fundamentos, teorias e práticas!
Annelise Gripp
 
Scrum
ScrumScrum
Scrum
Balaji Sathram
 
Scrum 101
Scrum 101Scrum 101
Scrum 101
beLithe
 
Sonarqube
SonarqubeSonarqube
Sonarqube
CDS
 
Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow one
Victor Rentea
 
Scrum values
Scrum valuesScrum values
Scrum values
Priyanka Rana
 
Building Agile Teams
Building Agile TeamsBuilding Agile Teams
Building Agile Teams
Angel Diaz-Maroto
 
Scrum Introduction
Scrum IntroductionScrum Introduction
Scrum Introduction
James Brett
 
Introduction to Agile - Scrum, Kanban, and everything in between
Introduction to Agile - Scrum, Kanban, and everything in betweenIntroduction to Agile - Scrum, Kanban, and everything in between
Introduction to Agile - Scrum, Kanban, and everything in between
Pravin Kumar Singh, PMP, PSM
 
Scrum master
Scrum masterScrum master
Scrum master
Patricio Gastón Moreno
 
Master scrum through scrum values
Master scrum through scrum valuesMaster scrum through scrum values
Master scrum through scrum values
sobiasheikh2
 
Agile Introduction - Scrum Framework
Agile Introduction - Scrum FrameworkAgile Introduction - Scrum Framework
Agile Introduction - Scrum Framework
Kshitij Yelkar MBA/PMP/CSM/ICP-ACC
 
Aligner votre stratégie d’entreprise, produit et managériale avec les OKR
Aligner votre stratégie d’entreprise, produit et managériale avec les OKRAligner votre stratégie d’entreprise, produit et managériale avec les OKR
Aligner votre stratégie d’entreprise, produit et managériale avec les OKR
Anne Gabrillagues
 
전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
devCAT Studio, NEXON
 
Scrum
ScrumScrum
Scrum
Elaine Cecília Gatto
 
Infografico do Scrum 2020
Infografico do Scrum 2020 Infografico do Scrum 2020
Infografico do Scrum 2020
Alvaro Junqueira
 
JavaFX: A nova biblioteca gráfica da plataforma Java
JavaFX: A nova biblioteca gráfica da plataforma JavaJavaFX: A nova biblioteca gráfica da plataforma Java
JavaFX: A nova biblioteca gráfica da plataforma Java
jesuinoPower
 
Planejamento de testes em um mundo ágil
Planejamento de testes em um mundo ágilPlanejamento de testes em um mundo ágil
Planejamento de testes em um mundo ágil
Ariane Izac
 
Scrum - Fundamentos, teorias e práticas!
Scrum - Fundamentos, teorias e práticas!Scrum - Fundamentos, teorias e práticas!
Scrum - Fundamentos, teorias e práticas!
Annelise Gripp
 
Scrum 101
Scrum 101Scrum 101
Scrum 101
beLithe
 
Sonarqube
SonarqubeSonarqube
Sonarqube
CDS
 
Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow one
Victor Rentea
 
Scrum Introduction
Scrum IntroductionScrum Introduction
Scrum Introduction
James Brett
 
Introduction to Agile - Scrum, Kanban, and everything in between
Introduction to Agile - Scrum, Kanban, and everything in betweenIntroduction to Agile - Scrum, Kanban, and everything in between
Introduction to Agile - Scrum, Kanban, and everything in between
Pravin Kumar Singh, PMP, PSM
 
Master scrum through scrum values
Master scrum through scrum valuesMaster scrum through scrum values
Master scrum through scrum values
sobiasheikh2
 
Aligner votre stratégie d’entreprise, produit et managériale avec les OKR
Aligner votre stratégie d’entreprise, produit et managériale avec les OKRAligner votre stratégie d’entreprise, produit et managériale avec les OKR
Aligner votre stratégie d’entreprise, produit et managériale avec les OKR
Anne Gabrillagues
 
전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
devCAT Studio, NEXON
 

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

Thinkful - Intro to JavaScript
Thinkful - Intro to JavaScriptThinkful - Intro to JavaScript
Thinkful - Intro to JavaScript
TJ Stalcup
 
Intro to javascript (6:19)
Intro to javascript (6:19)Intro to javascript (6:19)
Intro to javascript (6:19)
Thinkful
 
Intro to javascript (6:27)
Intro to javascript (6:27)Intro to javascript (6:27)
Intro to javascript (6:27)
David Coulter
 
Intro to JavaScript - Thinkful LA, June 2017
Intro to JavaScript - Thinkful LA, June 2017Intro to JavaScript - Thinkful LA, June 2017
Intro to JavaScript - Thinkful LA, June 2017
Thinkful
 
JavaScript ppt for introduction of javascripta
JavaScript ppt for introduction of javascriptaJavaScript ppt for introduction of javascripta
JavaScript ppt for introduction of javascripta
nehatanveer5765
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Presentation JavaScript Introduction Data Types Variables Control Structure
Presentation JavaScript Introduction  Data Types Variables Control StructurePresentation JavaScript Introduction  Data Types Variables Control Structure
Presentation JavaScript Introduction Data Types Variables Control Structure
SripathiRavi1
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptx
MattMarino13
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
rashmiisrani1
 
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
Gil Fink
 
Javascript
JavascriptJavascript
Javascript
Prashant Kumar
 
Javascript
JavascriptJavascript
Javascript
20261A05H0SRIKAKULAS
 
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 Mizrahi
Ran Mizrahi
 
Java script
Java scriptJava script
Java script
Jay Patel
 
JAVA in Artificial intelligent
JAVA in Artificial intelligentJAVA in Artificial intelligent
JAVA in Artificial intelligent
Virat Andodariya
 
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
viratandodariya
 
JS Essence
JS EssenceJS Essence
JS Essence
Uladzimir Piatryka
 
Thinkful - Intro to JavaScript
Thinkful - Intro to JavaScriptThinkful - Intro to JavaScript
Thinkful - Intro to JavaScript
TJ Stalcup
 
Intro to javascript (6:19)
Intro to javascript (6:19)Intro to javascript (6:19)
Intro to javascript (6:19)
Thinkful
 
Intro to javascript (6:27)
Intro to javascript (6:27)Intro to javascript (6:27)
Intro to javascript (6:27)
David Coulter
 
Intro to JavaScript - Thinkful LA, June 2017
Intro to JavaScript - Thinkful LA, June 2017Intro to JavaScript - Thinkful LA, June 2017
Intro to JavaScript - Thinkful LA, June 2017
Thinkful
 
JavaScript ppt for introduction of javascripta
JavaScript ppt for introduction of javascriptaJavaScript ppt for introduction of javascripta
JavaScript ppt for introduction of javascripta
nehatanveer5765
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Presentation JavaScript Introduction Data Types Variables Control Structure
Presentation JavaScript Introduction  Data Types Variables Control StructurePresentation JavaScript Introduction  Data Types Variables Control Structure
Presentation JavaScript Introduction Data Types Variables Control Structure
SripathiRavi1
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptx
MattMarino13
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
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
Gil 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 Mizrahi
Ran Mizrahi
 
JAVA in Artificial intelligent
JAVA in Artificial intelligentJAVA in Artificial intelligent
JAVA in Artificial intelligent
Virat Andodariya
 
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
viratandodariya
 
Ad

Recently uploaded (20)

Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Ad

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: