In this tutorial, I have shared the top 62 javascript interview questions and answers according to my working experience. These questions are useful for freshers as well as experienced developers.
Those developers who are looking for a job in the IT field, they have the best option here to prepare for an interview. Generally, most of the interviewers ask the maximum questions of this article. So, I suggest that you must prepare all the given questions for 2021.
Top JavaScript Questions 2020 | Developer Must Prepare
If you want to get a job in the web development field, you must know javaScript. Because It is frequently used for front-end & back-end web applications.
JavaScript is a very interesting language to develop your career. You can get a great job in the big MNC companies with the highest salary. It is a very important language for you. So, you must prepare these javascript interview Questions.
Read Also
PHP Interview Questions with Answers
Most Important JavaScript Interview Questions
This is the collection of the most important javascript Interview Questions with answers and examples. So, It is more helpful for fresher as well as experienced developers.
Most of the company asked these types of javascript questions in a face to face or telephonic round. So, you must prepare these questions to qualify for the interview.
1. What is JavaScript?
JavaScript is a Front-end Scripting language. It used to make the dynamic web content of the client-side of web pages.
2. Why we use javaScript?
Javascript can be used with HTML & CSS to create dynamic HTML element and CSS style.
It makes more attractive, lightweight & user-friendly web pages.
We can also use javascript for databases, many desktop and server programs like Nodejs, MongoDB are the best example.
3. How many ways to link javascript to HTML?
We can link javaScript to HTML using the following types of javascript
- Inline JavaScript
- Internal JavaScript
- External JavaScript
4. What is Inline Javascript
In Inline javaScript, we can directly write javaScript code into an open HTML tag.
Example –
Suppose that we have to show the alert message by clicking on the HTML button then
<button onclick="function(){alert('I am Inline JavaScript');}">click me<button>
5. What is Internal JavaScript
In Internal JavaScript, we can write JavaScript code into the head section with <script> </script>
element but the best way to write javaScript code just above the </body>
tag.
Example –
Suppose that we have to show a display message when a page is completely loaded by using Internal javaScript.
<script>alert('I am Internal JavaScript');</script>
6. What is External JavaScript?
In External JavaScript, we can write JavaScript code into separate javaScript file with .js
extension. and link to HTML just above the </body>
tag. But Javascript code is not written within <script></script>.
Example –
Suppose that We have an external.js file to link it just above </body>
. We can link it using the following script.
<script src="external-javascript-file.js" type="text/javascript" >
7. What is the difference between undefined & null?
JavaScript Undefined
Javascript undefined always occurs in the following cases
- It is a return value of a variable that has no value.
- It is also a value of a variable that always returns undefined.
- The data type of the undefined variable is undefined.
Example – 1
var und; document.write(und) // it returns undefined var xy=undefined; document.write(xy); // it returns undefined
Example – 2
var x; document.write(typeof x); //it returns undefined var x=undefined; document.write(typeof x); //it returns undefined
JavaScript Null
JavaScript Null Always occurs in the following cases
- It is a value of a variable than always returns a null value.
- The data type of null variable is always an object
Example – 1
var nul=null; document.write(null) // it return null
Example -2
var y=null; documnent.write(typeof y) ; //it returns object
8. What is the difference between indexof and search()?
indexOf()
can accept the second parameter but thesearch()
can’t accept the second parameter for the starting position of the string.
Example –
var mystr="I am a developer and I am learning javaScript" var srch=mystr.indexOf(am); document.write(srch); // It returns 2 var srch1= mystr.indexOf(am,5); document.write(srch1); // It returns 23
indexOf()
can accept regular expression but thesearch()
can’t accept regular expression for searching a string.
Example –
var mystr="I am a developer and I am learning javaScript" var srch=mystr.search(am); document.write(srch); // It returns 2
9. What is var Keyword?
We can use the var
keyword to create a variable according to the following conditions
- We can redeclare a var variable but It will return value of the last declared var variable.
- var variable is not a block-level scope because of We can access it outside the block.
Example – 1
var x=50 var x=80 document.write(x);
Example -2
var x=30; if(x==30) { x=80; } document.write(x); // It returns 80
10. What is let Keyword?
We can use the let
keyword to create a variable according to the following conditions
- We can’t redeclare let variable.
- let variable is a block-level scope because We can’t access it outside the block.
Example – 1
let x=50 let x=80 document.write(x); // It will produce an error
Example -2
let x=30; if(x==30) { let x=80; } document.write(x); // It returns 30 or var x=30 if(x==30) { let x=80 } document.write(x) // It returns 30
11. What is a const Keyword?
We can use the const keyword to create a variable according to the following conditions
- We can’t redeclare let variable.
- let variable is a block-level scope because We can’t access it outside the block.
Example -1
const x=50 const x=80 document.write(x); // It will produce an error
Example -2
const x=30; if(x==30) { const x=80; } document.write(x); // It returns 30 or var x=30 if(x==30) { const x=80 } document.write(x) // It returns 30
Remember – only one of var variable, let variable or const variable with same can be declared outside or inside the block.
var x=30; let x=40; const x=80; if(true) { var x=30; let x=40; const x=80; } // above variable declarations are not allowed
12. What is an arrow function?
An arrow function is defined in ES6 This function is the short form of a long function.
It does not contain a “function” keyword.
Syntax –
functionName=()=>{ // code is written here }
An Arrow function can be declared without its parenthesis if a function has only a single line of the statement.
Syntax –
functionName=()=>//single line statement here
Example –
fullName=()=> { var firstName="Sunil"; var secondName="Kumar"; return firstName+" "+secondName; } document.write(fullName()); // It returns Sunil Kumar intro=()={ return "My Name is developer"} document.write(intro()); // It returns My Name is developer // arrow funtion with parameter addition=(a,b)=>{return a+b;} document.write(addition(10,30)); // It returns 40
13. What is an anonymous function?
In javaScript, We can define a function without function is knows as an anonymous function.
Syntax-
function(){ // statement is written here }
Example –
var addNumber=function(x,y){ document.write(x+y); } addNumber(40,50); // It returns 90
14. What is a factory function?
A function that can return an object. That function will be a factory function.
We can assign a factory function to a variable.
Example –
function boyDetails(){ var boy={ name:"Ravi Kumar", age :25, city:"Jaipur" } return boy; } var res=boyDetails(); document.write(res.name); // It returns Ravi Kumar
15. How to add new HTML element dynamically
We have created a ul element with an id “newElement”.We have also created a button that has onclick with addElement(). Now We have to add a li element dynamically by clicking on the created button.
Example –
<!DOCTYPE html> <html> <body> <button onclick="addElement()">Add List</button> <ul id="newElement"></ul> <script> function addElement(){ var listNode = document.createElement("li"); var listText = document.createTextNode("I am new List"); listNode.appendChild(listText); document.getElementById("newElement").appendChild(listNode); } </script> </body> </html>
16. What is difference between == and ===?
==
and ===
are used to compare data in javascript but Both have the following difference.
double equal(==)
always compares data that have the same values & different datatype.
Example –
if(1=='1') { document.write('It is true'); }else{ document.write('It is false'); } // output - It is true
triple equal(===)
always compares data that have the same values as well as the same data type.
Example –
if(1==='1') { document.write('It is true'); }else{ document.write('It is false'); } // output - It is false
17. How to submit the form in javascript?
There are two ways are available in Javascript to submit the form
submit()
– It Can submit the form in javascript.
Example –
<form id="userForm" action=""> Name: <input type="text" name="firstName"> <input type="button" onclick="submitForm()" value="Submit"> </form> <script> function submitForm() { document.getElementById("userForm").submit(); alert('data can be posted in server through backend lenguage like php,ajax'); } </script>
onsubmit attribute-
This method calls them to submit the form in javaScript.
<body> <form onsubmit="submitForm()"> Name: <input type="text" name="firstName"> <input type="button" value="Submit"> </form> <script> function submitForm() { alert("The form was submitted"); } </script>
18. How to change class Name and style property?
Change Class Name
Before changing the class name
<p id="demo" class="first">I have old class</p>
Script to change the class name
document.getElementById("demo").className = "second";
After changing the class name
<p id="demo" class="second">I have new class</p>
Change style property:
Before changing style property
<h1 id="myId" style="color:red">I am red</h1>
Script to change the style property
document.getElementById("myId").style.color = "green";
After changing style property
<h1 id="myId" style="color:green">I am green</h1>
19. What is the use of the void(0) method?
It is mostly used in the form of javascript:void(0)
and generally used with the anchor tag. Because it prevents to refresh the web page by occurring the click event.
Suppose that, We have an anchor tag that has no redirecting page in the href
such as a href="#">click me</a>
. If we don’t want to refresh the page by clicking on it, We will use javascript:void(0)
with the anchor tag.
Example
// it will stop to refresh the web page <a href="javascript:void(0)">Click me</a>
20. What are the different types of errors in JavaScript?
There are five common javascript errors are explained below
SyntaxError – When we don’t declare valid syntax, it will generate a syntax error.
varr a=10; console.log(a); var b=func test(); console.log(b);
TypeError- When We try to run invalid value with the function, it will generate a TypeError
var a=20; console.log(a.fun()); console.log(a.slice()); console.log('noor'.fun());
ReferenceError- When We want to run a variable that is not exit, It will generate ReferenceError
console.log(myvar); var console.log(myfun());
RangeError- When We pass more than the allowed value of the function, It will generate RangError.
var cal=Number('5').toFixed(300); console.log(cal);
URIError- When We pass invalid URI to the URI-related methods. It will generate URIError
var decEr=decodeURIComponent('%'); console.log(decEr);
21. What is the Strict mode and How to enable it?
The strict mode was introduced in ES5 and used in the form of “use strict”.
It generates an error while using undeclared variables and disallowed properties
It can make a clean & secure javascript code.
To enable strict mode:
We have to declare “use strict” at the beginning of the script.
Example –
// for using undeclared variable "use strict"; x=10; // it is not declared with var keyword console.log(x); // it will generate an error // for using disallowed property var a=20; delete a; // it will generate an error // strick mode with function x=20; // it will not generate an error function mytest(){ "use strict mode"; y=30; // it will generate an error }
22. What is a For-in loop?
We can use the for-in loop for an object to access its indexes and value
syntax-
for (var index in object) { // statement of the code }
Example –
var admin = {firstName:"noor", lastName:"Khan", age:25}; var profile = ""; var i; for (i in admin) { profile += admin[i] + " "; } document.write(profile);
23. What is the forEach()?
forEach()
is used to call a function which can execute for an array
var boys = ["Amit", "Gaurav", "Suman"]; boys.forEach(myFunction); function myFunction(boyName, index) { document.write("index number is: "+item+ +" and boy name is: "+ boyName); }
24. What is the difference between call and apply?
An object can be used into another object by using call()
or apply()
but the difference is:
call()
can accept one or more values as parameters.
Example –
var boy = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + age + "," + city; } } var boy1 = { firstName:"Sunil", lastName: "Kumar" } var boyCall=boy.fullName.call(boy1, 24, "Patna"); document.write(boyCall);
apply()
can only accept an array as parameters.
Example –
var boy = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + age + "," + city; } } var boy1 = { firstName:"Sunil", lastName: "Kumar" } var boyApply=boy.fullName.apply(boy1, [24, "Patna"]); document.write(boyApply);
25. Is the javaScript variable Case sensitive?
Yes, We have given three examples below for better understanding if we declare two variable names that are uppercase & lowercase format respectively but both contain the same name as
Example –
var boy="Sunil Kumar" ; document.write(boy) // It gives output Sunil Kumar Var Boy ="Ankit Kumar"; documnet.write(Boy) // It gives output Ankit Kumar
We have declared below two variable names and both contain the same name and uppercase format as-
Example –
var Boy="Sunil Kumar" ; document.write(boy) // It gives output Sunil Kumar Var Boy ="Ankit Kumar"; documnet.write(Boy) // It gives output Sunil Kumar
See the below example has two variable names and both contain the same name and lowercase format as-
Example –
var boy="Sunil Kumar" ; document.write(boy) // It gives output Sunil Kumar Var boy ="Ankit Kumar"; documnet.write(Boy) // It gives output Sunil Kumar
26. What is the difference between toString() and join()?
toString()
and join()
are used to convert an array to a string but Both have the following difference
toString()
can not accept parameter.
Example –
var arr1=["Amit","Rahul",3,10,"Radha"]; var str=arr1.toString(); document.write(str); // It returns Amit,Rahul,3,10,Radha
join()
can accept a single parameter to separate array values of a converted string.
Example –
var arr1=["Amit","Rahul",3,10,"Radha"]; var str1=arr1.join("*"); document.write(str1); // It returns Amit*Rahul*3*10*Radha
27. What is DOM?
DOM stands for Document Object Model that is Application Programming Interface for HTML, XML document types.
DOM allows JavaScript code to create, update, delete, and modify dynamically the web pages.
28. What are NaN and isNaN?
JavaScript NaN
NaN stands for Not a Number It is always returned a number but it is not a valid number for mathematical operation in javascript.
Example –
document.write(typeOf NaN); // It returns Number
When we perform an arithmetic operation with a non-numeric string value or NaN value and numeric string then It will always return NaN.
Example –
var num=20/"mohan"; document.write(num); // it returns NaN var num1=20*mohan; document.write(num1); // It returns NaN var num2= 20%mohan; document.write(num2); // It returns NaN or var num3= 20/NaN; document.write(num3); // it returns NaN var num4= 20*NaN; document.write(num4); // it returns NaN var num5= 20%NaN; document.write(num5); // it returns NaN
If We perform arithmetic addition or subtraction operation with NaN value and numeric string, It will concatenate those numbers.
Example –
var num=NaN+"20"; document.write(num) // It returns NaN20 var num1="20"+NaN; document.write(num1) // It returns 20NaN var num2=NaN document.write(num1) // It returns NaN
JavaScript isNaN
It can check a variable or arithmetic operation is NaN or not.if it is NaN, it will return true otherwise false.
Example –
var checkNum=20/"Amit"; document.write(isNaN(checkNum)) //It returns true var checkNum1=NaN; document.write(isNaN(checkNum1)) //It returns true
29. What is noscript tag?
We use noscript tag to disable script in the browser or the browser which does not support script.
When the users stop to run the script on their browser then noscript will run.
It will also run when the browser does not support script.
Example –
<script> document.write("I am JavaScript") </script> <noscript>I'm unable to run in your browser!</noscript>
30. What is the closure function?
Closure function is the concept of a nested function that is a function that can be created inside another function. The inner function can have access to the outer function is known as closure function. The outer function can not have access to inner function.
Example –
function outerFunction(){ var x="This is outer function"; function innerFunction(){ var y="this is inner function"; document.write(y); document.write(x); } document.write(y) // It can't be accessed } outerFunction();
31. What is an immediately invoked function?
Immediately invoked is the function that can execute automatically without calling it.
If you want to run a function without calling it just after loading the web page then you can use the Immediately invoked function.
Example –
(function () { document.write("I am Immediately invoked function"); })()
32. How to create a cookie in javascript?
document.cookie = "username=Noor Khan";
Basic JavaScript Interview Questions for Fresher
This is the collection of the basic JavaScript Interview Questions with answers and examples. It is more necessary for fresher and experienced developers.
These types of javascript Interview questions are asked in a face to face or telephonic round. So, you must prepare these questions to face the interview
1. Define common methods for javascript output?
JavaScript has the following five common methods to displays output.
document.write()
It can show output on the web page but it removes all the existing content of that page.
if we give an HTML element inside this method. it can only display its effect.
Example –
documnet.write("This text can display on web page");
console.log()
- It can show output inside the console section of the web browser.
- We can mainly use it to check errors of javaScript code.
- If we give an HTML code inside this method it will show that HTML code.
Example –
console.log("This message can display inside console section of Browser");
window.alert()
- It displays the alert message in the form of a popup box.
- It has an ok button to close the popup box.
- You can use
alert()
instead ofwindow.alert()
.
Example –
window.alert('I am Confirm message'); alert('I am Confirm message');
window.confirm()
- It displays the confirmation message in the form of a popup box.
- It has an ok & a cancel button.
- You can use
confirm()
instead ofwindow.confirm()
.
Example –
window.alert('I am Confirm message'); alert('I am Confirm message');
window.prompt
- It displays the input field in the form of a popup box to take users’ input.
- It has an ok & a cancel button.
- You can use
prompt()
instead ofwindow.prompt()
.
Example –
window.prompt('I am ready to take user input'); prompt('I am ready to take user input');
2. What are the rules for declaring javascript Variable?
Most Important rules for declaring the variable name such as-
- The first character of a variable name must be a letter or dollar
$
, underscore_
sign.
Example –
var abc; var _myname; var $boyname="Amit Kumar";
- A variable name can be declared with a combination of digits, letters, dollars
$
, , and underscore_
sign.
Example-
var ab2; var x34y; var boy$name; var first_name;
- A variable name can describe as case sensitive means that we can declare two variables with the same name but both are in the form of uppercase and lowercase respectively then both variables will always treat as different.
Example-
var boy; var BOY; // here, both variables are different.
3. How to check the data type of the javascript variable?
javaScript has an operator is typeof that is used to find data type of a variable.
Example –
typeof " " // It returns string type
typeof "amit"; // It returns string type
typeof null; // It returns object type
typeof undefined; // It returns undefined type
typeof 45; // It returns number type
typeof 4.12 // It returns number type
typeof true; // It returns boolean type
typeof false; // It returns boolean type
typeof x // It returns undefined type if x has no assigned value
typeof [1,2,4,5] // It returns object type
typeof {name:"amit", age:24} // It returns object type
typeof function jsfunction(){} // It returns function type
4. What is the difference between break and continue?
break Statement
It can stop the loop at the specified condition.
Example
for(var i=1;i<=20;i++{ if(i==5){ break; } document.write(i); // It returns 1 2 3 4 }
continue statement
It skips only specified conditions and continues the loop.
Example –
for(var i=1;i<=10;i++) { if(i==5){ continue; } document.write(i); // It returns 1 2 3 4 6 7 8 9 10 }
5. What are the Differences between pop() and push()?
pop() method
It can delete elements from the last index of an array.
Example –
var popArr=[4,5,10,2,8,1]; popArr.pop(); document.write(popArr); // It returns 4,5,10,2,8
It can return the deleted element of an array.
Example –
var popArr=[4,5,10,2,8,1]; var popRes= popArr.pop(); document.write(popRes); // It returns 1
push() method
It can insert a new element into the last index of an array.
Example –
var pushpArr=[4,5,10,2,8,1]; popArr.push(12); document.write(pushArr); // It returns 4,5,10,2,8,1,12
It can return the length of the new array.
Example –
var pushpArr=[4,5,10,2,8,1]; var pushRes=popArr.push(12); document.write(pushRes); // It returns 7
6. What are the differences between shift() and unshift()?
shift() method
It can remove an element from the first index of an array.
Example –
var shiftArr=[4,5,10,2,8,1]; shiftArr.shift(); document.write(shiftArr); // It returns 5,10,2,8,1
It can return removed element of an array.
Example –
var shiftArr=[4,5,10,2,8,1]; var shiftRes= shiftArr.shift(); document.write(shiftRes); // It returns 4
unshift() method
It can insert a new element into the last index of an array.
Example –
var unshiftArr=[4,5,10,2,8,1]; unshiftArr.unshift(12); document.write(unshiftArr); // It returns 12,4,5,10,2,8,1
This method can return the length of the new array.
Example –
var unshiftArr=[4,5,10,2,8,1]; var unshiftRes=unshiftArr.unshift(12); document.write(unshiftRes); // It returns 7
7. How to find the string length?
We can find the length of a string by using the length property of javaScript. length property can return the whole length of a string by counting its characters from 1 index with including one or more white spaces.
Example –
var myStr="I am Learning Javascript" var len =myStr.length; document.write(len); // it returns 24 // if We add Add two white spaces at the beginning var myStr="I am Learning Javascript" var len =myStr.length; document.write(len); // it returns 26
8. What are the differences between splice and slice()?
splice() method
It can add one or more new elements to the specified index of an array.
It can remove an existing element from the specified index of an array.
We can pass three arguments to the splice() such as
Syntax –
splice(add,remove,elements);
- add- an integer value of the index for adding new elements
- remove-total number of removing element
- elements- one or more new element for adding to an array
slice() method
It can’t add a new element to an array.
It can’t remove an element.
We can create a new array to take a part of array elements on the basis of its specified index as an argument.
Syntax-
slice(startIndex,endIndex);
- startIndex – We can include start position
- endIndex- We can’t include end position
9. What is concat() method?
concat()
the method returns a new array by merging two or more created arrays.- one of those created arrays &
concat()
the method is concatenated with dot.
symbol and other arrays are passed as parameters ofconcat()
. concat()
method can accept one or more elements as parameters.
10. What are the ways for javaScript comment?
There are two ways available in javascript to comment statements
- single-line comment- We can comment on a single line statement by using // symbol
- Multiple line Comment- We can comment two or more statements by using /* multiple line statements here */
Example –
// this is single line comment /* this is line 1 this is line 2 this is line 3 */
11. What is an event?
An event can perform actions on the web pages. such as
- clicking an element
- submission a form
- scrolling the web page
- hovering on the element
Advanced JavaScript Interview Questions for Experienced
This is the collection of the basic Advanced JavaScript Interview Questions with answers and examples.
It is more necessary for experienced developers. But Beginner developers may prepare these types of questions.
1. What can We do in javaScript?
We can do the following work in javascript.
- Updating HTML content
- Updating HTML Style
- Showing HTML element
- Hiding HTML element
- updating values of HTML attribute
Updating HTML Content
We can update HTML content on the behalf of its id by using one of the most popular methods as getElementById() and innerHTML.
Example –
Suppose that We have to change the content of a paragraph with it’s given id is “changeContent” then
document.getElementById('changeContent').innerHTML="change content text";
Updating HTML STyle
We can update the style of an HTML element on the behalf of it’s given id by using getelementById() and style attribute.
Example –
Suppose that, We have to change the color of a paragraph text with it’s given id “changeColor”.
document.getElementById("changeColor").style.color = "red";
Showing HTML Element
We can show an HTML element on the behalf of it’s given id by using getElementById() and style attribute
Example –
suppose that We have to show paragraph with it’s given id is “showMe” then-
document.getElementById("showMe").style.display = "block";
Hiding HTML Elements
We can hide an HTML element on the behalf of it’s given id by using getElementById() and style attribute
Example –
Suppose that We have to show paragraph with it’s given id is “hideMe” then
document.getElementById("hideMe").style.display = "block";
Updating Values of HTML Attributes
We can update the attribute value of an HTML on the behalf of it’s given id by using getElementById() and it’s attribute name.
Example –
Suppose that We have to change the value of href attribute from old-url.html to new-url.html then
document.getElementById('elementID').href='new-url.html'";
2. How to create an object and access it’s properties?
To create an object, first of all, we have to declare an object name in the form of a variable to store an object such as
Example –
var developer={ fullName:"Amit Kumar", age:25, department:technology, homeTown:Noida, state:Uttar Pradesh, pin:201304 fullAddress:function(){ return this.homeTown+", "+this.state+", "+this.pin; } }
Ways to Access object properties
We can access object properties through the following ways
- objectName.propertyName
Example –
var fn=developer.fullName; document.write(fn) // It returns Amit kumar var totalAge=developer.age; document.write(totalAge); //it returns 25; var dep=developer.department; document.write(dep); // it returns technology var home=developer.homeTown; document.write(home) // it returns Noida var stateName=developer.state; document.write(stateName); // it returns Uttar Pradesh var pinCode= developer.pin; document.write(pinCode); // it returns pinCode
- objectName[‘propertyName]
Example –
var fn=developer.["fullName"]; document.write(fn) // It returns Amit kumar var totalAge=developer.["age"]; document.write(totalAge); //it returns 25; var dep=developer.["department"]; document.write(dep); // it returns technology var home=developer.["homeTown"]; document.write(home) // it returns Noida var stateName=developer.["state"]; document.write(stateName); // it returns Uttar Pradesh var pinCode= developer.["pin"]; document.write(pinCode); // it returns pinCode
3. What are the methods to extract a part of a string?
There are three methods are given below to extract a part of a string
- slice()
- substr()
- substring
slice() method
slice()
can extract a part of a string on the basis of its two parameters.
It accepts the first parameter for the start position and the second parameter for the end position.
The extracted part of a string will return as a new string.
slice(startPosition, endPosition) or slice(-endPosition,-startPosition)
When we use slice(startPosition, endPosition) In this case, the position of a string will be counted from left to right.
startPosition
It the position from where the string will be extracted and a letter of this position will be included.
suppose that, we have a string “I am learning javaScript” and its startPosition is 3 then “m” letter will be part of a string that is starting position from left.
endPositionac
It is the position till where the string will be extracted and a letter of this position will not be included.
Suppose that, we have a string “I am learning JavaScript” and its endPosition is 5 then “l” letter will not be part of a string that is end position from.
var mystr="I am Learning JavaScript"; var ext1= mystr.slice(2,3); // It returns m var ex2=mystr.slice(2) // it returns am learning javaScript
When we use slice(-startPosition,-endPosition) , the position of a string will be counted from right to left
-startPosition
It is the position where the string will be extracted and a letter of this position will not be included.
suppose that, we have a string “I am learning javaScript” and its startPosition is 3 then “r” letter will not be part of a string that is starting position from right.
-endPosition
It is the position till where the string will be extracted and a letter of this position will not be included.
suppose that we have a string “I am learning JavaScript” and its endPosition is 5 then “l” letter will not be part of a string that is end position from right.
var mystr= "I am learning javaScript"; var ext1=mystr.slice(-10,-6) // It returns java var ext2= mystr.slice(-10) // It returns javaScript
substr() method
substr()
the same as the slice()
but it can extract a part of a string on the basis of its two parameters such as the first parameter is declared for start position and the second parameter is declared for length.
syntax–
substr(startPosition,length)
here, length can be counted from its start position.
Example –
var mystr="I am learning javaScript"; var ext= mystr.substr(5,8); document.write(ext); // It returns learning var ext1=mystr.substr(5); document.write(ext1); // It returns learning javaScript var ext2=mystr.substr(-10); // It returns javaScript
substring() method
substring()
is the same as slice()
but It can’t accept negative parameters.
syntax-
substring(startPosition,endPosition)
var mystr="I am learning javaScript"; var ext= mystr.substring(5,8); document.write(ext); // It returns learn var ext1= mystr.substring(5) document.write(ext1) //It returns learning javaScript
4. What is the difference between array and object?
An array can be an object but an object can’t be an array.
An array value can be declared within the greatest brackets but object properties can be declared within the parenthesis.
Array–
var arr= [value1,value2,value3....valuen];
Object
var obj= { property1:value1, property2:value2, property3:value3, .... propertyn:valuen };
An Array can have a numeric index that starts from the first position of an array value with 0 indexes. but An object can have numeric & string which is custom declared
Object
var arr=[ Amit,25,patna ] var name=arr.[0]; document.write(name); // It returns Amit var age= arr.[1]; document.write(age); // It returns 25 var city=arr.[2]; document.write(city); // It returns patna
Array
var obj={ name:Amit, age:25, city:patna } var name=arr.["name"]; document.write(name); // It returns Amit var age= arr.["age"]; document.write(age); // It returns 25 var city=arr.["city]; document.write(city); // It returns patna
5. What is the scope of variables in javaScript?
We can use function Scope of variables in two ways
Local Scope
In this scope, we can define variables within the function and will only use within the function.so, it is known as the local variable Scope.
Example –
function localFunction() { var boyName = "Amit Kumar"; document.write(boyName); // it returns Amit Lumar } document.write(boyName); // it returns undefined
Global Scope
In this scope, we can define variables outside the function and will only use within the function as well as outside of function.so, it is known as local variable Scope.
Example –
var boyName = "Amit Kumar"; function localFunction(){ document.write(boyName); // it returns Amit Lumar } document.write(boyName); // it returns Amit Kumar
6. What is hoisting in javaScript?
We can use a variable before its declaration in javaScript.so, this behavior is hoisting.
Example –
x = 5; // Assign 5 to x document.write(x); var x; // Declare x
7. What is function expression?
A variable is declared to store a function is known as a function expression.
We have to always call a function expression with a pair of small brackets.
We can’t call a function expression before the function definition.
Example –
var funEx= addNumber(a,b){ return a+b; } var res=funExt(40,10); document.write(res); // It returns 50
8. Define common methods to access an HTML element?
We can access an HTML element by using the following common methods.
document.getElementById()
In this method, We can access the HTML element by the declared id name.
Example –
<body> <p id="para">I am paragraph with id name para</p> <script> document.getElementById("para").style.color = "red"; </script> </body>
document.getElementsByTagName()
In this method, We can access an html element by declared it’s tagname.
Example –
<body> <ul> <li>One</li> <li>Two</li> <li>Three</li> </ul> <p id="demo"></p> <script> var x = document.getElementsByTagName("li"); var firstList= x[0].innerHTML; var secondList= x[1].innerHTML; var thirdList= x[2].innerHTML; document.write(firstList); // It returns One document.write(secondList); // It returns Two document.write(thirdList); // It returns Three </script> </body>
document.getElementByClassName()
This method can access the html element by its declared class name.
Example –
<body> <p class="para">I am paragraph with id name para</p> <script> document.getElementByClassName("para").style.color = "red"; </script>
document.querySelector()
In this method, we can access the first element of the declared attribute.
Example –
<body> <p class="para">this is the first paragraph</p> <p class="para">this is the second paragraph</p> <p class="para">this is the third paragraph</p> <script> document.querySelector("p").style.backgroundColor = "red"; </script> </body>
<body> <p class="para">this is first paragraph</p> <p class="example">this is first paragraph</p> <p class="example">this is first paragraph</p> <script> document.querySelector(".para").style.backgroundColor = "red"; </script> </body>
JavaScript Coding Interview Questions
- These are coding based javascript interview questions for the written test.
- These questions more necessary for experienced developers and freshers can prepare as well
- After preparing the javascript coding question, you will able to solve any level of questions.
1. change an element “books” of an array to fruits. array is [“boys”, “animals”, “books”, “girls”]?
First of all, We have to declare a variable to store array then change “books” element of that array to “fruits” by using its index.
var changeArr=["boys", "animals", "books", "girls"]; changeArr[2]="fruits"; document.write(changeArr); // It returns boys,animals,fruits,girls
2. Write javaScript code for 10+30+”mycode”+30+50?
var sum=10+30+"mycode"+30+50; document.write(sum); // It returns 40mycode3040
In this question, addition contains numbers and a string. So, javaScript can only add those numbers which remain before the string and remaining numbers will concatenate as a string.
3. Write JavaScript code for 200/jscode?
200/”jscode”=In this case, we want to divide a number by a non-numeric string that is not possible.so it will return NaN
var myNum=200/"jscode"; document.write(myNum); // It return NaN
4. Solve 20+40+NaN in javaScript?
20+40+NaN- Here, the number is going to add with NaN.so, it will return NaN
var res=20+40+NaN; document.write(res); // It returns NaN
5. What is the result of 20+”40″+NaN?
20+”40″+NaN- Here, a number and the numeric string is going to add with NaN.so it will return 2040NaN
var res=20+”40″+NaN; document.write(res); // It returns 2040NaN
6. What is the output of 20+40+NaN+”5″?
20+40+NaN+”5″ – Here, numbers and numeric string are going to add with NaN. So, It will return NaN5
var res=20+40+NaN+”5″; document.write(res); // It returns NaN5
7. How to code for NaN+”5″+20+40?
NaN+”5″+20+40 it returns NaN52040
var res=NaN+”5″+20+40; document.write(res); // It returns NaN52040
8. How to code for 10/0 and -10/0?
10/0 returns infinity and -10/0 returns -infinity
var num1=10/0; document.write(num1); // It returns infinity var num2= -10/0 document.write(num2); // It returns -infinity
9. What is the result of 10+”40”?
10+”40″ here 10 is a number and 40 is a numeric string. So, it will return to 1040.
var res=10+”40″; document.write(res); // It returns 1040
10. How to calculate 10+”40″ is 50 in javascript?
As the previous Question, 10+”40″ it returns 1040 because of it has not added due to 40 is a numeric string.so we have to add this and get results 50. first of all, We have to use Number() method to convert numeric string to a number then it will return 50
var res=10+ Number(”40″); document.write(res); // It returns 50
11. How to calculate 34.132783 as 34.13?
We can solve this question by using toFixed() method
var fixed=34.132783; var cal=fixed.toFixed(); document.write(cal); // It returns 34.13
Suggestion
Dear developer, I have shared the top javaScript interview Questions according to my working experience. If you will prepare the given questions, you will definitely qualify the interview.