45+ TOP JavaScript Interview Questions and Answers

Most Frequently Asked JavaScript Interview Questions with detailed Answers for Freshers and Experienced Professionals:

If you are preparing for an interview, here are the most frequently asked JavaScript interview questions and answers for your reference.

We have designed the same to get you introduced to the questions you may likely encounter during your technical interview.

Let's Explore!!

JavaScript Interview Questions

About JavaScript

JavaScript is a high-level programming language, probably one of the most used programming languages in the world right now. It can be used to program the web browser or even servers.

To know the importance of JavaScript, disable JavaScript on your browser and try to load the Web page in it. Those Web pages will not work properly. Many contents in them may misbehave. Almost all modern browsers use the combination of JavaScript, CSS, and HTML.

JavaScript is an interpreted programming language. An interpreter is embedded in browsers like Google Chrome, Microsoft Internet Explorer, etc. So, its code can be handled by the JavaScript Engine of the browser.

JavaScript appeared in December 1995 and was initially called LiveScript, although the name was soon changed for marketing reasons. It should not be confused with ‘Java’ which is also bearing some resemblance but is a completely different language.

Most Frequently Asked JavaScript Interview Questions

Q #1) What is JavaScript?

Answer: JavaScript is a scripting language developed by Netscape. It can be used to program web browsers or even servers. It can dynamically update the contents of the webpage, which is the beauty of this language.

Q #2) What are the advantages of using External JavaScript?

Answer: Using External JavaScript in our code has many advantages.

These are stated below.

  • Separation of code is done.
  • Code Maintainability is easy.
  • The performance is better.

Q #3) In the following code snippet can you please predict the output or If you get an error, please explain the error?

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p id="studentName"></p>

<script>
var studentName = "Sajeesh Sreeni"; // String 'Sajeesh Sreeni' stored in studentName
var studentName; // varaible is decalred again
document.getElementById("studentName").innerHTML = 
"Redeclaring the varaible will not lose the value!.<br>"
+"Here the value in studentName is "+ studentName;

</script>
</body>
</html>

Answer: This code will not produce any errors. Redeclaration of the variables is allowed in JavaScript. Hence, the value of the variable will not be lost after the execution of the statement here.

Q #4) In the following code snippet can you please predict the output or If you get an error; please explain the error?

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p id="sum_first"></p>
<p id="sum_second"></p>
<script>
var sum_first =50+20+' Sajeesh Sreeni ';
var sum_second= " Sajeesh Sreeni "+50+20;
document.getElementById("sum_first").innerHTML = "The first varaible sum is :"+sum_first +
"<br>The second varaible sum is :"+sum_second ;
</script>
</body>
</html>

Answer: This code will not show any error!

Output of the code snippet:

      The first variable sum is: 70 Sajeesh Sreeni
   The second variable sum is: Sajeesh Sreeni 5020

Q #5) What is the difference between test () and exec () methods?

Answer: Both test () and exec () are RegExp expression methods.

By using a test (), we will search a string for a given pattern, if it finds the matching text then it returns the Boolean value ‘true’ or else it returns ‘false’.

But in exec (), we will search a string for a given pattern, if it finds the matching text then it returns the pattern itself or else it returns ‘null’ value.

Q #6) What are the advantages of JavaScript?

Answer: This Scripting language has many advantages as stated below.

  • Lightweight: It is easy to implement. It has small memory footprints.
  • Interpreted: It is an interpreted language. Instructions are executed directly.
  • Object-oriented: It is an object-oriented language.
  • First-class functions: In JavaScript, a function can be used as a value.
  • Scripting Language: It’s a language in which instructions are written for a run-time environment.

Q #7) In the following code snippet can you please predict the output or If you get an error; please explain the error?

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Example Const Variable </p>
<p id="display"></p>
<script>
const first_num;
first_num =1000;
document.getElementById("display").innerHTML = "First Number:"+ first_num;
</script>
</body>
</html>

Answer: The ‘const’ variable ’first_num’ is not initialized with a value, so the code will produce a Syntax Error.

Output of the code snippet:

Error: Uncaught SyntaxError: Missing initializer in the const declaration

Q #8) Have you used any browser for debugging? If yes, how is it done?

Answer: By pressing the ‘F12’ key in the keyboard we can enable debugging in the browser. Chose the ‘Console’ tab to view the result.

In Console, we can set breakpoints and view the value in variables. All the modern browsers have a built-in debugger with them (For Example: Chrome, Firefox, Opera, and Safari). This feature can be turned ON and OFF.

Q #9) What is the use of the ‘debugger’ keyword in JavaScript code?

Answer: Using the ‘debugger’ keyword in the code is like using breakpoints in the debugger.

To test the code, the debugger must be enabled for the browser. If debugging is disabled for the browser, the code will not work. During debugging of the code, the remaining part should stop executing, before it goes to the next line.

Q #10) What are the distinct types of Error Name Values?

Answer: There are 6 types of values in ‘Error Name’ Property.

ErrorDescription
Range ErrorWe will get this error if we use a number outside the range
Syntax ErrorThis error raises when we use the incorrect syntax. (Please refer Ques No: 7)
Reference ErrorThis error is thrown if used an undeclared variable Please refer Ques No: 19
Eval ErrorThrown due to the error in eval(). New JavaScript version doesn’t have this error
Type ErrorValue is outside the range of types used. Please refer Ques No :22
URI Error
Due to the usage of illegal characters.

Q #11) What is JavaScript Hoisting?

Answer: While using the ‘JavaScript Hoisting’ method, when an interpreter runs the code, all the variables are hoisted to the top of the original /current scope. If you have a variable declared anywhere inside the code, then it is brought to the top.

This method is only applicable to the declaration of a variable and is not applicable for the initialization of a variable. Functions are also hoisted to the top, whereas function explanations are not hoisted to the top.

Basically, where we declared the variable inside the code doesn’t matter much.

Q #12) What is JavaScript ‘Strict Mode’?

Answer: ‘Strict mode’ is a restricted variant of JavaScript. Usually, this language is ‘not very strict’ in throwing errors. But in ‘Strict mode’ it will throw all types of errors, even the silent errors. Thus, the process of debugging becomes easier. And the chances for making a mistake for the developer is reduced.

Q #13) What are the characteristics of JavaScript ‘Strict Mode’?

Answer: Given below are the characteristics of ‘Strict Mode’:

  • ‘Strict Mode’ will stop developers from creating global variables.
  • Developers are restricted from using duplicate parameters.
  • Strict mode will restrict you from using the JavaScript keyword as a variable name or function name.
  • Strict mode is declared with ‘use strict’ keyword at the beginning of the script.
  • All browsers support strict mode.

Q #14) What are Self Invoking Functions?

Answer: They are also known as ‘Immediately Invoked Function Expressions’ or ‘Self Executing Anonymous Functions’. These functions are invoked automatically in the code, hence they are named as ‘Self Invoking Functions’.

Usually, we define a function and invoke it, but if we want to execute a function automatically where it is explained, and if we are not going to call it again, we can use anonymous functions. And these types of functions have no name.

Q #15) What is the syntax of ‘Self Invoking Function’? Give an example?

Answer:

The syntax for the Self-Invoking function:

(function () {
return () } () ;

Here the last ‘()’ parenthesis in the syntax states that it is a function expression.

Example of Self Invoked Functions:

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Example for Self-Invoking </p>
<p id="dispaly_num"></p>
<script>
(function (){
elem = document.getElementById("dispaly_num");
elem.innerHTML = "This function has no name.<br>It is called automatically";
}());
</script>
</body>
</html>

Here, the anonymous function is automatically invoked in the code snippet.

The function is used to set the text property of <p> tag having ‘display_num’ as Id.

Output of the code snippet:

      This function has no name.
   It is called automatically

Q #16) In the following code snippet, can you please predict the output or If you get an error; please explain the error?

Answer: 

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample : Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Example for JavaScript Hoisting </p>
<p id="dispaly_num"></p>
<script>
first_num = 100; // Assign value 100 to num
elem = document.getElementById("dispaly_num");
elem.innerHTML = " Here the variable first_num:<u> "+first_num +"</u> is taken to the top <br>" +
"Since second variable is initialised the value is not taken to the top and it's value is "
+ "<u>"+second_num +"</u> “;
var first_num; // declaration only
var second_num =200; // Initialised the variable
</script>
</body>
</html>

Please refer to previous Q #11, as explained there, the interpreter will take all the variables declared except initialization to the top.

As per this, the ‘first_num’ variable is taken to the top and the ‘second_num’ variable is initialized with a value, so it is not taken to the top. This code will not throw an error. But the value of ‘second_num’ is undefined.

Output of the code snippet:

        Here the variable first_num: 100 is taken to the top
       Since the second variable is initialized the value is not taken to the top and its value is undefined

Q #17) If you need to hide the JavaScript code from the older browser versions, how will you perform it?

Answer: In Code, after the <script> tag, add ‘<! –’ HTML tag.

This will not allow the browser to execute the JavaScript code if it was being an older version of it. Also, after the end </script> tag add ‘//–>’ HTML tag.

This method will help in solving compatibility issues and UI issues to an extent.

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p id="display"></p>
<script> <!--
document.getElementById("display").innerHTML = "Here I am not using an older version of browser.<br> 
So the code will work in my browser";
//-->
</script>
</body>
</html>

Here, the code snippet after a <script> tag is executed in my browser as I am not using an older version of the browser.

Output of the code snippet:

      Here I am not using an older version of the browser.
      So the code will work in my browser

Q #18) In the following code snippet can you please predict the output or If you get an error, please explain the error?

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Find the output </p>
<p id="display"></p>
<script>
var first_num =500;
var result= function(){
document.getElementById("display").innerHTML = first_num;
var first_num =1000;
}
result();
</script>
</body>
</html>

Answer: Here in the code given above, the value of the ‘first_num’ variable will not be 1000.

In JavaScript, there is no hoisting for variable initialization. The function ‘result ()’ will choose the local variable ‘first_num’, as it is declared inside the function. Since the variable is declared after it is used, the value of ‘first_num’ is undefined.

Output of the code snippet:

Undefined

Q #19) What is the difference between ‘var’ and ‘let’ keyword?

Answer: The differences are as follows:

Var
let
’var’ keyword was introduced in JavaScript code from the beginning Stage itself.‘let’ keyword is introduced in 2015 only.
’Var’ keyword has function scope. The variable defined with var is available anywhere within the functionA variable declared with ‘let’ keyword has a scope only with in that block. So, let has a Block Scope.
The variable declared with ‘var’ be hoistedThe variable declared with ‘let’ be hoisted

Q #20) In the following code snippet can you please predict the output or If you get an error; please explain the error?

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Find the output </p>
<p id="display_first"></p>
<p id="display_second"></p>
<script>
if(true){ 
var first_num =1000; 
let second_num=500; 
}
document.getElementById("display_first").innerHTML = "First Number:" + first_num;
document.getElementById("display_second").innerHTML = "Second Number:" + second_num;
</script>
</body>
</html>

Answer:

Output of the code snippet:

     First Number :1000

We will get ‘First Number :1000’ as output. There is an ‘Uncaught Reference Error’ error also.

In the code snippet, the scope of ‘second_num’ is only within the if() block. If a developer tries to access the value outside the block, he will get an ‘Uncaught Reference error’.
Uncaught Reference Error: second_num is not defined.

Q #21) What is the difference between ‘==’ and ‘===’?

Answer: Both ‘==’ and ‘===’ are comparison operators.

‘==’ operator
‘===’ operator
It is known as ‘Type Converting Operator’
It is known as ‘Strict Equality Operator’
It compares Value, do not compare type
It compares both value and type.

Q #22) What is the difference between ‘let’ and ‘const’?

Answer: Differences are as follows:

let
const
using ‘let’ we can change the value of variable any number of timesusing ‘const’, after the first assignment of the value we cannot redefine the value again
Consider the code
{
let first_num =1;
first_num=2;
document. write (first_num);
}
Here the code will give an output, since the change in value of first_num is possible.
Consider the code
{
const second_num =1;
second_num=2;
document. write (second_num);
}
Here the code will produce an error, since the ‘second_num’ is assigned with a second value.

Q #23) In the following Code snippet can you please predict the output or If you get an error; please explain the error?

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Example of 'Const' Keyword </p> 
<p id="display_first"></p>
<p id="display_second"></p>
<script>
let first_num =500; 
first_num=501; 
document.getElementById("display_first").innerHTML = "First Number:"+ first_num ; 
const second_num =1000; 
second_num=1001; 
document.getElementById("display_second").innerHTML = "Second Number :"+second_num;
</script>
</body>
</html>

Answer: Please refer Q #21 before reading further

Output of the code snippet:

 First Number:501

We will also get an error while running the code, as we are trying to change the value of a ‘const’ variable.

Error: Uncaught TypeError: Assignment to constant variable.

Q #24) What is the difference between ‘null’ and ‘undefined’?

Answer: Both keywords represent empty values.

The differences are:

  • In ‘undefined’, we will define a variable, but we won’t assign a value to that variable. On the other hand, in ‘null’ we will define a variable and assign the ‘null’ value to the variable.
  • type of (undefined) and type of (null) object.

Q #25) What is the difference between ‘function declaration’ and ‘function expression’?

Answer:  It can be explained with an example:

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Example Function Declaration</p> 
<p id="display_add"></p>
<p id="display_sub"></p>
<script>
function add(first_num,second_num){
return first_num + second_num;
}
var substract = function sub(first_num,second_num){
return first_num - second_num;
}
var first_num=700;
var second_num=300;
document.getElementById("display_add").innerHTML = "Sum of the number is:" + add(first_num,second_num);
document.getElementById("display_sub").innerHTML = "Difference of the number is:" + substract(first_num,second_num);
</script>
</body>
</html>

As shown in the example add() is a function declaration and subtract() is a function expression. The syntax of the function declaration is like a function which is saved into a variable.

Function declarations are hoisted but function expressions are not hoisted.

Q #26) What are ‘settimeout()’?

Answer: It will be better explained with an example.

Consider the code snippet

Console.log (‘First Line’);
Console.log (‘Second Line’);
Console.log (‘Third Line’);

Output of the code snippet:

First Line
Second Line
Third Line

Now you introduce the settimeout() method and wrap the same set of code in it.

Settimeout(function() {
Console.log (‘First Line’);
},0);
Console.log (‘Second Line’);
Console.log (‘Third Line’);

Output of the code snippet:

Second Line
Third Line
First Line

With the introduction of settimeout(), the processes become asynchronous. The first statements to be placed in the stack is Console.log (‘Second Line’), and Console.log (‘Third Line’), and they will get executed first. You need to wait until everything in the stack is completed first.

Even though ‘0’ is the timeout period, it doesn’t mean that it will be executed right away.

Q #27) What is a Closure and how do you use it?

Answer: A closure is an inner function. It can access the outer variables of a function. In Closure, within function_1 there is another function_2 which returns ‘A’ value and function_1 also returns a value; say ‘B’.

Here, sum() is the outer function and add () is an inner function, it can access all the variables including ‘first_num’ ‘second_num’ and ‘third_num’. The outer function is calling the inner function add().

<script>
// To find the sum of two numbers using closure method
function sum( first_num, second_num )
{
var sumStr= 600;
function add(first_num , second_num)
{
return (sumStr + (first_num + second_num));
}
return add();
}
document.write("Result is :"+ sum(150,350));
</script>

Output of the code snippet:

Result is: 500

Q #28) In the following code snippet can you please predict the output or If you get an error; please explain the error?

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Example Assignmnet Statement</p>
<p id="display"></p>
<script>
var x =500;
let y,z,p,q;
q=200;
if(true){
x=y=z=p=q;
document.getElementById("display").innerHTML = "x="+ x + "<br>y :"+ y +"<br>z :"+ z+"<br>p :"+ p+"<br>q :"+ q;
}
</script>
</body>
</html>

Answer: The assignment statements are considered from Right to left.

Output of the code snippet:

x=200
y:200
z:200
p:200
q:200

Q #29) Can you give an example where the code snippet shows the difference between test () and exec () methods?

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample : Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Example for exec() methods </p>
<p>Click the button to search for a pattern "How“ in the given string "Hello. Good Morning. How do you feel today?"</p>
<p>If the "How" is found, the method will return the pattern </p>
<button onclick="searchTxt()">Search</button>
<p id="result"></p>
<script>
function searchTxt() {
var str = "Hello. Good Morning. How do you feel today?";
var search_patt = new RegExp("How");
var res = search_patt.exec(str);
document.getElementById("result").innerHTML ="Found the pattern :"+ res;
}
</script>
</body>
</html>

Answer: This is an example of the test () and exec () method, Refer Ques No: 5 for more details.

Output of the code snippet:

Found the pattern using exec (): How
Using test () the result is: true

Q #30) Can you give an example showing JavaScript Hoisting?

Answer:

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Example for JavaScript Hoisting </p>
<p id="dispaly_num"></p>
<script>
num = 100; // Assign value 100 to num
elem = document.getElementById("dispaly_num"); 
elem.innerHTML = "Here the variables are used before declaring it." +
" <br>The value of the variable is " + num;
var num; // Declare the varaible </script>
</body>
</html>

Please refer to Q #11 for more details.

Here the variable ‘num’ is used before declaring it. But JavaScript Hoisting will allow it.

Output of the code snippet:

       Here the variables are used before declaring it.
  The value of the variable is 100

Q #31) Can you give an example showing the use of the ‘debugger’ keyword in the JavaScript code?

Answer:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p style='text-decoration:underline'> Example for debug keyword </p>
<p> Here to test the code, debugger must be enabled for the browser, 
<br>during debugging the code below should stop executing before it goes to the next line. </p>
<p id="wait_result"></p>
<p id="show_result"></p>
<script>
var a = 1000;
var b = 500;
var sum = a + b;
document.getElementById("wait_result").innerHTML = "Adding numbers......<br>
Select 'Resume Script execution' to continue: ";
debugger;
document.getElementById("show_result").innerHTML = "Sum of the numbers : "+sum;
</script>
</body>
</html>

Note: The debugger must be enabled for the browser to test the code. Refer Ques No: 5 for more details

This is an example of debugging keyword (Browser used: Chrome)

Output of the code snippet:

Here to test the code, the debugger must be enabled for the browser,
during debugging the code below should stop executing before it goes to the next line.
Adding numbers…
Select ‘Resume Script execution' to continue:

<Click on ‘Resume Script execution’ Button>

Sum of the numbers: 1500

Q #32) In the following code snippet can you please predict the output or If you get an error; please explain the error?

<!DOCTYPE html>
<html>
<body>
<h2> <strong> Sample: Software Testing Help</strong> </h2>
<p style='text-decoration:underline'>Example Type Converting </p>
<p id="display"></p>
<script>
var first_num =500;
var first_name='500';
if(first_num == first_name){ 
document.getElementById("display").innerHTML = "Comparison will return 'true' by Type converting Operator ";
}
</script>
</body>
</html>

Answer: Consider the code

If (‘100’==100) {
document. write (“It’s a Type Converting Operator”);
}
Here
  typeof(‘100’) is string
   typeof(100) is number
the ‘==’ operator will convert the number type, which is on the right side of the operator to string and compare both values

Output of the code snippet:

Comparison will return ‘true' by Type converting Operator

Q #33) Are Java and JavaScript similar? If not, then what is the difference between Java & JavaScript?

Answer:

Sl NoJavaJavaScript
1Java is a general-purpose programming language.JavaScript is a high-level, interpreted scripting language. 
2Java is based on Object-Oriented Programming (OOPS)concepts.JavaScript  is both an  object-oriented  as well as a  functional  scripting.
3Runs in a Java Virtual Machine ( JVM ) or browser.Runs on a browser only.
4Java code needs to get compiled as Java class file.JavaScript  has no  compilation  step.
Instead, an interpreter in the browser reads over the  JavaScript code , interprets each line, and runs it.

So, in short, these languages are not at all linked with or dependent on each other.

Q #34) Which data types are supported by JavaScript?

Answer: JavaScript supports the following Seven primitives data types and Object:

(i) Boolean: This is a logical data type that can have only two values i.e. true or false. When we check the data type of ‘true’ or ‘false’ using typeof operator, it returns a boolean value.

For Example,  typeof(true) // returns boolean

Boolean values can be used for comparing two variables.

For Example, 

var x = 2;
var y = 3;
x==y //returns false

The boolean value can also be used to check a condition

For Example, 

var x = 2;
var y = 3;
If(x<y){
alert(‘Hi’);
}

If the above condition ‘x<y’ is true, the alert gets pop up.

A boolean variable can be created using the Boolean() function.

var myvar = ‘Hi';
Boolean(myvar); // This returns true because the 'myvar' value exists

Also, the Boolean object can be created using the new operator as follows:

var myobj = new Boolean(true);

(ii) NullThis is a data type that is represented by only one value, the ‘null’ itself. A null value means no value.

For Example, 

var x = null;
console.log(x);// This returns null

If we check the data type of a using the typeof operator, we get:

typeof(x); // This returns object. type of a null value is an object, not null. 

(iii) Undefined: This data type means a variable that is not defined. The variable is declared but it does not contain any value.

For Example, 

var x;
console.log(x); // This returns undefined
x=10;//Assign value to x
console.log(x); // This returns 10

The variable ‘a’ has been declared but hasn’t been assigned a value yet.
We can assign a value to a:

(iv) Number: This data type can be a floating-point value, an integer, an exponential value, a ‘NaN’ or an ‘Infinity’.

For Example, 

var x=10; // This is an integer value
var y=10.5; // decimal value
var c = 10e5 // an exponential value 
‘xyz’ * 10; //This returns NaN
10/0; // This returns infinity

Number literal can be created by using the Number() function:

var x = Number(10); 
console.log(x);// This returns 10

Also, the number object can be created using the ‘new’ operator as follows:

var x= new Number(10);
console.log(x); // This returns 10

(v) BigInt: This is a numeric primitive which can represent integers with arbitrary precision. BigInt is created by appending n to the end of an integer

For Example, 

const x = 15n;

The number can be converted to a BigInt with the BigInt(number) function.

const x = 251;
const y = BigInt(x);
y === 251n // returns true

(vi) String: This data type is used to represent textual data.

For Example, 

var strVar1 = “Hi,how are you?”; 
var strVar2 = ‘Hi,how are you?’;

New string can also be created using String() function as follows:

var strVar3 = String(‘Hi,how are you?’); // This creates a string literal with value ‘Hi,how are you?’

The String() function is also used to convert a non-string value to a string.

String(150); // This statement will create a string ‘150’

String can also be created using ‘new' operator

var strVar4 = new String(“Hi,how are you?”); // This is a string object
console.log(strVar4); // This will return the string ‘Hi,how are you?’

JavaScript strings are immutable i.e. once a string is created, it can’t be modified. But another string can be created using an operation on the original string.

For Example, 

(vii) Symbol: This is a unique and immutable primitive value and used as the key of an Object property. Symbols are new to JavaScript in ECMAScript 2015

Symbol value represents a unique identifier.

For Example, 

var symVar1 = Symbol("Symbol1");
let symVar2 = Symbol("Symbol1"); 
console.log(symVar1 === symVar2); // This returns "false".

So, many symbols are created with the same description, but with different values.

Symbols can’t be auto-converted.

For Example, 

var symVar1 = Symbol("Symbol1");
alert(symVar1); // This gives TypeError: Cannot convert a Symbol value to a string

This can be worked using toString() as follows:

alert(symVar1.toString()); // Symbol(symVar1), this works

Object data type

An object is a value in memory referenced by an identifier.

Object refers to a data structure having data and instructions to work with the data. Objects sometimes refer to real-world things, For Example,  an employee or a car.

For Example, 

In JavaScript objects, values are written as name:value pairs as below:

var car1 = {type:"BMW", model:” The BMW X5“, color:"white"};
An object definition can span multiple lines as follows:
var car1 = {
type:"BMW",
model: "The BMW X5",
color:"white"
};

The name:values pairs are called properties. For Example,  ‘type’ is property and ‘BMW’ is the value of the property.

Property values are accessed using objectName.propertyName

or objectName[“propertyName”]

For Example,  car1.type or car1[“type”] , returns ‘BMW’

Value of the object car1 can be changed as follows:

car1.type = “Audi”;

Now,

console.log(car1) ;//This will return {type:"Audi", model:” The BMW X5“ , color:"white"};

Q #35) Is JavaScript a case-sensitive language?

Answer: Yes, JavaScript is a case sensitive language. Meaning of this is keywords of the language, variables, function names, and any other identifiers that must always be typed with consistent uppercase or lower-case letters.

For Example,  myVar is a different variable to myvar.

Q #36) How to determine what data type an operand belongs to?

Answer:  Operand data type can be found using the typeof operator

It returns a string indicating the type of the operand.

Syntax: typeof operand

typeof(operand)

The operand can be any variable, object or function.

For Example, 

console.log (typeof 10);// expected output: "number"
console.log (typeof 'hello');// expected output: "string"
console.log (typeof<declared But UndefinedVariable>);//expected output: //"undefined";

Q #37) Why JavaScript is called as a loosely typed or a dynamic language?

Answer:  JavaScript is called as a loosely typed or a dynamic language because JavaScript variables are not directly associated with any value type and any variable can be assigned and re-assigned values of all types:

For Example, 

var myvar = ‘abc’; // myvar is string
myvar =true; // myvar is now a boolean
myvar = 10; // myvar is now a number

Q #38) What is null in JavaScript?

Answer: The value null represents the intentional absence of any object value.

This is one of JavaScript's primitive values.

For Example, 

Var myvar = null;
console.log(myvar); //This will print null

Q #39) What is NaN?

Answer: NaN is a property of global object representing Not-A-Number.

For Example, 

function checkValue(x) {
if (isNaN(x)) {
return NaN;
}
return x;
}

console.log(checkValue ('5')); //expected output: "5"
console.log(checkValue (‘Any value’)); //expected output: NaN

Q #40) How to split a string into array items?

Answer: A string can be split into an array using the JavaScript split() method. This method takes a single parameter, the character you want to separate the string at, and returns the substrings between the separator as items in an array.

For Example, 

myDaysString = ''Sunday,Monday,Tuesday,Wednesday”;
String can be split at comma as below:
myDaysArray= myDaysString.split(',');
console.log(myDaysArray[0]); //output is the first item in the array i.e. Sunday
console.log (myDaysArray[myDaysArray.length-1]); //output is the last //item in the array i.e. Wednesday

Q #41) How to join array items into a string?

Answer: Array items can be joined using the join() method.

For Example, 

var myDaysArray= ["Sunday","Monday","Tuesday",”Wednesday”];

Array items are joined into a string as follows:

myDaysString= myDaysArray.join(',');
console.log(myDaysString);//output is joined string i.e.//Sunday,Monday,Tuesday,Wednesday

Q #42) What type of errors does JavaScript have?

Answer: Following are the 2 types of error:

  • Syntax errors: These are typos or errors in spelling in the code which cause the program not to run at all or stop working partway through. Usually, error messages are also provided.
  • Logic errors: These are errors when the syntax is correct, but the logic or code is inaccurate. Here, the program runs successfully without errors. But output results are incorrect. These are often harder to fix than syntax errors as these programs don’t give any error messages for logic errors.

Q #43) How to handle a large number of choices for one condition in an effective way?

Answer: This is done using switch statements:

For Example, 

switch (expression) {
case choice1:
code to be run
break;

case choice2:
code to be run
break;

:
:

default:
code to run if there is no case match
}

Q #44) What is a ternary operator?

Answer: The ternary or conditional is an operator that is used to make a quick choice between two options based on a true or false test.

This can be used as a substitute forif…else block when having two choices that are chosen between a true/false condition.

For Example, 

if (some condition)
result = ‘result 1’;
else
result = ‘result 2’;

Same code can be written using a ternary operator in a single statement as follows:

result = (condition)?‘result 1’:‘result 2’;

Q #45) Suppose, there is an object called a person

const person = {

name : {

first: ‘Bob',

last: ‘Smith'

}

};

Which of the following is correct way of accessing the object property ‘first' ?

  • person.name.first, or
  • person[‘name'][‘first'] ?

Answer: Both are correct ways. i.e. using dots like person.name.first or using bracket notation like person[‘name'][‘first']

Q #46) What is “this”?

Answer: The ‘this' keyword refers to the current object the code is being written inside.

This is to ensure that the correct values are used when a member's context changes

For Example, there are two different instances of a person having different names and it is required to print their own name in the alert as follows:

const person1 = {
name: 'Tom',
greeting: function() {
alert('Good Morning! I am ' + this.name + '.');
}
}

Here, output is Good Morning! I am ‘Tom'

const person2 = {
name: 'Jerry',
greeting: function() {
alert('Good Morning! I am ' + this.name + '.');
}
}

Here, the output is Good Morning! I am ‘Jerry'

Q #47) What are Anonymous functions?

Answer: Anonymous functions are functions without having any name and won't do anything on their own. These are generally used along with an event handler.

For Example, in the following code, anonymous function code i.e. alert(‘Hi'); would run on click of the associated button:

var myButton = document.querySelector('button');

myButton.onclick = function() {
alert('Hi');
}

Anonymous function can also be assigned to the value of a variable.

For Example, 

var myVar = function() {
	alert('Hi');
}

This function can be invoked using:

myVar();

Conclusion

It’s better to store the JavaScript Codes, CSS, and HTML as separate External ‘js’ files. Separating the coding part and HTML part will make it easier to read and work with them. Multiple developers also find this method easier to work with simultaneously.

JavaScript Code is easy to maintain. The same set of JavaScript Codes can be used in multiple pages. If we use External JavaScript codes and if we need to change the code, then we need to change it in one place. So that we can reuse the code and maintain them in a much easier way.

JavaScript Code has better performance. External JavaScript file will increase the page loading speed as it will be cached by the browser.

I hope you have found the answers to the most frequently asked interview questions on ‘JavaScript’. Practice as many questions as possible and be confident.

Best of luck with the interview!!