Javascript Interview Questions and Answers

Question: How to call a function after page load?

window.onload = function() {
    consol.log('Page loaded successfully');
};



Question: How to detect a mobile device in JavaScript?
var isMobile = false; 
if( /Android|webOS|iPhone|iPod|iPad|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    isMobile=true;
}

if(isMobile){
    /** Write here code **/

    /** Write here code **/
}



Question: How to get all elements in having same class in JavaScript?
var element = document.getElementsByClassName("className");
for (index = element.length - 1; index >= 0; index--) {
    /** 
    Write your code here
    **/
}



Question: How to add a class to a given element?
var element = document.getElementById("myDivId");
d.className += " anotherClass";  //It will add anotherClass to the #myDivId



Question: How to update a class to a given element?
var element = document.getElementById("myDivId");
d.className = " anotherClass";  //anotherClass will added



Question: How to DELETE a class to a given element?
var element = document.getElementById("myDivId");
d.className = '';  //All exist class will be removed



Question: How to get element object by tag name?
var element = document.getElementsByTagName("h2");



Question: How do I remove a property from a JavaScript object?
var myJSONObject = {"Key1": "value1", "Key2": "value2", "Key3": "value3"};
delete myJSONObject.two;
console.log(myJSONObject); /* Object { Key1="value1",  Key2="value2",  Key3="value3"}*/



Question: How do I add a property from a JavaScript object?
var myJSONObject = {"Key1": "value1", "Key2": "value2", "Key3": "value3"};
myJSONObject.Key4='value4';
console.log(myJSONObject); /* Object { Key1="value1",  Key2="value2",  Key3="value3",  Key4="value4" }*/



Question: How do I update a property from a JavaScript object?
var myJSONObject = {"Key1": "value1", "Key2": "value2", "Key3": "value3", "Key4": "value4"};
myJSONObject.Key4='444444444444';
console.log(myJSONObject); /* Object { Key1="value1",  Key2="value2",  Key3="value3",  Key4="444444444444"}*/



Question: How do I count the size of object?
var myJSONObject = {"Key1": "value1", "Key2": "value2", "Key3": "value3"};
Object.keys(myJSONObject).length; //3

JavaScript Interview Questions and Answers for Experienced 2016


Question: How to Get class name using jQuery?
className = $('#IdWhichClassNameWantToGet').attr('class');



Question: How to check a div having class name or Not?
className = $('#IdWhichClassNameWantToCheck').hasClass('hasClass');



Question: How to add a focus on inputbox?
className = $('input#inputBoxId').focus();



Question: How to add X number of days in date?
var dateObject = new Date();
dateObject.setDate(dateObject.getDate()+5); //Add 5 Days



Question: How to add X number of minutes in date?
var dateObject = new Date();
dateObject.setDate(dateObject.getTime()+(30 * 60 * 1000)); //Add 30 Minutes



Question: How to delete an element from Associate Array?
var myArray = new Object();
myArray["firstname"] = "Arun";
myArray["lastname"] = "Kumar";
myArray["age"] = "26";
console.log(myArray); /* Object { firstname="Arun",  lastname="Kumar",  age="26"} */
delete myArray["age"];//Delete an Element
console.log(myArray); /*  Object { firstname="Arun",  lastname="Kumar"} */
Question: How to exit from for loop from JS?
Use return true to exit from loop. For Example:
for (i = 0; i < 5; i++) { 
    if(i>2){
        break;
    }    
}



Question: How to load a noimage.gif, If there we are unable to load images?
Use return true to exit from loop. For Example:
&lt;img onerror="this.onerror=null;this.src='/images/noimage.gif';" src="/images/actualimage.jpg" /&gt;



Question: How to change the image source with jQuery?
Use return true to exit from loop. For Example:
$("#imageElement").attr("src","/folder/image.jpg");



Question: How to get image Height & Width?
var img = document.getElementById('imageId'); 
var width = img.clientWidth; //this is image width
var height = img.clientHeight; //this is image height



Question: How to Format a number with exactly two decimals in JavaScript?
Use return true to exit from loop. For Example:
var num = 6.42003;
alert(num.toFixed(2)); // "6.42"



Question: How to prevent buttons from submitting forms?
Use return true to exit from loop. For Example:
&lt;form method="post" onsubmit="return saveDatainDb()"&gt;
First name:  &lt;input name="firstname" type="text" /&gt;&lt;br /&gt;
Last name:&lt;br /&gt;
&lt;input name="lastname" type="text" /&gt;

&lt;input name="submit" type="submit" value="Save Data" /&gt;

&lt;/form&gt;
&lt;script&gt;
function saveDatainDb(){
    /** Validate , if not valid return false**/
    validation_false=true;
    If(validation_false){
        return false;
    }
    /** Validate , if not valid return false**/


    /** Write here code for AJax call**/
 
    /** Write here code for AJax call**/


}
&lt;/script&gt;

JavaScript encodeURIComponent function - Encode and Decode


Question: What is encodeURI?
It encodes only symbols that is not allowed in a URL.


Question: What is encodeURIComponent?
It encodes Whole URL. Its mainly use when you want to send the URL in a parameter.


Question: What is use of escape?
It is deprecated and recommended not to use.


Question: How to use URL encode in Javascript using encodeURIComponent?
var encodedURL = encodeURIComponent('http://www.onlinevideoswatch.com/tools/javascript-urlencode-online');
console.log(encodedURL);//http%3A%2F%2Fwww.onlinevideoswatch.com%2Ftools%2Fjavascript-urlencode-online



Question: From where we can URL encode in Javascript online?
http://www.onlinevideoswatch.com/tools/javascript-urlencode-online


Question: How to use URL decodeed in Javascript using decodeURIComponent?
var decodedURL = decodeURIComponent('http%3A%2F%2Fwww.onlinevideoswatch.com%2Ftools%2Fjavascript-urlencode-online');
console.log(encodedURL);//http://www.onlinevideoswatch.com/tools/javascript-urlencode-online



Question: From where we can URL decode in Javascript online?
http://www.onlinevideoswatch.com/tools/javascript-urldecode-online


Question: What is the difference between a URI, a URL and a URN?
Just See Examples
Suppose we have this link: http://www.onlinevideoswatch.com/tools/javascript-urldecode-online#name=encodeing
URI - Uniform Resource Identifer
http://www.onlinevideoswatch.com/tools/javascript-urldecode-online#name=encodeing%20Data

URL-Uniform Resource Locator
http://www.onlinevideoswatch.com/tools/javascript-urldecode-online

URN - Uniform Resource Name
onlinevideoswatch.com/tools/javascript-urldecode-online#name=encodeing%20Data

Javascript Questions And Answers for Fresher and Experienced


Question: How to pass multiple parameter in setTimeout function?
function myFunctionName(var1,var2){
    console.log('called after 2 sec of page load '+var1+' '+var2);
}
setTimeout(myFunctionName,2000,'value1','value2');



Question: How to enumerate the properties of js objects?
var myObject = {name1: 'Value1',name2: 'Value2'};
//console.log(myObject); //It will print all the values

for (var name in myObject) {
  //console.log(name+'=>'+myObject[name]);
  }



Question: How to measure the execution time of javascript script?
var startTime = new Date().getTime();
/*
Write here you script
*/
for(i=1;i<=500000; i++){
}
var endTime = new Date().getTime();

var time = endTime - startTime;
console.log('Execution time in Milli Seconds: ' + time);
console.log('Execution time in Seconds: ' + time/1000);



Question: How to listen (Do some changes) the window.location.hash change?
$(window).on('hashchange', function() {  
  callNewFunction(window.location.href)  
});
function callNewFunction(url){
    console.log('Hash URL is called');
}

After appling above code, whenever you add/update the hash value, callNewFunction will called automatically.

hashchange event is HTML5 feature and supported by all modern browsers and support is added in following browser.
  1. Internet Explorer 8
  2. Firefox 3.6
  3. Chrome 5
  4. Safari 5
  5. Opera 10.6



Question: How to add class in an element?
HTML Part
&lt;div id="myDivId"&gt;
&lt;/div&gt;

javaScript Part
var d = document.getElementById("myDivId");
d.className += " newClass";



Question: How to get the list of classes for an element?
d = document.getElementById("myDivId");
console.log(d.className);



Question: Can we compare two javaScript objects?
Yes, We can compare two javascript objects. See Following examples.
var myObject1 = {name1: 'Value1',name2: 'Value2'};
var myObject2 = {name1: 'Value111',name2: 'Value222'};
if(JSON.stringify(myObject1) === JSON.stringify(myObject2)){
 console.log("Both object are same");
}else{
console.log("Both object are different");
} 



Question: What is difference between Array(3) and Array('3') in javascript?
new Array(3), means declare the 3 elements and each have value "undefined". new Array('3'), means declare the 1 element and have value 3.
console.log(new Array(3)); // [undefined, undefined, undefined]
console.log(new Array('3')); // ["3"]



Question: How to get browser URL for all browser?
console.log(window.location.href);



Question: How to remove an element(string OR object ) from javascript Array/Object?
var myObject = {name1: 'Value1',name2: 'Value2'};
delete myObject['name1']
console.log(myObject);



Question: What does jQuery.fn mean?
jQuery.fn is just an prototype for defining the new functions.
fn is an alias to the prototype property.
For Example,
$.fn.newFunctionName = function(val){
console.log('something '+val); //something Test Value
};
$.fn.newFunctionName('Test Value');



Question: How to remove an empty elements from an Array?
var simpleArray = [1,3,,3,null,,0,,undefined,4,,6,,];
var cleanArray = simpleArray.filter(function(n){ return n != undefined }); 
console.log(cleanArray);



Question: How to add 5 days in JavaScript?
var result = new Date();
result.setDate(result.getDate() + 5);
console.log(result);

Javascript Interview Questions And Answers for 4 year experienced


Question: How to remove an item from javaScript Array?
var myArray = new Array('a', 'b', 'c', 'd');
var index = myArray.indexOf('b');
myArray.splice(myArray, 1);
console.log(myArray);



Question: How to call a function after 2 section?
function myFunctionName(){
    //console.log('called after 2 sec of page load');
}
setTimeout(myFunctionName,2000);



Question: How to start/stop setInterval function?
function myFunctionName(){
    //console.log('called after 2 sec of page load');
}
var refreshIntervalObject =setInterval(myFunctionName, 3000);
clearInterval(refreshIntervalObject);



Question: What is basic difference between $(document).ready() and window.onload?
$(document).ready(): This event occurs after the HTML document has been loaded.
window.onload This event when all content (e.g. html, js, images) also has been loaded.


Question: Is JavaScript a pass-by-reference OR pass-by-value?
passed by reference


Question: How to send cross domain Ajax Request?
You can send ajax request with "JSONP" only in Cross Domain.
$.ajax({
    url: '/ajax',
    dataType: 'jsonp',
    success:function(data, textStatus, request){
      console.log(request.getResponseHeader('some_header'));
    
    }
});   



Question: What is CDATA? When it is required?
CDATA stand for "Character Data" and it means that the data in between tags.
CDATA is required when you need an document to parse as XML.


Question: How to compare two Dates in javaScript?
var date1 = new Date();
var date2 = new Date(d1);
if(d1.getTime() === d2.getTime()){
    /* Both Time are are Same **/
}else{
    /* Time are are Different**/
}



Question: How to merge two array?
var array1 = ["One","Two"];
var array2 = ["Three", "Four"];
var mergeArray = array1.concat(array2);
console.log(mergeArray);



Question: How to use Regular Expression in JavaScript?
var searchString= '12 34';
var result=searchString.match( /\d+/g ) 
console.log(result ); //["12", "34"]
console.log(result.length+' Elements matched'); //2 Elements matched



Question: How to trigger ENTER key was pressed?
var code = e.keyCode || e.which; if(code == 13) { /** Enter key is pressed **/ }


Question: How to select element by Name?
var arrChkBox = document.getElementsByName("elementName");
Question: How to Convert character to ASCII code in JavaScript?
var characterString='$';
characterString.charCodeAt(0);//36



Question: What do you mean by "javascript:void(0)"?
javascript:void(0) means "DO Nothing";
for example:
&lt;a href="javascript:void(0)"&gt;No effect on clicking&lt;/a&gt;



Question: Can we detect, if javaScript is enabled?
Yes, we can do with html tag.
&lt;noscript&gt;
    javascript is not enabled, Please enable javascript in your browser.
&lt;/noscript&gt;



Question: How to add element in the begining OR at the end of array?
var myArray = new Array('a', 'b', 'c', 'd');
myArray.push('end');
myArray.unshift('start');
console.log(myArray);

Javascript Interview Questions And Answers for 3 year experienced


Question: How to open a URL in a new tab using javaScript?
JavaScript
function OpenInNewTab() {  
  var url='http://www.onlinevideoswatch.com/';
  var win = window.open(url, '_blank');
  win.focus();
}

Html
&lt;div onclick="OpenInNewTab();"&gt;
Click to Open in Tab&lt;/div&gt;



Question: How to Convert JavaScript String to be all lower case?
var strVal="How are yOu";
strVal.toLowerCase(); //how are you



Question: How to detect a mobile device in javaScript?
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 /** You are using Mobile Devices**/
}



Question: How do you check if a variable is an array in JavaScript?
var myArray=new Array('one','two','three','four');
console.log(myArray);
var myval='two';

if (myArray.indexOf(myval)) {
  console.log('value is Array!');
} else {
  console.log('Not an array');
}



Question: How to generate random number between two numbers (1-100)?
var minimum=1
var maximum=100
var randomnumber 

randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
console.log(randomnumber);



Question: How to declare constant in javaScript?
const MY_CONSTANT_NAME = "value that will never change";

Here you can't change the value of "MY_CONSTANT_NAME"
It Will work in all browsers except IE 8, 9 and 10.


Question: How can I format numbers as money format?
var monthlyExpanse=98765.432
monthlyExpanse.toFixed(4);//98765.4320 
monthlyExpanse.toFixed(3);//98765.432 
monthlyExpanse.toFixed(2);//98765.43
monthlyExpanse.toFixed(1);//98765.4



Question: How can display JSON data in readble form?
var str = JSON.stringify(obj, null, 2); // space level  2



Question: How to Get selected value from dropdown list ?
HTML
&lt;select id="countryId"&gt;  
  &lt;option value="11"&gt;England&lt;/option&gt;
&lt;option selected="selected" value="22"&gt;India&lt;/option&gt;
  &lt;option value="33"&gt;Japan&lt;/option&gt;
&lt;/select&gt;

JavaScript
var e = document.getElementById("countryId");
var countryId = e.options[e.selectedIndex].value;
//console.log(countryId); //22



Question: How to convert a number to hexadecimal,octal ?
var myNumber= 500;
//console.log(myNumber.toString(16));//1f4
//console.log(myNumber.toString(8));//764



Question: How to convert a hexadecimal,octal number to decimal?
var hexaDecimal='1f4';
var octal='764';
console.log(parseInt(hexaDecimal,16)); //500
console.log(parseInt(octal,8)); //500



Question: How to convert a String to Decimal?
var strVal='100';
number=parseInt(strVal);



Question: What is use of instanceof?
var simpleStr = "This is string"; 
var myString  = new String();
var newStr    = new String("constructor");
var myDate    = new Date();
var myObj     = {};

simpleStr instanceof String; // returns false, checks the prototype chain, finds undefined
myString  instanceof String; // returns true
newStr    instanceof String; // returns true
myString  instanceof Object; // returns true



Question: How to Scroll to the top of the page?
var xCoord=200;
var yCoord=500;
window.scrollTo(xCoord, yCoord);



Question: How to display javaScript Object?
console.log(obj);



Question: How to use namespaces in javaScript?
var myNamespaceName = {

    foo: function() {
        alert('foo');
    },

    foo2: function() {
        alert('foo2');
    }
};

myNamespaceName.foo();//alert foo
myNamespaceName.foo2();//alert foo2


How to bookmarks a web page with JavaScript


Follow Simple 3 Steps.
  1. Add Following code where you want to show the Bookmark Button.
    &lt;a href="https://www.blogger.com/blogger.g?blogID=5911253879674558037#" id="bookmarkmarkme" rel="sidebar" title="Click to Bookmark this Page"&gt;Bookmark Me&lt;/a&gt;
  2. Include jQuery File
    &lt;script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"&gt;&lt;/script&gt;
  3. Add Following JavaScript code at end of page.
                            $(document).ready(function() {
                              $("#bookmarkmarkme").click(function() {
                                /* Mozilla Firefox Bookmark */
                                if ('sidebar' in window && 'addPanel' in window.sidebar) { 
                                    window.sidebar.addPanel(location.href,document.title,"");
                                } else if( /*@cc_on!@*/false) { // IE Favorite
                                    window.external.AddFavorite(location.href,document.title); 
                                } else { // webkit - safari/chrome
                                    alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
                                }
                            });
                          });
                                        


Object Oriented JavaScript interview questions and answers for experienced



Question: Is JavaScript case sensitive?
Yes, JavaScript is a case sensitive..


Question:What are different Data-Types of JavaScript?
Following are different data-type in JavaScript.
  1. String
  2. Number
  3. Boolean
  4. Function
  5. Object
  6. Null
  7. Undefined



Question: What is an Object?
The object is a collection of properties & each property associated with the name-value pairs.
The object can contain any data types (numbers, string, arrays, object etc.).


Question: What are different two ways of creating an object?
Object Literals: This is the most common way to create the object with object literal.
For Example:
var emptyObj= {};

Object Constructor: It is way to create object using object constructor and the constructor is used to initialize new object.
For Example:
Var obj = new Object();


Question: What is scope variable in JavaScript?
The scope is set of objects which can be variables and function.
"Scope variable" can be have global scope variable and local scope variable.



Question: Give an example creating Global variable
Global variable: A variable which can be variable from any where of the page.
Following are different two ways.
First Way Declare the JavaScript variable at the top of JavaScript code and out of function & objects.
var globalVariable1 ='This is global variable 1'

Second WayDeclare a varaible without "var" in Function.
function testfunction(){
    globalVariable2 ='This is global variable 2'
}



Question: Give an example creating Global variable
Local variable: A variable which can be local and can't access globally.
When we declare a local varriable, Its local and can't access globally. It must create using "var" keyword.
function testfunction1(){
    var localVariable ='This is local variable '
}


Question: What is public, private and static variables in JavaScript?
Public Varaible: A variable which associate to object and is publicily available with object.
For Example:
function funcName1 (name) {
 this.publicVar='1'; 
}

Private Variable: A variable which associate to object and is limited available.
For Example:
function funcName2 (name) {
 var privateVar='1'; 
}

Static variable: A static member is shared by all instances of the class as well as the class itself and only stored in one place.
For Example:
function funcName3 (name) {
 
}
// Static property
funcName3.name = "Web Technology Experts Notes";



Question: How to achieve inheritance in JavaScript
"Pseudo classical inheritance" and "Prototype inheritance"


Question: What is closure in JavaScript?
When we create the JavaScript function within another function and the inner function freely access all the variable of outer function.


Question: What is prototype in JavaScript?
All the JavaScript objects has an object and its property called prototype & it is used to add and the custom functions and property. See Following example in which we create a property and function.
var empInstance = new employee();
empInstance.deportment = "Information Technology";
empInstance.listemployee = function(){

}


What are differences between $(document).ready and $(window).load?



$(document).ready();
$(document).ready(function() {
 /** Add your code here **/
            


/** Add your code here **/

 console.log("HTML Document is fully load. HTML, javaScript and CSS is fully loaded.");
});

JavaScript code written inside $(document).ready will be called when HTML Document is fully loaded. It means JavaScript code will be called just after HTML, JavaScript & CSS is fully loaded.



$(window).load();
$(window).load(function() { 
 /** Add your code here **/
            


/** Add your code here **/


 console.log("Web page fully Loaded. HTML, Javascript, CSS, Images, Iframes and objects are fully loaded.");
});


JavaScript code written inside $(window).load will be called when Web page fully Loaded. It means JavaScript code will be called just after HTML, Javascript, CSS, Images, Iframes and objects are fully loaded.

Following document ready have same meaning and work as same.
$(document).ready(function(){

});
OR
$(function(){

});
OR
$(document).on('ready', function(){
})

Javascript Interview Questions and Answers for Experienced 2




Question: 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@domain.com **/
function function1(name, email)
 {
   email = typeof email !== 'undefined' ? email : 'defaultemail@domain.com';
    console.log('name='+name+', Email= '+email);
 }

function1('john','myname@gmail.com');
function1('john');



Queston: How to convert a string to lowercase?
var str='This is testing String';
str = str.toLowerCase();
console.log(str);



Question: How to modify the URL of page without reloading the page?
use pushState javascript function.
For Example:
window.history.pushState('page2', 'This is page Title', '/newpage.php');


Question: How to convert JSON Object to String?
var myobject=['Web','Technology','Experts','Notes']
JSON.stringify(myobject);


Question: How to convert JSON String to Object?
var jsonData = '{"name":"web technology","year":2015}';
var myobject = JSON.parse(jsonData);
console.log(myobject);


Question: 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);



Question: Can i declare a variable as CONSTANT like in PHP?
No, I think cosntant not exist in javascript.
But you can follow same type convention to declare constant.
var CONSTANT_NAME = "constant value";


Question: How to open URL in new tab in javascript?
use javascript, window.open function.
window.open('http://www.web-technology-experts-notes.in/','_blank');


Question: What is difference between undefined and object?
undefined means some variable's value is not defined yet.
object means variables's value is defined that is either function, object OR array.

With use of below, you can easily determine whether it is object OR NULL.
console.log(typeof(null));      // object
console.log(typeof(undefined)); // undefined


Question: How to get current date in JavaScript?
var today = new Date();
console.log(today);



Question: How do I declare a namespace in JavaScript?
var myNamespace = {

    function1: function() {   },

    function2: function() {    }

    function3: function() {    }
};

myNamespace.function3();


Question: 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) ) {

}



Question: 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');      
}



Question: 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');      
}



Javascript Interview Questions and Answers for Experienced



Question: What is JavaScript closures? Give an Example?
A closure is an inner function that has access to the outer function's variables known as Closure.
 function function1(x) {
  var tmp = 3;
  function function2(y) {
    console.log(x + y + (++tmp)); // will console 7
  }
  function2(1);
}

function1(2);


Question: What is the function of the var keyword in Javascript?
var is used to create the local variables.
If you're in a function then var will create a local variable.
 var x =10;
function function1(){
var x=20;
}
function1();
alert(x); //10 

var x = 10 declares variable x in current scope.
If the declaration appears in a function It is a local variable.
if it's in global scope - a global variable is declared.
 
x =10;
function function1(){
x=20;
}
function1();
alert(x); //20
x=10 declare a global variable.


Question: How can I make a redirect page using jQuery?
 window.location.href = "http://www.web-technology-experts-notes.in/p/sitemap.html";


Question: How can I check if one string contains another substring?
you can use indexOf function,
If string found - It will returns the position of the string in the full string.
If string not found- it will return -1
See Example
 
var haystack = "full-string-here";
var needle = 'string';
if(haystack.indexOf(needle)>=0){
    console.log('String found');
}else{
console.log('String Not found');
}


Question: What is difference between == and === in javascript?
Both are used to check the equality only difference === check with both data type.
For Example
 2=='2' // will return true;
2==='2'// will return false;


Question: Can I comment a JSON file?
No, but you can add a node on root where you can display the information.


Question: How to Check checkbox checked property?
 var checkboxStatus = $('#checkMeOut').prop('checked'); 
if(checkboxStatus){
    console.log('Checkbox is Checked');
}else{
    console.log('Checkbox is Not Checked');
}


Question: How to include a JavaScript file in another JavaScript file?
With use of jQuery, its quite simple, See below:
 $.getScript("my_lovely_script.js", function(){   

});


Question: How to remove single property from a JavaScript object?
var myobject=['Web','Technology','Experts','Notes']
delete myobject['Technology'];


Question: How to add single property from a JavaScript array?
var myobject=['Web','Technology','Experts','Notes']
 myobject.push(' Web Development');


Question: How to empty an array?
var myobject=['Web','Technology','Experts','Notes']
 myobject.length = 0


Question: How to trim string in JavaScript?
You can do in very simple way using jQuery.
See Below:
$.trim('  Web Technology   ');


Question: How do you get a timestamp in JavaScript?
new Date().getTime()


Question: How to use javaScript Loop?
var myobject=['Web','Technology','Experts','Notes']
for (index = 0; index < myobject.length; ++index) {
    console.log(myobject[index]);
}


Question: How to detect an undefined object property in JavaScript?
if (typeof myobject === "undefined") {
    console.log("myobject is undefined");
}


Question: How to validate email address in JavaScript?
function validateEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
}
validateEmail('contactuse@web-technology-experts-notes.in'); // Will return true;


Question: How to capitalize the first letter of string?
function capitalizeFirstLetterOfString(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
capitalizeFirstLetterOfString('web-technology-experts-notes'); //Web-technology-experts-notes


Question: How to get current url in web browser?
window.location.href


Question: How can I refresh a page with jQuery?
window.location.reload();


How do I copy to the clipboard in JavaScript?


Step 1: Add Following javascript function in Web page.
    function selectAllData(id) {
    var obj = document.getElementById(id);
        var text_val=eval(obj);
        text_val.focus();
        text_val.select();
        if (!document.all) return; // if IE return;
        r = text_val.createTextRange();
        r.execCommand('copy');
    }

Step 2: call selectAllData('id') function with passing the id of the container. See Example
&lt;input onclick="return selectAllData('textareaId')" type="button" value="Select All" /&gt;


Following are consolidate Code:
&lt;script type="text/javascript"&gt; function selectAllData(id) { var obj = document.getElementById(id); var text_val=eval(obj); text_val.focus(); text_val.select(); if (!document.all) return; // if IE return; r = text_val.createTextRange(); r.execCommand('copy'); }&lt;/script&gt; &lt;textarea cols="30" id="textareaId" row="50"&gt; javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers &lt;/textarea&gt; &lt;input onclick="return selectAllData('textareaId')" type="button" value="Select All" /&gt;


See demo:







Difference between encodeuri and encodeuricomponent in javascript?


encodeURI: This javascript function is used to encode a URI (Uniform Resource Identifier). This function encode special characters except the following:
, / ? : @ & = + $ #

We used encodeURI when we want to encode the url parameter.
For Example:
var url=encodeURI('http://www.example.com/mysite.php?name=web technology experts notes&char=*');
console.log(url);
//output will be following
//http://www.example.com/mysite.php?name=web%20technology%20experts%20notes&char=*

decodeURI(): It is used to decode a URL which was encoded with encodeURI.




encodeURIComponent: This javascript function is used to encode a URI component. This function encodes all special characters Except the following:
~!*()'

We used encodeURIComponent when we want to encode the both (URI parameter & URI components). For Example:
var url=encodeURIComponent('http://www.example.com/mysite.php?name=web technology experts notes&char=*');
console.log(url);
//output will be following
//http%3A%2F%2Fwww.example.com%2Fmysite.php%3Fname%3Dweb%20technology%20experts%20notes%26char%3D*
decodeURIComponent() It is used to decode a URL which was encoded with encodeURIComponent.

What is the Correct content-type of JSON and JSONP?



Question: What is the Correct content-type of JSON?
  • application/json
  • application/javascript
  • application/x-javascript
  • text/javascript
  • text/x-javascript
  • text/x-json

Answer:
application/json

JSON is a domain-specific language (DSL) and a data format is independent of JavaScript it have its own MIME type i.e. application/json.

Example of JSON:
{ "Name": "Web Technology", "Website": "http://www.web-technology-experts-notes.in" }

Content-Type: application/json




Question: What is the Correct  content-type of JSONP?
  • application/json
  • application/x-javascript
  • application/javascript
  • text/javascript
  • text/x-javascript
  • text/x-json
Answer:
application/javascript

JSONP is JSON with padding. Response is JSON data but with a function call wrapped around it.

Example of JSONP:
functioncallExample({ "Name": "Web Technology", "Website": "http://www.web-technology-experts-notes.in" });

Content-Type: application/javascript

How to Call a javaScript function in PHP



You can't call a javascript function in PHP directly.

But You can Call a Javascript function from outputted HTML by PHP. It means you can call the javaScript function on conditional. See Example Below:
 
$count= empty($_GET['count'])?0:$_GET['count'];
if(empty($count)){
    echo '';
}elseif($count&amp;lt;=10){
echo '';
}else{
echo '';
}

In this way, we call the JavasScript function in PHP.



Front End Developer Interview Questions and Answers


Question: What is the importance of the HTML DOCTYPE?
DOCTYPE is an instruction to the web browser about what version of the markup language the page is written. Its written before the HTML Tag. Doctype declaration refers to a Document Type Definition (DTD).


Question: Explain the difference between visibility:hidden; and display:none?
Visibility:Hidden; - It is not visible but takes up it's original space.
Display:None; - It is hidden and takes no space.


Question: How do you clear a floated element?
clear:both


Question: What is the difference between == and === ?
== is equal to
=== is exactly equal to (value and type)



Question: What is a java script object?
A collection of data containing both properties and methods. Each element in a document is an object. Using the DOM you can get at each of these elements/objects.



Question: Describe what "this" is in JavaScript?
this refers to the object which 'owns' the method.



Question: What is a closure?
Closures are expressions, usually functions, which can work with variables set within a certain context.

Question: How to use a function a Class?
function functionName(name) {  
    this.name = name;
}
// Creating an object
var functionName = new functionName("WTEN");  
console.log(functionName.name);  //WTEN



Question: What is Difference between null and undefined?
null is an object with no value. undefined is a type.
typeof null; // "object"  
typeof undefined; // "undefined"  



Question: What is the difference between HTML and XHTML?
HTML is HyperText Markup Language used to develop the website.
XHTML is modern version of HTML 4. XHTML is an HTML that follows the XML rules which should be well-formed.

Javascript Interview Questions and Answers


JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. You can change the DOM element and call the Ajax. It is independent of operating and language.


Question: How many types of loop are there in javaScript?

Answer: JavaScript supports following different types of loops
for - loops through a block of code a number of times
for/in - loops through the properties of an object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
/** for loop example **/
cars=["BMW","Volvo","Merchi","Ford"];
var i=2,len=cars.length;
for (; i");
}
/** for loop example **/

/** For/In Loop **/
var person={fname:"John",lname:"Doe",age:25}; 

for (x in person)
  {
alert(person[x]);
  }
/** For/In Loop **/

/** while loop **/
while (i<5 data-blogger-escaped-br="" data-blogger-escaped-he="" data-blogger-escaped-i="" data-blogger-escaped-is="" data-blogger-escaped-number="" data-blogger-escaped-x="x">";
  i++;
  }
/** while loop **/ 


Question:What are global variables? How are they declared? How these are different from local variables?
Answer: Variable that are available throughout the page.
These are declared without use of var keyword.

Variable that are declared with use of keyword var are local variable and available within scope.
// Declare a local variable
var localVariable = "PHP Tutorial"
// Declare a global
globalVariable = "google"
 


Question:What is the difference between undefined and null?
Answer: The value of a variable with no value is undefined (i.e., it has not been initialized). Variables can be emptied by setting their value to null. You can use === operator to test this.


Question: What are the various datatypes in javascript?
Answer: Number - Store Number like 1,100, 33
String - Store string like "php","tutorial-" etc
Boolean - Store true OR false
Function - Store the function
Object - Store the object like person object
Null - Store the variable value null
Undefined - Not defined variable value are undefined.


Question: What is negative infinity?
Answer: It’s a number in JavaScript, derived by dividing negative number by zero. For example var a=-100/0;

Question: How to check the type of variable?
Answertypeof is used to check the variable type. For example alert(typeof abc);

Question: How do you convert numbers between different bases in JavaScript?
Answer: Use the parseInt() function.
alert( parseInt ("3F", 16));


Question: What is Javascript namespacing? How and where is it used?
Answer: Using global variables in Javascript is evil and a bad practice. That being said, namespacing is used to bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that you’ve attached all further methods, properties and objects.

Question: How to load javascript files asynchronously?
Question: How to load javascript files fast?
 Answer: If you have latest browser which support HTML5 then you just need to add "async" tag with value true
If you have old browser, you need to create a js function that will add javascript async Following are the Javascript function example
function loadScriptAsync (scriptFilePath){
    var scriptHeadTag=document.getElementsByTagName('script')[0];
    var ss=document.createElement('script');
    ss.type='text/javascript';
    ss.async=true;
    ss.src= scriptFilePath
    scriptHeadTag.parentNode.insertBefore(ss,s);
}

loadScriptAsync('/js/jsfile.js'); 
Pass PHP Array into Ajax Call
//Setp 1: Include jQuery file in your page

$phpData = array('fname'=>'G', 'lname'=>'Geo','email'=>[email protected]'); //Setp 2: This is your PHP Array data

 [script]
/** Setp 3: This is Ajax Call will be called after page fully load **/
     function saveuserdetail(mydata) {                                    
                    $.ajax({
                        type: "POST",//Here you can use POST/GET Method
                        url: '/postpageurl/',
                        data: mydata,
                        success: function(msg){                            
                            console.log('Data'+msg);
                        },
                        dataType: 'json'
                    });                
            }
/** This is Ajax Call will be called after page fully load **/


/* Step 4: When Page Load, PHP Array will convert into javaScript Object */
/* Pass the javaScript Object into javaScript Function i.e saveuserdetail**/
$( document ).ready(function() {
    var data=new Object("echo json_encode($phpData) ")
    saveuserdetail(data);
});
[/script]

Question: Is JavaScript case sensitive?
Answer: Yes!
getElementById is different from getElementbyID.
Question: How will you get the Checkbox status whether it is checked or not?
Answer:
alert(document.getElementById('checkbox1').checked);
Question: How do you submit a form using JavaScript?
Answer:
document.forms[0].submit();
Question: What does isNaN function do?
Answer: isNaN : IsNotaNumber
returns true if the argument is not a number;
Question: What does "1"+9+4 evaluate to?
Answer: 194
How do you assign object properties?
obj["age"] = 22 or obj.age = 22.



What’s a way to append a value to an array?
arr[arr.length] = value;


How to read and write a file using javascript?
 I/O operations like reading or writing a file is not possible with client-side javascript.



How do you convert numbers between different bases in JavaScript?
Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal FF to decimal, use parseInt ("FF", 16);



What is negative infinity? 
It’s a number in JavaScript, derived by dividing negative number by zero.



How to set a HTML document's background color?
 document.bgcolor property can be set to any appropriate color.



What boolean operators does JavaScript support?
&&, and !



How to get the contents of an input box using Javascript?
 Use the "value" property.var myValue = window.document.getElementById("textboxID").value;



How to determine the state of a checkbox using Javascript? 
var checkedP = window.document.getElementById("CheckBoxID").checked;



How to set the focus in an element using Javascript? 
<script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>



How to access an external javascript file that is stored externally and not embedded? 
This can be achieved by using the following tag between head tags or between body tags.<script src="raj.js"></script>How to access an external javascript file that is stored externally and not embedded? where abc.js is the external javscript file to be accessed.



What is the difference between an alert box and a confirmation box? 
An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.



What is a prompt box? 
A prompt box allows the user to enter input by providing a text box.



Can javascript code be broken in different lines?
Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.that is ,document.write("Hello \ world");is possible but not document.write \("hello world");



What looping structures are there in JavaScript?
for, while, do-while loops, but no foreach.



How do you create a new object in JavaScript?
var obj = new Object(); or var obj = {};



What is this keyword?
It refers to the current object.


What is the difference between SessionState and ViewState? 
ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.

What looping structures are there in JavaScript? 
for, while, do-while loops, but no foreach.



To put a "close window" link on a page ? 
<a href='javascript:window.close()'> Close </a>



How to comment javascript code? 
Use // for line comments and/**/ for block comments



Name the numeric constants representing max,min values 
Number.MAX_VALUENumber.MIN_VALUE



What does javascript null mean? The null value is a unique value representing no value or no object.It implies no object,or null string,no valid boolean value,no number and no array object.



How do you create a new object in JavaScript? 
var obj = new Object(); or var obj = {};



How do you assign object properties? 
obj["age"] = 23 or obj.age = 23.



What’s a way to append a value to an array? 
arr[arr.length] = value;


What does undefined value mean in javascript? 
Undefined value means the variable used in the code doesn't exist or is not assigned any value or the property doesn't exist.



What is the difference between undefined value and null value? 
(i)Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null(ii)typeof undefined variable or property returns undefined whereas typeof null value returns object



What is variable typing in javascript? It is perfectly legal to assign a number to a variable and then assign a string to the same variable as followsexamplei = 10;i = "string";This is called variable typing



Does javascript have the concept level scope? No. JavaScript does not have block level scope, all the variables declared inside a function possess the same level of scope unlike c,c++,java.

What is === operator ? ==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.

How to disable an HTML object ?
document.getElementById("myObject").disabled = true;



How to create a popup warning box?
alert('Warning: Please enter an integer between 0 and 1000.');



How to create a confirmation box? 
confirm("Do you really want to launch the missile?");



How to create an input box? 
prompt("What is your temperature?");


What's Math Constants and Functions using JavaScript? 
The Math object contains useful constants such as Math.PI, Math.EMath.abs(value); //absolute valueMath.max(value1, value2); //find the largestMath.random() //generate a decimal number between 0 and 1Math.floor(Math.random()*101) //generate a decimal number between 0 and 100



What does the delete operator do? 
The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword.



How to get value from a textbox?
alert(document.getElementById('txtbox1').value);



How to get value from dropdown (select) control?alert(document.getElementById('dropdown1').value);


What is console.log?
It is feature of Firebug used for debug the javascript OR jQuery code. It can print the string, number, array OR object. It is same as print_r() in php.

Example of console.log
console.log (22 );
console.log ('web technology experts notes' );
console.log (arrayVal);
console.log (objectVal);


Question: How to check checkbox is checked or not in jquery?
$('.checkBoxClass').is(':checked');


Question: How to check the checkbox as checked?
$(".checkBoxClass").attr('checked', true); // Deprecated
$(".checkBoxClass").prop('checked', true);

Comments

  1. Excellent blog admin, thanks for sharing this javascript interview questions with answers. It is really helpful to me. Keep sharing more like this.
    JAVA Training Institutes in Chennai | Best JAVA Training institute in Chennai

    ReplyDelete

Post a Comment

Footer