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

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