Showing posts with label Javascript Interview Questions and Answers. Show all posts
Showing posts with label Javascript Interview Questions and Answers. Show all posts

Sunday 29 March 2020

How do I copy to the clipboard in JavaScript?

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
<input onclick="return selectAllData('textareaId')" type="button" value="Select All" />


Following are consolidate Code:

<script type="text/javascript"> 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'); }</script> <textarea cols="30" id="textareaId" row="50"> 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 </textarea> <input onclick="return selectAllData('textareaId')" type="button" value="Select All" />


See demo:






Question: What is the most efficient way to deep clone an object in JavaScript?
const a = {
  string: 'string',
  number: 123,
  bool: false,
  nul: null,
  date: new Date(), 
}
console.log(a);
console.log(typeof a.date);  // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);




Wednesday 14 February 2018

What is Object.assign()? and how to use Object.assign()?

What is Object.assign()? and how to use Object.assign()?

Question: What is Object.assign()?
The Object.assign() is used to copy the values of all properties from one or more source objects to a target object.



Question: What is syntax for Object.assign()?
Object.assign(target, ...sources);



Example 1
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
const object2 = Object.assign(object1,{d:4});
console.log(object2);

Output
Object { a: 1, b: 2, c: 3, d: 4 }



Example 2
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
const object2 = Object.assign(object1,{d:4,e:5, a:11});
console.log(object2);

Output
Object { a: 11, b: 2, c: 3, d: 4, e: 5 }



Example 3
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
const object2 = Object.assign(object1,{d:4,e:5, a:11},{f:5, a:111});
console.log(object2);

Output
Object { a: 111, b: 2, c: 3, d: 4, e: 5, f: 5 }



Example 4
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
const object2 = Object.assign(object1,{d:4,e:5, a:11},{f:5, a:111},null, undefined);
console.log(object2);

Output
Object { a: 111, b: 2, c: 3, d: 4, e: 5, f: 5 }



Example 5
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
const object2 = Object.assign(object1,{d:4,e:5, a:11},{f:5, a:111},null, undefined,{g:6, a:1111});
console.log(object2);



Output
Object { a: 1111, b: 2, c: 3, d: 4, e: 5, f: 5, g: 6 }



Thursday 14 July 2016

Callback, Trigger and Event handler in javaScript

what callback, trigger and event handler in javaScript
Callback is a function that is passed to another function as parameter and callback function is called inside another function.
Example:
$("#MyButton").click(function(){
    $("p#hideDiv").hide("slow", function(){
        alert("function() is callback and called.");
    });
});

Here following are callback function.
function(){
        alert("function() is callback and called.");
    }



The trigger is code that is executed automatically on some events.
Example:
<script>
$(document).ready(function(){
    $("input").select(function(){
        $("input").after(" Text marked!");
    });
    $("button").click(function(){
        $("input").trigger("select");
    });
});
</script>
<input type="text" value="Hello World" />
<button>Click on this button</button>



Handler: An event handler executes a part of a code based on certain events occurring within the application such as onClick, onBlur, onLoad etc.
Example:
$(document).ready(function(){
    $("button").click(function(){
        $("input").trigger("select");
    });
});



Following are few more event handler
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page



Monday 6 June 2016

Core JavaScript Interview Questions

Core JavaScript Interview Questions

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



Question: How can I remove a specific item from an array?
Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

const array = [2, 5, 9];
const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}
// array = [2, 9]
console.log(array); 




Wednesday 25 May 2016

JavaScript Interview Questions and Answers for Experienced 2016

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:
<img onerror="this.onerror=null;this.src=&#39;/images/noimage.gif&#39;;" src="/images/actualimage.jpg" />



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:
<form method="post" onsubmit="return saveDatainDb()">
First name:  <input name="firstname" type="text" /><br />
Last name:<br />
<input name="lastname" type="text" />

<input name="submit" type="submit" value="Save Data" />

</form>
<script>
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**/


}
</script>



Thursday 19 May 2016

JavaScript encodeURIComponent function - Encode and Decode

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





Wednesday 6 April 2016

Javascript Questions And Answers for Fresher and Experienced

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
<div id="myDivId">
</div>

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



Tuesday 5 April 2016

Javascript Interview Questions And Answers for 4 year experienced

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:
<a href="javascript:void(0)">No effect on clicking</a>



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



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




Monday 4 April 2016

Javascript Interview Questions And Answers for 3 year experienced

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
<div onclick="OpenInNewTab();">
Click to Open in Tab</div>



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
<select id="countryId">  
  <option value="11">England</option>
<option selected="selected" value="22">India</option>
  <option value="33">Japan</option>
</select>

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



Thursday 26 November 2015

How to bookmarks a web page with JavaScript


How to bookmarks a web page with JavaScript


Follow Simple 3 Steps.
  1. Add Following code where you want to show the Bookmark Button.
    <a href="https://www.blogger.com/blogger.g?blogID=5911253879674558037#" id="bookmarkmarkme" rel="sidebar" title="Click to Bookmark this Page">Bookmark Me</a>
  2. Include jQuery File
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
  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.');
                                }
                            });
                          });
                                        



Friday 23 October 2015

Object Oriented JavaScript interview questions and answers for experienced

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(){

}



Tuesday 8 September 2015

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


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(){
})



Thursday 2 April 2015

Javascript Interview Questions and Answers for Experienced 2

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






Wednesday 1 April 2015

Javascript Interview Questions and Answers for Experienced

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();