Below is the list of latest and updated JavaScript interview questions and
their answers for freshers as well as experienced users. These
interview questions will help you to prepare for the interviews, So let’s start….
When would you use var in your declaration and when you wouldn’t?
Always use var. Not using var for variable declaration will traverse scopes all the way up till the global scope. If variable with that name is not found it will declare it in the global scope. Therefore not using var implicitly declares variable in the global scope (which, let me remind you, is a bad practice).
(function() {
   baz = 5;
   var bar = 10;
})();
 
console.log(baz); // outputs 5
//console.log(bar); // error: bar is not defined
A common mistake is to not use var in loops which might, in some cases, bear unexpected results or pollute the global scope:
(function() {
    var baz = "Hello World";
    for(var bar=1; bar
What does the attribute defer/async do when added to the script tag?
The defer attribute will cause browser to execute script after the document has been parsed. This attribute was first implemented in Internet Explorer 4, then added to HTML 4 and more recently HTML 5 spec. You might not have heard of it as it has not been supported till version 3.5 (Gecko 1.9.2). Async is another attribute that can affect how a script is loaded and executed, here is a quote from HTML 5 spec on how this is expected to work:

There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.

Note: A somewhat (but not exactly) similar defer behavior can be achieved by placing your script tags at the end of the body tag and that’s what is considered to be modern ‘best practice’
What is the difference between == and ===? Which one would you use?
The equality (==) operator will compare for equality after doing necessary type casting, the identity operator (===) doesn’t do any conversions. A good practice suggested by Douglas Crockford is to always use strict equality,  couple of examples from Douglas’ book JavaScript: The Good Parts
'' == '0'          // false
0 == ''            // true
0 == '0'           // true
 
false == 'false'   // false
false == '0'       // true
 
false == undefined // false
false == null      // false
null == undefined  // true
How would you check if a variable is null/undefined?
//check if bar is null
bar === null
//check if bar is undefined
typeof bar === "undefined"
How do you check if a variable is an object

You can use typeof to determine if variable is an object, however bear in mind that null is actually an object! However null object is ‘falsy’ thus the following will work:

if(bar && typeof bar === "object") {
    console.log('bar is object and is not null');
}
Discuss  scoping in JavaScript.
JavaScript has lexical scoping based on functions but not blocks. Therefore:
//global scope
(function() {
    //anonymous function scope
    var foo = 1;
    function bar() {
        //bar function scope
        var foo = 2;
    }
    bar();
    console.log(foo); //outputs 1
    if(true) {
        var foo = 3; //redeclares foo
    }
    console.log(foo); //outputs 3
})();
Explain hoisting in JavaScript.
As some might not be familiar with the term ‘hoisting’ yet have the relevant experience this question could be asked indirectly
In JavaScript function declarations ( function foo() {} ) and variable declarations ( var bar  ) are ‘hoisted’ i.e. are silently moved to the very top of the scope. Consider the following code:
(function() {
    console.log(bar); //returns 'undefined'
    //console.log(baz) // error: baz is not defined
    foo(); // outputs 'aloha' to the console
 
    //function declaration AND its body is hoisted
    function foo() {
        console.log('aloha');
    }
    //variable declaration is hoisted but value assignment stays here
    var bar = 1;
    baz = 2; //defines baz in global scope
})();
What are closures?
(function() {
    function foo(x) {
        var baz = 3;
        return function (y) {
        console.log(x + y + (++baz));
        }
    }
var moo = foo(2); // moo is now a closure.
moo(1); // 7
moo(1); // 8!
})();
The inner function inside foo will close-over the variables of foo before leaving creating a closure.
Explain prototypal/differential inheritance
Conceptually this is very simple: A new object can inherit properties of an old object.
(function() {
    var genericObject = {
        bar : "Hello World",
        get_bar : function() {
            return this.bar;
        }
    };
    var customObject = Object.create(genericObject);
    customObject.bar = "Aloha folks!";
    console.log(customObject.get_bar()); //outputs: "Aloha folks"
    delete customObject.bar;
    console.log(customObject.get_bar()); //fallbacks to the prototype's value, outputs: "Hello World"
})();
While JavaScript has always been a prototype-oriented language, tools to work with prototypes were somewhat missing. Object.create used in the code snipped above has been added in ECMAScript 5 and has not been supported prior to Firefox 4, Chrome 5, IE 9
What is Strict Mode in JavaScript
Strict Mode has been introduced as part of ECMAScript 5 and introduces new, restricted variant of JavaScript which has following aims:
  • Throws errors for actions that are rather silly but previously didn’t throw an error
  • Throws errors for potentially unsafe actions
  • Disables functions that are poorly thought out
  • Potentially code in strict mode could run faster by eliminating mistakes that would make it difficult for JavaScript engines to perform optimizations
Strict mode can be enabled for the entire source file or on per function basis by adding a string literal “use strict” on top of the file/function i.e.
function foo(){
  "use strict";
  // ... your code ...
}
What is JavaScript?

Ans:JavaScript is a scripting language most often used for client-side web development.

What is the difference between JavaScript and Jscript?

Ans:Both JavaScript and Jscript are almost similar. JavaScript was
developed by Netscape. Microsoft reverse engineered Javascript and
called it JScript.

How do we add JavaScript onto a web page?

Ans:There are several way for adding JavaScript on a web page, but there are two ways which are commonly used by developers
If your script code is very short and only for single page, then following ways are the best:
a) You can place <script type="text/javascript"> tag inside the <head> element.

<head>
<title>Page Title</title>
<script language="JavaScript" type="text/javascript">
   var name = "Vikas Ahlawta"
   alert(name);
</script>
</head>
b) If your script code is very large, then you can make a JavaScript file and add its path in the following way:
<head>
<title>Page Title</title>
<script type="text/javascript" src="myjavascript.js"></script>
</head>
Is JavaScript case sensitive?

Ans:Yes!
A function getElementById is not the same as getElementbyID.

What are the types used in JavaScript?
Ans:String, Number, Boolean, Function, Object, Null, Undefined.
What are the boolean operators supported by JavaScript?
And Operator: &&

Or Operator: ||
Not Operator: !
What is the difference between “==” and “===”?

Ans:
“==” checks equality only,
“===” checks for equality as well as the type.

How to access the value of a textbox using JavaScript?

Ans:
ex:-

<!DOCTYPE html>
<html>
<body>
Full name: <input type="text" id="txtFullName" 
name="FirstName" value="Vikas Ahlawat">
</body>
</html>
There are following ways to access the value of the above textbox:
var name = document.getElementById('txtFullName').value;
alert(name);
or:
we can use the old way:
document.forms[0].mybutton.

var name = document.forms[0].FirstName.value;
alert(name);
Note: This uses the “name” attribute of the element to locate it.
What are the ways of making comments in JavaScript?

Ans:

// is used for line comments
ex:- var x=10; //comment text

/*
*/  is used for block comments

ex:-

var x= 10; /* this is
block comment example.*/
How will you get the Checkbox status whether it is checked or not?

Ans:

var status = document.getElementById('checkbox1').checked; 
alert(status);
will return true or false.
How to create arrays in JavaScript?

Ans:There are two ways to create array in JavaScript like other languages:

a) The first way to create array
Declare Array:
var names = new Array(); 
Add Elements in Array:-
names[0] = "Vikas";
names[1] = "Ashish";
names[2] = "Nikhil";
b) This is the second way:
var names = new Array("Vikas", "Ashish", "Nikhil");
If an array with name as “names” contain three elements, then how will you print the third element of this array?

Ans: Print third array element document.write(names[2]);
Note:- Array index starts with 0.

How do you submit a form using JavaScript?

Ans:Use document.forms[0].submit();

What does isNaN function do?

Ans:
It returns true if the argument is not a number.
Example:

document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2013/06/23")+ "<br>");
document.write(isNaN(123)+ "<br>");
The output will be:
true
true
false
What is the use of Math Object in JavaScript?

Ans:
The math object provides you properties and methods for mathematical constants and functions.
ex:-

var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
var z = Math.sin(90);    Returns the sine of 90
What do you understand by this keyword in JavaScript?

Ans: In JavaScript the this is a context-pointer and not an
object pointer. It gives you the top-most context that is placed on the
stack. The following gives two different results (in the browser, where
by-default the window object is the 0-level context):

var obj = { outerWidth : 20 }; 
function say() {
    alert(this.outerWidth);
} 
say();//will alert window.outerWidth
say.apply(obj);//will alert obj.outerWidth
What does “1”+2+4 evaluate to?

Ans: Since 1 is a string, everything is a string, so the result is 124.

What does 3+4+”7″ evaluate to?

Ans: Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it is concatenation, so 77 is the result.

How do you change the style/class on any element using JavaScript?

Ans:

document.getElementById(“myText”).style.fontSize = “10";

-or-

document.getElementById(“myText”).className = “anyclass”;
Does JavaScript support foreach loop?

Ans: JavaScript 1.6(ECMAScript 5th Edition) support foreach loop,

What looping structures are there in JavaScript?

Ans: for, while, dowhile loops

What is an object in JavaScript, give an example?

Ans:
An object is just a container for a collection of named values:
// Create the man object

var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;
How you will add function as a property in a JavaScript object? Give an example.
Ans:
var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;
man.getName = function() { return man.name;}
console.log(man.getName()); // Logs 'Vikas Ahlawat'.
What is the similarity between the 1st and 2nd statement?

1st:- var myString = new String('male'); // An object.
2nd:- var myStringLiteral = 'male'; // Primitive string value, not an object.
Ans: Both will call String() constructor function
You can confirm it by running the following statement:

console.log(myString.constructor, myStringLiteral.constructor);
What will be the output of the following statements?
var myString = 'Vikas' // Create a primitive string object.
var myStringCopy = myString; // Copy its value into a new variable.
var myString = null; // Manipulate the value
console.log(myString, myStringCopy);
Ans: // Logs 'null Vikas'
Consider the following statements and tell what would be the output of the logs statements?
var price1 = 10;
var price2 = 10;
var price3 = new Number('10'); // A complex numeric object because new was used.
console.log(price1 === price2); 
console.log(price1 === price3);

Ans:

console.log(price1 === price2); // Logs true.
console.log(price1 === price3); /* Logs false because price3 
contains a complex number object and price 1
is a primitive value. */
What would be the output of the following statements?
var object1 = { same: 'same' };
var object2 = { same: 'same' };
console.log(object1 === object2);
Ans: // Logs false, JavaScript does not care that they are identical and of the same object type.
When comparing complex objects, they are equal only when they reference the same
object (i.e., have the same address). Two variables containing identical objects are not
equal to each other since they do not actually point at the same object.

What would be the output of the following statements?

var object1 = { same: 'same' };
var object2 = object1;
console.log(object1 === object2);

Ans: // Logs true

What is this?
var myArray = [[[]]];

Ans: Three dimensional array

Name any two JavaScript functions which are used to convert nonnumeric values into numbers?

Ans:

Number()
parseInt()
parseFloat()
var n1 = Number(“Hello world!”); //NaN
var n2 = Number(“”);             //0
var n3 = Number(“000010”);       //10
var n4 = Number(true);           //1
var n5 = Number(NaN);            //NaN
Does JavaScript Support automatic type conversion, If yes give example.
Ans: Yes! Javascript support automatic type conversion. You should take advantage of it, It is most common way of type conversion used by Javascript developers.
Ex.
var s = '5';
var a = s*1;
var b = +s;
typeof(s); //"string"
typeof(a); //"number"
typeof(b); //"number"