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;
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"];
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: