JavaScript Q&A
Q1).What is JavaScript?
JavaScript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.
Other way:- JavaScript is a scripting language most often used for client-side web development.
Q2).What is Difference between JavaScript and Jscript?
Both JavaScript and Jscript are almost similar. Java script was developed by Netscape. Microsoft reverse engineered Javascript and called it JScript.
Q3).How do we add JavaScript onto a web page?
There are serveral way for adding javascript on a web page but there are two way with is commonly userd by developers
If your script code is very short and only for single page then following ways is best.
A). You can place <script > tag inside the <head> element.
<head>
<title>MyPage Title</title>
<script language="JavaScript" >
var name = "Om Singh"
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>MyPage Title</title>
<script src="myjavascript.js"></script>
</head>
Q4).Is JavaScript case sensitive?
Yes javaScript is case sensitive.
Like-A function getElementById is not the same as getElementbyID
Q5).What are the types used in JavaScript?
String, Number, Boolean, Function, Object, Null, Undefined.
Q6).What are the boolean operators sported by JavaScript?
And Operator: &&
Or Operator: ||
Not Operator: !
Q7).What is the difference between “==” and “===”?
“==” checks equality only,
“===” checks for equality as well as the type.
Q8).How to access the value of a textbox using JavaScript?
<!DOCTYPE html>
<html>
<body>
Full name: <input id="txtFullName" name="FirstName" value="Om Singh">
</body>
</html>
There are following way 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.
Q9).What are the way of make comment in Javascript?
// 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.*/
Q10).How you will get the CheckBox status whether it is checked or not?
var status = document.getElementById('checkbox1').checked;
alert(status);
it will return true or false
Q11).How to create arrays in JavaScript?
There are Two way dor create array in Javascript like other languages..
a) first way to create array
Declare Array:-
var names = new Array();
Add Elements in Array:-
names[0] = "Rahul";
names[1] = "Sumit";
names[2] = "Amrit";
b) this is second way
var names = new Array("Rahul", "Sumit", "Amrit");
Q12).If an array with name as "names" contain three elements then how you will print the third element of this array?
Print third array element document.write(names[2]);
Note:- array index start with 0
Q13).How do you submit a form using Javascript?
Use document.forms[0].submit();
Q14).What does isNaN function do?
It Return true if the argument is not a number.
ex:-
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2013/06/13")+ "<br>");
document.write(isNaN(123)+ "<br>");
output :-
true
true
false
Q15).What is the use of Math Object in Javascript?
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
Q16).What do you understand by this keyword in javascript?
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
Q17).What does "1"+2+4 evaluate to?
Since 1 is a string, everything is a string, so the result is 124.
Q18).What does 3+4+"7" evaluate to?
Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it’s concatenation, so 77 is the result.
Q19).How do you change the style/class on any element using javascript?
document.getElementById(“myText”).style.fontSize = “10";
-or-
document.getElementById(“myText”).className = “anyclass”;
Q20).Does javascript support foreach loop?
Yes it is, Please see this link for more clarification :
http://jsfiddle.net/Osingh/76sx1vv6/
Q21).What looping structures are there in JavaScript?
for, while, do-while loops
Q22).what is an object in JavaScript, give an example?
An object is just a container for a collection of named values
// Creating man object
var man = new Object();
man.name = 'Om Singh';
man.living = true;
man.age = 27;
Q23).How you will add function as a property in a JavaScript object? Give some example.
var man = new Object();
man.name = 'Om Singh';
man.living = true;
man.age = 27;
man.getName = function() { return man.name;}
console.log(man.getName()); // Logs 'Om Singh'.
Q24).What is the similarity between 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 run the following statement
console.log(myString.constructor, myStringLiteral.constructor);
Q25).What will be the output of the following statements?
var myString = 'Om'; // 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);
Q26).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. */
Q27).What would be the output of the following statements?
var object1 = { same: 'same' };
var object2 = { same: 'same' };
console.log(object1 === object2);
Ans:- // Logs false, JavaScipt 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.
Q28).What would be the output of the following statements?
var object1 = { same: 'same' };
var object2 = object1;
console.log(object1 === object2);
Ans:- // Logs true
Q29).What is this?
var myArray = [[[]]];
Ans:- Three dimantional array
Q30).Name any two JavaScript functions which are used for convert nonnumeric values into numbers?
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
Q31).What is the use of IsNan() function in JavaScript?
isNaN() function accepts a single argument, which can be of any data type, to determine if the value is “not a number.”.
alert(isNaN(“red”)); //true - cannot be converted to a number
alert(isNaN(true)); //false - can be converted to number 1
alert(isNaN(NaN)); //true
alert(isNaN(5)); //false - 5 is a number
alert(isNaN(“5”)); //false - can be converted to number 5
Q32).Can you describe "===" operator?
The identically equal operator is represented by three equal signs "===" and returns true only if the operands are equal without
conversion, as in this example.
var result1 = (“55” == 55); //true - equal because of conversion
var result2 = (“55” === 55); //false - not equal because different data
Q33).DOM method "document.getElementById()" didn’t exist in Internet Explorer
prior to version 5. What is the way to detect that "document.getElementById()" is supported by the browser or not?
if (document.getElementById){
return document.getElementById("txtBox1");
}
else {
throw new Error(“getElementById function not supported by browser”);
}
Q34).How do you check if a variable is an array in JavaScript?
We can use "instanceof Array"
Example:
if (v1 instanceof Array) {
alert('v1 is Array!');
} else {
alert('v1 is not an array');
}
Q35).What is the difference between following two ?
a).var myfunc = function() {}
b).function myfunc() {}
var myfunc = function() {} defines a variable that references an anonymous function.
function myfunc() {} defines a named function "myfunc".
Q36).When we try to convert a sting into Boolean then in JavaScritp it will show error/true/false?
var message = "Hello!!";
var messageAsBoolean = Boolean(message);
alert(messageAsBoolean);
Ans:-Alert box will show "true"
Other Conversion
<!DOCTYPE html>
<html>
<head>
<script>
var SimpleString = "Hello World!!";
var EmptyString = "";
var ZeroNumber = 0;
var NoneZeroNumber = 7;
var NanString = NaN;
var Obj = new Object();
var Undifined;
//Convert into Boolean
var SimpleStringAsBoolean = Boolean(SimpleString); //true
var EmptyStringAsBoolean = Boolean(EmptyString); //fasle
var ZeroNumberAsBoolean = Boolean(ZeroNumber); //false
var NoneZeroNumberAsBoolean = Boolean(NoneZeroNumber); //true
var NanStringAsBoolean = Boolean(NanString); //false
var UndifinedAsBoolean = Boolean(Undifined); //false
//See result
alert(SimpleStringAsBoolean); //Will Show "true"
alert(EmptyStringAsBoolean); //Will Show "false"
alert(ZeroNumberAsBoolean); //Will Show "false"
alert(NoneZeroNumberAsBoolean); //Will Show "true"
alert(NanStringAsBoolean); //Will Show "false"
alert(UndifinedAsBoolean); //Will Show "false"
</script>
</head>
<body>
Q36).What will be the output of below statement?
alert(NaN == NaN);
it will show false
because NaN is not equal to any value, including NaN.
Q37).What is the difference between undefined value and null value?
Undefined value: If a value that is not defined and has no keyword then it is known as undefined. For example in the declaration, int num; the num has undefined value.
Null value: If a value that is explicitly specified by the keyword ‘null’ then it is known as null value. For example in the declaration, String str=null; the str has a null value.
Q38).What would be the difference if we declare two variables inside a JavaScript, one with 'var' keyword and another without 'var' keyword?
The variable with var keyword inside a function is treated as Local variable.
and the variable without var keyword inside a function is treated a global variable.
Q39).Have a look on the following script and tell me which the global/local variables here are.
<script>
var n1= 10;
function my_function()
{
var n2 = 0;
n3 = 0;
}
</script>
Ans:-
<script>
var n1= 10; // Global
function my_function()
{
var n2 = 0; // is a local
n3 = 0; // is a global
}
</script>
Top Essential JavaScript Interview Questions
Q40).What will the code below output to the console and why?
(function(){
var a = b = 3;
})();
console.log("a defined? " + (typeof a !== 'undefined'));
console.log("b defined? " + (typeof b !== 'undefined'));
Solution:-
Since both a and b are defined within the enclosing scope of the function, and since the line they are on begins with the var keyword, most JavaScript developers would expect typeof a and typeof b to both be undefined in the above example.
However, that is not the case. The issue here is that most developers incorrectly understand the statement var a = b = 3; to be shorthand for:
var b = 3;
var a = b;
But in fact, var a = b = 3; is actually shorthand for:
b = 3;
var a = b;
As a result (if you are not using strict mode), the output of the code snippet would be:
a defined? false
b defined? true
But how can b be defined outside of the scope of the enclosing function? Well, since the statement var a = b = 3; is shorthand for the statements b = 3; and var a = b;, b ends up being a global variable (since it is not preceded by the var keyword) and is therefore still in scope even outside of the enclosing function.
Note that, in strict mode (i.e., with use strict), the statement var a = b = 3; will generate a runtime error of ReferenceError: b is not defined, thereby avoiding any headfakes/bugs that might othewise result. (Yet another prime example of why you should use use strict as a matter of course in your code!)
Q41).What will the code below output to the console and why?
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();
Solution:
Above code will output the following :
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
In the outer function, both this and self refer to myObject and therefore both can properly reference and access foo.
In the inner function, though, this no longer refers to myObject. As a result, this.foo is undefined in the inner function, whereas the reference to the local variable self remains in scope and is accessible there. (Prior to ECMA 5, this in the inner function would refer to the global window object; whereas, as of ECMA 5, this in the inner function would be undefined.)
Q42).What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?
is is an increasingly common practice, employed by many popular JavaScript libraries (jQuery, Node.js, etc.). This technique creates a closure around the entire contents of the file which, perhaps most importantly, creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries.
Another feature of this technique is to allow for an easily referenceable (presumably shorter) alias for a global variable. This is often used, for example, in jQuery plugins. jQuery allows you to disable the $ reference to the jQuery namespace, using jQuery.noConflict(). If this has been done, your code can still use $ employing this closure technique, as follows:
(function($) { /* jQuery plugin code referencing $ */ } )(jQuery);
Q43).What is the significance, and what are the benefits, of including 'use strict' at the beginning of a JavaScript source file?
the short and most important answer here is that use strict is a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions. In general, it is a good practice.
Some of the key benefits of strict mode include:
Q44).Consider the two functions below. Will they both return the same thing? Why or why not?
function foo1()
{
return {
bar: "hello"
};
}
function foo2()
{
return
{
bar: "hello"
};
}
Solution:
Surprisingly, these two functions will not return the same thing. Rather:
console.log("foo1 returns:");
console.log(foo1());
console.log("foo2 returns:");
console.log(foo2());
will yield:
foo1 returns:
Object {bar: "hello"}
foo2 returns:
undefined
Not only is this surprising, but what makes this particularly gnarly is that foo2() returns undefined without any error being thrown.
The reason for this has to do with the fact that semicolons are technically optional in JavaScript (although omitting them is generally really bad form). As a result, when the line containing the return statement (with nothing else on the line) is encountered in foo2(), a semicolon is automatically inserted immediately after the return statement.
No error is thrown since the remainder of the code is perfectly valid, even though it doesn’t ever get invoked or do anything (it is simply an unused code block that defines a property bar which is equal to the string "hello").
This behavior also argues for following the convention of placing an opening curly brace at the end of a line in JavaScript, rather than on the beginning of a new line. As shown here, this becomes more than just a stylistic preference in JavaScript.
Q45).What is NaN? What is its type? How can you reliably test if a value is equal to NaN?
The NaN property represents a value that is “not a number”. This special value results from an operation that could not be performed either because one of the operands was non-numeric (e.g., "abc" / 4), or because the result of the operation is non-numeric (e.g., an attempt to divide by zero).
While this seems straightforward enough, there are a couple of somewhat surprising characteristics of NaN that can result in hair-pulling bugs if one is not aware of them.
For one thing, although NaN means “not a number”, its type is, believe it or not, Number:
console.log(typeof NaN === "number"); // logs "true"
Additionally, NaN compared to anything – even itself! – is false:
console.log(NaN === NaN); // logs "false"
A semi-reliable way to test whether a number is equal to NaN is with the built-in function isNaN(), but even using is NaN
A better solution would either be to use value !== value, which would only produce true if the value is equal to NaN. Also, ES6 offers a new Number.isNaN() function, which is a different and more reliable than the old global isNaN() function.
Q46).What will the code below output? Explain your answer.?
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 == 0.3);
An educated answer to this question would simply be: “You can’t be sure. it might print out “0.3” and “true”, or it might not. Numbers in JavaScript are all treated with floating point precision, and as such, may not always yield the expected results.”
The example provided above is classic case that demonstrates this issue. Surprisingly, it will print out:
0.30000000000000004
false
Q47).Discuss possible ways to write a function isInteger(x) that determines if x is an integer. ?
This may sound trivial and, in fact, it is trivial with ECMAscript 6 which introduces a new Number.isInteger() function for precisely this purpose. However, prior to ECMAScript 6, this is a bit more complicated, since no equivalent of the Number.isInteger()method is provided.
The issue is that, in the ECMAScript specification, integers only exist conceptually; i.e., numeric values are always stored as floating point values.
With that in mind, the simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following:
function isInteger(x) { return (x^0) === x; }
The following solution would also work, although not as elegant as the one above:
function isInteger(x) { return Math.round(x) === x; }
Note that Math.ceil() or Math.floor() could be used equally well (instead of Math.round()) in the above implementation.
Or alternatively:
function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }
One fairly common incorrect solution is the following:
function isInteger(x) { return parseInt(x, 10) === x; }
While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:
> String(1000000000000000000000)
'1e+21'
> parseInt(1000000000000000000000, 10)
1
> parseInt(1000000000000000000000, 10) === 1000000000000000000000
false
Q48).What will the following code output to the console ?
console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10));
Solution:
The code will output the value of 10 factorial (i.e., 10!, or 3,628,800).
Here’s why:
The named function f() calls itself recursively, until it gets down to calling f(1) which simply returns 1. Here, therefore, is what this does:
f(1): returns n, which is 1
f(2): returns 2 * f(1), which is 2
f(3): returns 3 * f(2), which is 6
f(4): returns 4 * f(3), which is 24
f(5): returns 5 * f(4), which is 120
f(6): returns 6 * f(5), which is 720
f(7): returns 7 * f(6), which is 5040
f(8): returns 8 * f(7), which is 40320
f(9): returns 9 * f(8), which is 362880
f(10): returns 10 * f(9), which is 3628800
Q49).Consider the code snippet below. What will the console output be and why?
(function(x) {
return (function(y) {
console.log(x);
})(2)
})(1);
Solution:
The output will be 1, even though the value of x is never set in the inner function. Here’s why:
As explained a closure is a function, along with all variables or functions that were in-scope at the time that the closure was created. In JavaScript, a closure is implemented as an “inner function”; i.e., a function defined within the body of another function. An important feature of closures is that an inner function still has access to the outer function’s variables.
Therefore, in this example, since x is not defined in the inner function, the scope of the outer function is searched for a defined variable x, which is found to have a value of 1.
Q50).What will the following code output to the console and why ?
var hero = {
_name: 'John Doe',
getSecretIdentity: function (){
return this._name;
}
};
var stoleSecretIdentity = hero.getSecretIdentity;
console.log(stoleSecretIdentity());
console.log(hero.getSecretIdentity());
What is the issue with this code and how can it be fixed...
Solution:
The code will output:
undefined
John Doe
The first console.log prints undefined because we are extracting the method from the hero object, so stoleSecretIdentity() is being invoked in the global context (i.e., the window object) where the _name property does not exist.
One way to fix the stoleSecretIdentity() function is as follows:
var stoleSecretIdentity = hero.getSecretIdentity.bind(hero);
Q51).Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate children). For each element visited, the function should pass that element to a provided callback function ?
The arguments to the function should be:
-a DOM element
-a callback function (that takes a DOM element as its argument)
Solution:-
Here’s an example solution:
function Traverse(p_element,p_callback) {
p_callback(p_element);
var list = p_element.children;
for (var i = 0; i < list.length; i++) {
Traverse(list[i],p_callback); // recursive call
}
}
Q52).How to open URL in new tab in JavaScript?
Solution:
use javascript, window.open function.
window.open('http://osingh.weebly.com/','_blank');
Q53).How to get current date in JavaScript?
var today = new Date();
console.log(today);
Q54).How do I declare a namespace in JavaScript?
var myNamespace = {
function1: function() { },
function2: function() { }
function3: function() { }
};
myNamespace.function3();
Q55).What is the best way to detect a mobile device in jQuery?
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
}
Q56).How to detect mobiles including ipad using navigator.useragent in javascript ?
if(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone/i)){
console.log('Calling from Mobile');
}else{
console.log('Calling from Web');
}
Q57).How to detect mobiles including ipad using navigator.useragent in javascript?
if(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone/i)){
console.log('Calling from Mobile');
}else{
console.log('Calling from Web');
}
Q58).How to check an variable is Object OR String OR array?
Use below function to get Data type of javascript variable.
function checkDataType(someVar){
result ='String';
if(someVar instanceof Object){
result ='Object'
}
if($.isArray(someVar)){
result = 'Array';
}
return result;
}
var someVar= new Array("Saab", "Volvo", "BMW");
console.log(result);
Q59).How to modify the URL without reloading the page?
window.history.pushState('page2', 'This is page Title', '/newpage.php');
Q60).How to convert Object to String?
var myobject=['Web','Technology','Experts','Notes']
JSON.stringify(myobject);
Q61).How to convert JSON String to Object?
var jsonData = '{"name":"web technology","year":2015}';
var myobject = JSON.parse(jsonData);
console.log(myobject);
Q62).How to set a default parameter value for a JavaScript function?
/** Here email is parameter in which we have set the default value i.e [email protected] **/
function function1(name, email)
{
email = typeof email !== 'undefined' ? email : '[email protected]';
console.log('name='+name+', Email= '+email);
}
function1('john','[email protected]');
function1('john');
Done>>>>><<<<<........!!!
JavaScript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.
Other way:- JavaScript is a scripting language most often used for client-side web development.
Q2).What is Difference between JavaScript and Jscript?
Both JavaScript and Jscript are almost similar. Java script was developed by Netscape. Microsoft reverse engineered Javascript and called it JScript.
Q3).How do we add JavaScript onto a web page?
There are serveral way for adding javascript on a web page but there are two way with is commonly userd by developers
If your script code is very short and only for single page then following ways is best.
A). You can place <script > tag inside the <head> element.
<head>
<title>MyPage Title</title>
<script language="JavaScript" >
var name = "Om Singh"
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>MyPage Title</title>
<script src="myjavascript.js"></script>
</head>
Q4).Is JavaScript case sensitive?
Yes javaScript is case sensitive.
Like-A function getElementById is not the same as getElementbyID
Q5).What are the types used in JavaScript?
String, Number, Boolean, Function, Object, Null, Undefined.
Q6).What are the boolean operators sported by JavaScript?
And Operator: &&
Or Operator: ||
Not Operator: !
Q7).What is the difference between “==” and “===”?
“==” checks equality only,
“===” checks for equality as well as the type.
Q8).How to access the value of a textbox using JavaScript?
<!DOCTYPE html>
<html>
<body>
Full name: <input id="txtFullName" name="FirstName" value="Om Singh">
</body>
</html>
There are following way 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.
Q9).What are the way of make comment in Javascript?
// 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.*/
Q10).How you will get the CheckBox status whether it is checked or not?
var status = document.getElementById('checkbox1').checked;
alert(status);
it will return true or false
Q11).How to create arrays in JavaScript?
There are Two way dor create array in Javascript like other languages..
a) first way to create array
Declare Array:-
var names = new Array();
Add Elements in Array:-
names[0] = "Rahul";
names[1] = "Sumit";
names[2] = "Amrit";
b) this is second way
var names = new Array("Rahul", "Sumit", "Amrit");
Q12).If an array with name as "names" contain three elements then how you will print the third element of this array?
Print third array element document.write(names[2]);
Note:- array index start with 0
Q13).How do you submit a form using Javascript?
Use document.forms[0].submit();
Q14).What does isNaN function do?
It Return true if the argument is not a number.
ex:-
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2013/06/13")+ "<br>");
document.write(isNaN(123)+ "<br>");
output :-
true
true
false
Q15).What is the use of Math Object in Javascript?
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
Q16).What do you understand by this keyword in javascript?
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
Q17).What does "1"+2+4 evaluate to?
Since 1 is a string, everything is a string, so the result is 124.
Q18).What does 3+4+"7" evaluate to?
Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it’s concatenation, so 77 is the result.
Q19).How do you change the style/class on any element using javascript?
document.getElementById(“myText”).style.fontSize = “10";
-or-
document.getElementById(“myText”).className = “anyclass”;
Q20).Does javascript support foreach loop?
Yes it is, Please see this link for more clarification :
http://jsfiddle.net/Osingh/76sx1vv6/
Q21).What looping structures are there in JavaScript?
for, while, do-while loops
Q22).what is an object in JavaScript, give an example?
An object is just a container for a collection of named values
// Creating man object
var man = new Object();
man.name = 'Om Singh';
man.living = true;
man.age = 27;
Q23).How you will add function as a property in a JavaScript object? Give some example.
var man = new Object();
man.name = 'Om Singh';
man.living = true;
man.age = 27;
man.getName = function() { return man.name;}
console.log(man.getName()); // Logs 'Om Singh'.
Q24).What is the similarity between 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 run the following statement
console.log(myString.constructor, myStringLiteral.constructor);
Q25).What will be the output of the following statements?
var myString = 'Om'; // 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);
Q26).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. */
Q27).What would be the output of the following statements?
var object1 = { same: 'same' };
var object2 = { same: 'same' };
console.log(object1 === object2);
Ans:- // Logs false, JavaScipt 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.
Q28).What would be the output of the following statements?
var object1 = { same: 'same' };
var object2 = object1;
console.log(object1 === object2);
Ans:- // Logs true
Q29).What is this?
var myArray = [[[]]];
Ans:- Three dimantional array
Q30).Name any two JavaScript functions which are used for convert nonnumeric values into numbers?
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
Q31).What is the use of IsNan() function in JavaScript?
isNaN() function accepts a single argument, which can be of any data type, to determine if the value is “not a number.”.
alert(isNaN(“red”)); //true - cannot be converted to a number
alert(isNaN(true)); //false - can be converted to number 1
alert(isNaN(NaN)); //true
alert(isNaN(5)); //false - 5 is a number
alert(isNaN(“5”)); //false - can be converted to number 5
Q32).Can you describe "===" operator?
The identically equal operator is represented by three equal signs "===" and returns true only if the operands are equal without
conversion, as in this example.
var result1 = (“55” == 55); //true - equal because of conversion
var result2 = (“55” === 55); //false - not equal because different data
Q33).DOM method "document.getElementById()" didn’t exist in Internet Explorer
prior to version 5. What is the way to detect that "document.getElementById()" is supported by the browser or not?
if (document.getElementById){
return document.getElementById("txtBox1");
}
else {
throw new Error(“getElementById function not supported by browser”);
}
Q34).How do you check if a variable is an array in JavaScript?
We can use "instanceof Array"
Example:
if (v1 instanceof Array) {
alert('v1 is Array!');
} else {
alert('v1 is not an array');
}
Q35).What is the difference between following two ?
a).var myfunc = function() {}
b).function myfunc() {}
var myfunc = function() {} defines a variable that references an anonymous function.
function myfunc() {} defines a named function "myfunc".
Q36).When we try to convert a sting into Boolean then in JavaScritp it will show error/true/false?
var message = "Hello!!";
var messageAsBoolean = Boolean(message);
alert(messageAsBoolean);
Ans:-Alert box will show "true"
Other Conversion
<!DOCTYPE html>
<html>
<head>
<script>
var SimpleString = "Hello World!!";
var EmptyString = "";
var ZeroNumber = 0;
var NoneZeroNumber = 7;
var NanString = NaN;
var Obj = new Object();
var Undifined;
//Convert into Boolean
var SimpleStringAsBoolean = Boolean(SimpleString); //true
var EmptyStringAsBoolean = Boolean(EmptyString); //fasle
var ZeroNumberAsBoolean = Boolean(ZeroNumber); //false
var NoneZeroNumberAsBoolean = Boolean(NoneZeroNumber); //true
var NanStringAsBoolean = Boolean(NanString); //false
var UndifinedAsBoolean = Boolean(Undifined); //false
//See result
alert(SimpleStringAsBoolean); //Will Show "true"
alert(EmptyStringAsBoolean); //Will Show "false"
alert(ZeroNumberAsBoolean); //Will Show "false"
alert(NoneZeroNumberAsBoolean); //Will Show "true"
alert(NanStringAsBoolean); //Will Show "false"
alert(UndifinedAsBoolean); //Will Show "false"
</script>
</head>
<body>
Q36).What will be the output of below statement?
alert(NaN == NaN);
it will show false
because NaN is not equal to any value, including NaN.
Q37).What is the difference between undefined value and null value?
Undefined value: If a value that is not defined and has no keyword then it is known as undefined. For example in the declaration, int num; the num has undefined value.
Null value: If a value that is explicitly specified by the keyword ‘null’ then it is known as null value. For example in the declaration, String str=null; the str has a null value.
Q38).What would be the difference if we declare two variables inside a JavaScript, one with 'var' keyword and another without 'var' keyword?
The variable with var keyword inside a function is treated as Local variable.
and the variable without var keyword inside a function is treated a global variable.
Q39).Have a look on the following script and tell me which the global/local variables here are.
<script>
var n1= 10;
function my_function()
{
var n2 = 0;
n3 = 0;
}
</script>
Ans:-
<script>
var n1= 10; // Global
function my_function()
{
var n2 = 0; // is a local
n3 = 0; // is a global
}
</script>
Top Essential JavaScript Interview Questions
Q40).What will the code below output to the console and why?
(function(){
var a = b = 3;
})();
console.log("a defined? " + (typeof a !== 'undefined'));
console.log("b defined? " + (typeof b !== 'undefined'));
Solution:-
Since both a and b are defined within the enclosing scope of the function, and since the line they are on begins with the var keyword, most JavaScript developers would expect typeof a and typeof b to both be undefined in the above example.
However, that is not the case. The issue here is that most developers incorrectly understand the statement var a = b = 3; to be shorthand for:
var b = 3;
var a = b;
But in fact, var a = b = 3; is actually shorthand for:
b = 3;
var a = b;
As a result (if you are not using strict mode), the output of the code snippet would be:
a defined? false
b defined? true
But how can b be defined outside of the scope of the enclosing function? Well, since the statement var a = b = 3; is shorthand for the statements b = 3; and var a = b;, b ends up being a global variable (since it is not preceded by the var keyword) and is therefore still in scope even outside of the enclosing function.
Note that, in strict mode (i.e., with use strict), the statement var a = b = 3; will generate a runtime error of ReferenceError: b is not defined, thereby avoiding any headfakes/bugs that might othewise result. (Yet another prime example of why you should use use strict as a matter of course in your code!)
Q41).What will the code below output to the console and why?
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();
Solution:
Above code will output the following :
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
In the outer function, both this and self refer to myObject and therefore both can properly reference and access foo.
In the inner function, though, this no longer refers to myObject. As a result, this.foo is undefined in the inner function, whereas the reference to the local variable self remains in scope and is accessible there. (Prior to ECMA 5, this in the inner function would refer to the global window object; whereas, as of ECMA 5, this in the inner function would be undefined.)
Q42).What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?
is is an increasingly common practice, employed by many popular JavaScript libraries (jQuery, Node.js, etc.). This technique creates a closure around the entire contents of the file which, perhaps most importantly, creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries.
Another feature of this technique is to allow for an easily referenceable (presumably shorter) alias for a global variable. This is often used, for example, in jQuery plugins. jQuery allows you to disable the $ reference to the jQuery namespace, using jQuery.noConflict(). If this has been done, your code can still use $ employing this closure technique, as follows:
(function($) { /* jQuery plugin code referencing $ */ } )(jQuery);
Q43).What is the significance, and what are the benefits, of including 'use strict' at the beginning of a JavaScript source file?
the short and most important answer here is that use strict is a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions. In general, it is a good practice.
Some of the key benefits of strict mode include:
- Makes debugging easier. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions, alerting you sooner to problems in your code and directing you more quickly to their source.
- Prevents accidental globals. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript. In strict mode, attempting to do so throws an error.
- Eliminates this coercion. Without strict mode, a reference to a this value of null or undefined is automatically coerced to the global. This can cause many headfakes and pull-out-your-hair kind of bugs. In strict mode, referencing a a this value of null or undefined throws an error.
- Disallows duplicate property names or parameter values. Strict mode throws an error when it detects a duplicate named property in an object (e.g., var object = {foo: "bar", foo: "baz"};) or a duplicate named argument for a function (e.g., function foo(val1, val2, val1){}), thereby catching what is almost certainly a bug in your code that you might otherwise have wasted lots of time tracking down.
- Makes eval() safer. There are some differences in the way eval() behaves in strict mode and in non-strict mode. Most significantly, in strict mode, variables and functions declared inside of an eval() statement are not created in the containing scope (they are created in the containing scope in non-strict mode, which can also be a common source of problems).
- Throws error on invalid usage of delete. The delete operator (used to remove properties from objects) cannot be used on non-configurable properties of the object. Non-strict code will fail silently when an attempt is made to delete a non-configurable property, whereas strict mode will throw an error in such a case.
Q44).Consider the two functions below. Will they both return the same thing? Why or why not?
function foo1()
{
return {
bar: "hello"
};
}
function foo2()
{
return
{
bar: "hello"
};
}
Solution:
Surprisingly, these two functions will not return the same thing. Rather:
console.log("foo1 returns:");
console.log(foo1());
console.log("foo2 returns:");
console.log(foo2());
will yield:
foo1 returns:
Object {bar: "hello"}
foo2 returns:
undefined
Not only is this surprising, but what makes this particularly gnarly is that foo2() returns undefined without any error being thrown.
The reason for this has to do with the fact that semicolons are technically optional in JavaScript (although omitting them is generally really bad form). As a result, when the line containing the return statement (with nothing else on the line) is encountered in foo2(), a semicolon is automatically inserted immediately after the return statement.
No error is thrown since the remainder of the code is perfectly valid, even though it doesn’t ever get invoked or do anything (it is simply an unused code block that defines a property bar which is equal to the string "hello").
This behavior also argues for following the convention of placing an opening curly brace at the end of a line in JavaScript, rather than on the beginning of a new line. As shown here, this becomes more than just a stylistic preference in JavaScript.
Q45).What is NaN? What is its type? How can you reliably test if a value is equal to NaN?
The NaN property represents a value that is “not a number”. This special value results from an operation that could not be performed either because one of the operands was non-numeric (e.g., "abc" / 4), or because the result of the operation is non-numeric (e.g., an attempt to divide by zero).
While this seems straightforward enough, there are a couple of somewhat surprising characteristics of NaN that can result in hair-pulling bugs if one is not aware of them.
For one thing, although NaN means “not a number”, its type is, believe it or not, Number:
console.log(typeof NaN === "number"); // logs "true"
Additionally, NaN compared to anything – even itself! – is false:
console.log(NaN === NaN); // logs "false"
A semi-reliable way to test whether a number is equal to NaN is with the built-in function isNaN(), but even using is NaN
A better solution would either be to use value !== value, which would only produce true if the value is equal to NaN. Also, ES6 offers a new Number.isNaN() function, which is a different and more reliable than the old global isNaN() function.
Q46).What will the code below output? Explain your answer.?
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 == 0.3);
An educated answer to this question would simply be: “You can’t be sure. it might print out “0.3” and “true”, or it might not. Numbers in JavaScript are all treated with floating point precision, and as such, may not always yield the expected results.”
The example provided above is classic case that demonstrates this issue. Surprisingly, it will print out:
0.30000000000000004
false
Q47).Discuss possible ways to write a function isInteger(x) that determines if x is an integer. ?
This may sound trivial and, in fact, it is trivial with ECMAscript 6 which introduces a new Number.isInteger() function for precisely this purpose. However, prior to ECMAScript 6, this is a bit more complicated, since no equivalent of the Number.isInteger()method is provided.
The issue is that, in the ECMAScript specification, integers only exist conceptually; i.e., numeric values are always stored as floating point values.
With that in mind, the simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following:
function isInteger(x) { return (x^0) === x; }
The following solution would also work, although not as elegant as the one above:
function isInteger(x) { return Math.round(x) === x; }
Note that Math.ceil() or Math.floor() could be used equally well (instead of Math.round()) in the above implementation.
Or alternatively:
function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }
One fairly common incorrect solution is the following:
function isInteger(x) { return parseInt(x, 10) === x; }
While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:
> String(1000000000000000000000)
'1e+21'
> parseInt(1000000000000000000000, 10)
1
> parseInt(1000000000000000000000, 10) === 1000000000000000000000
false
Q48).What will the following code output to the console ?
console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10));
Solution:
The code will output the value of 10 factorial (i.e., 10!, or 3,628,800).
Here’s why:
The named function f() calls itself recursively, until it gets down to calling f(1) which simply returns 1. Here, therefore, is what this does:
f(1): returns n, which is 1
f(2): returns 2 * f(1), which is 2
f(3): returns 3 * f(2), which is 6
f(4): returns 4 * f(3), which is 24
f(5): returns 5 * f(4), which is 120
f(6): returns 6 * f(5), which is 720
f(7): returns 7 * f(6), which is 5040
f(8): returns 8 * f(7), which is 40320
f(9): returns 9 * f(8), which is 362880
f(10): returns 10 * f(9), which is 3628800
Q49).Consider the code snippet below. What will the console output be and why?
(function(x) {
return (function(y) {
console.log(x);
})(2)
})(1);
Solution:
The output will be 1, even though the value of x is never set in the inner function. Here’s why:
As explained a closure is a function, along with all variables or functions that were in-scope at the time that the closure was created. In JavaScript, a closure is implemented as an “inner function”; i.e., a function defined within the body of another function. An important feature of closures is that an inner function still has access to the outer function’s variables.
Therefore, in this example, since x is not defined in the inner function, the scope of the outer function is searched for a defined variable x, which is found to have a value of 1.
Q50).What will the following code output to the console and why ?
var hero = {
_name: 'John Doe',
getSecretIdentity: function (){
return this._name;
}
};
var stoleSecretIdentity = hero.getSecretIdentity;
console.log(stoleSecretIdentity());
console.log(hero.getSecretIdentity());
What is the issue with this code and how can it be fixed...
Solution:
The code will output:
undefined
John Doe
The first console.log prints undefined because we are extracting the method from the hero object, so stoleSecretIdentity() is being invoked in the global context (i.e., the window object) where the _name property does not exist.
One way to fix the stoleSecretIdentity() function is as follows:
var stoleSecretIdentity = hero.getSecretIdentity.bind(hero);
Q51).Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate children). For each element visited, the function should pass that element to a provided callback function ?
The arguments to the function should be:
-a DOM element
-a callback function (that takes a DOM element as its argument)
Solution:-
Here’s an example solution:
function Traverse(p_element,p_callback) {
p_callback(p_element);
var list = p_element.children;
for (var i = 0; i < list.length; i++) {
Traverse(list[i],p_callback); // recursive call
}
}
Q52).How to open URL in new tab in JavaScript?
Solution:
use javascript, window.open function.
window.open('http://osingh.weebly.com/','_blank');
Q53).How to get current date in JavaScript?
var today = new Date();
console.log(today);
Q54).How do I declare a namespace in JavaScript?
var myNamespace = {
function1: function() { },
function2: function() { }
function3: function() { }
};
myNamespace.function3();
Q55).What is the best way to detect a mobile device in jQuery?
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
}
Q56).How to detect mobiles including ipad using navigator.useragent in javascript ?
if(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone/i)){
console.log('Calling from Mobile');
}else{
console.log('Calling from Web');
}
Q57).How to detect mobiles including ipad using navigator.useragent in javascript?
if(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone/i)){
console.log('Calling from Mobile');
}else{
console.log('Calling from Web');
}
Q58).How to check an variable is Object OR String OR array?
Use below function to get Data type of javascript variable.
function checkDataType(someVar){
result ='String';
if(someVar instanceof Object){
result ='Object'
}
if($.isArray(someVar)){
result = 'Array';
}
return result;
}
var someVar= new Array("Saab", "Volvo", "BMW");
console.log(result);
Q59).How to modify the URL without reloading the page?
window.history.pushState('page2', 'This is page Title', '/newpage.php');
Q60).How to convert Object to String?
var myobject=['Web','Technology','Experts','Notes']
JSON.stringify(myobject);
Q61).How to convert JSON String to Object?
var jsonData = '{"name":"web technology","year":2015}';
var myobject = JSON.parse(jsonData);
console.log(myobject);
Q62).How to set a default parameter value for a JavaScript function?
/** Here email is parameter in which we have set the default value i.e [email protected] **/
function function1(name, email)
{
email = typeof email !== 'undefined' ? email : '[email protected]';
console.log('name='+name+', Email= '+email);
}
function1('john','[email protected]');
function1('john');
Done>>>>><<<<<........!!!