You are on page 1of 16

Q: How do I debug JavaScript as used on a webpage?

A: There are many approaches that you can take to debugging JavaScript. Let's discuss what you may do in the code itself first: The most common is to insert alerts into the code, where you alert the values and types of variables, function arguments, and object properties. If you are doing code forking to support different ways of doing things, you may useconfirms to force a certain path to be taken. If you want to be able to cut and paste the results, you may want to useprompts. In an effort to get better error reporting you may use window.onerror or the try..catch statement. These may also be used to let code run without halting on errors, letting all errors be reported after the code has been executed. Reduce hard-to-find errors that may sneak into your code by always following coding conventions such as explicitly ending statements by semicolon instead of relying on the semicolon insertion; by always using braces around the bodies of statements of the control structures (if, if..else, switch, while, do..while, for, statements); by using parentheses instead of relying on operator precedence; by using consistent and verbose naming conventions; by using indentation and spacing consistently in a way that makes your source code easily readable; by avoiding automatic type casting through using explicit type casting or other methods to achieve the same effect; by using full syntaces where browsers allow shortcuts (this especially goes for ie), etc. Run the code through js lint, which will do some work towards detecting potential coding errors.

Ok, that was what you could do in the code itself. How about the detection of errors in the code? Use many browsers for testing your scripts while you develop them. On windows, use at least ie6w, op7 and moz. On mac, use at least saf, op7, ie5m and moz. If things doesn't work in one or more of these browsers, see if you can do them differently. If not, make a fork for the chosen browser. In ie, be sure to turn error reporting on. If you're on windows, use the Microsoft Script Debugger. You may use thedebugger keyword inside the script to turn control of the execution of the script over to the debugger, if you need to track an error down. It's recommended that you use ie primarily for testing, and use op7 or moz for debugging. In Op7, be sure to turn on JavaScript error reporting in the JavaScript Console. The Op7 JavaScript Console is far better than the ie bug reporting, and it contains a nice tracing feature that makes it easy to see where functions are called from. It also reports correct line number, in difference to iew. In moz there's a sea of tools. You have the Mozilla JavaScript Console which reports errors and warnings as well as allows you to do simple script evaluation. You can turn on Strict Warnings to be alerted of many more potential problematic situations. You can use the DOM Inspector to view the document tree, the stylesheets tree, the computed styles, and JavaScript objects. You can use Venkman (the Mozilla JavaScript Debugger) to get a really advanced JavaScript debugger tool. You can use Ian Hickson's JavaScript Evaluation Sidebar or one of Jesse Ruderman'sJavaScript Environment, view scripts bookmarklet, JavaScript Shell or view variables bookmarklet; or my ViewScriptsbookmarklet. In konq your are pretty much on your own. Use the source code tricks.

In saf you can turn on the hidden debug menu, to display frighteningly unhelpful error messages in the system Console, as well as get access to a more useful Show DOM Tree feature, if you turn on display of the Debug menu using the following command in the terminal while Safari is not running:

defaults write IncludeDebugMenu 1

Q: How do you read, write, delete and detect support for cookies?

A: Let's take it one step at a time:

Reading cookies is simple. document.cookie is the JavaScript interface to cookies. It contains a semicolon separated list of cookies in the following fashion: "cookiename1=cookievalue1;...;cookienamen=cookievaluen". Only cookies for the current domain and path will be included in the string. Writing cookies is more complicated. The easiest form of cookies are session-only cookies, which only lives as long as the browser window. These are written simply like this:

document.cookie="cookiename=cookievalue"; Longer lived cookies are more advanced. They contain a string of the following pattern:"cookiename=cookievalue;expires=date;path=path;domain=domain;secure" . Only include the path, domain and secureparts if you need to set them to something other than the default (which is '/', document.domain, and absent, respectively). date should be in the form of the return from the toUTCString method of instances of JavaScript's Dateobject. Deleting cookies is done by overwriting a cookie, setting the expiry time in the past. Thus,

document.cookie='cookiename=;'+ 'expires=Thu, 01-Jan-70 00:00:01 GMT;'+ 'path=path;'+ 'domain=domain"; where path and domain MUST be the same as they were when the cookie was originally set. Detecting cookie support is done by writing a cookie and then reading it out again. If the value is the same as what you wrote, the browser supports cookies.

If you don't feel like writing your own cookies handling script, there are many cookies libraries out there that you can use. I personally wrote two different ones in this thread, for instance, and the rest of the CF community has contributed to among other places this thread.

Q: What are the limits on cookies?

A: There's a list of limits put on cookies:

Cookies are limited to one domain. There is a limit of 20 cookies per domain. Cookies can be read only from pages from that domain. Cookies can further be limited by paths, so that only pages with a specific path on that domain may read the cookie. Cookies have an expiry date. If no such date is set, they will only survive as long as the browser session is still running. Cookies that pass the expiry date are removed, but not necessarily from your harddrive. It depends on how your browser stores them. Cookies may be 4kb long each, name of the cookie included. Your max limit is no smaller than 300 cookies in total. Most browsers allow no longer expiry time than three years. Some have a 90 day limit even.

Official specifications exist for this, and can be found at Netscape Cookie Specification, which is the base for the IETF RFC2109 Specification.

Q: What is Javascript good for? A: Because any general web user may have javascript in their browser disabled any use of javascript on a web page is best limited to enhancing the functionality, user friendliness and overall experience on your web pages. Nothing on your page should absolutely depend on javascript unless it's a nonessential part of the page. Javascript can also be used to make a page less friendly but there's no point in doing that. Useful things: Forms Validation, because Javascript can be disabled you must always perform validation on the server side but any validation of user input you can also perform interactively with the user before a form is submitted can save the user a round trip to the server and can save your server a hit where no actual transaction occurs. Interactive Forms, In the case of something like an online store it's always nice to update order totals and (when possible) shipping costs and other incidental costs (handling fees, taxes...) as the user updates the quantities or selects/deselects various items on the page. While you may want to post that toal back to your server for your own security, you must never trust that figure. Recalculate any totals based on the posted selections/quantities, you can however compare the posted total vs the server side computed total to detect bugs in the script and/or attempts at theft. Visual aides, the Title property can and should be used to give a user of your web page additional information about some element or group of elements on your page but javascript can be used to supplement the relatively weak content control available via the title property with a much richer full html content using a tooltip script.

Q: How do I format a number so that it always has two decimals?

A: There are more than one way to do it. You could use the Number.prototype.toFixed method to do it, if it wasn't for the fact that ie5.5w is buggy and saf doesn't support it at all. Instead, do something like this:

Number.prototype.toDecimals=function(n){ n=(isNaN(n))? 2: n; var nT=Math.pow(10,n); function pad(s){ s=s||'.'; return (s.length>n)? s: pad(s+'0'); } return (isNaN(this))? this: (new String( Math.round(this*nT)/nT )).replace(/(\.\d*)?$/,pad); }
This code extends all numbers to contain a toDecimals method, which you can invoke like this:

var nYourNumber=300.3, sYourFormattedNumber=nYourNumber.toDecimals(2); // => '300.30'

Q: How do I trim whitespace from the beginning and end of a string?

A: By using regular expressions matching:


String.prototype.trim=function(){ return this.replace(/^\s*|\s*$/g,''); } String.prototype.ltrim=function(){ return this.replace(/^\s*/g,''); } String.prototype.rtrim=function(){ return this.replace(/\s*$/g,''); } These can then be used like this:

var sOriginal=' text ', sTrim=sOriginal.trim(), sLTrim=sOriginal.ltrim(), sRTrim=sOriginal.rtrim(); /* After execution: sOriginal is ' text ' sTrim is 'text' sLTrim is 'text '

sRTrim is ' */


Q: Why does parseInt('08') generate 0?

A: Because JavaScript integers are automatically radix detected. A number starting with 0 is considered to be octal, a number starting with 0x or 0X is considered to be hexadecimal, all other numbers are considered to be decimal. In octal, the digits range from 0 to 7, and thus the 8 is an illegal digit. How to fix it? That is easy. You can override the JavaScript automatic radix detection by providing a second argument to the parseInt function, having a value of 10 (for decimal numbers). Thus, you do it like this:

var nYourNumber=parseInt('08', 10);

Q: How do I read/write files? A: Pure client-side JavaScript cannot write files to the server because it simply was never intended to and moreover, that's what server-side languages are used for. Perhaps there are security reasons among others for this as well. As for reading files with JavaScript, this is completely possible and done quite easily if you use something like Vlad's scriptor David's script. Q: How do I get multiple scripts to work on a single page? A: The short (not recommend) answer is to rename all of the variable and function names in the second instance of the script thus preventing them from conflicting. The longer (recommend) answer would be to rewrite the script in an object-oriented fashion. The reason you'd do it like this is because this is inherently how object-oriented code is intended to work: with multiple instances. This is true because when you call the constructor for that object, all variables become internal properties of it therefore completely removing the chance of anything conflicting between the two scripts. Also note by making it an object you can have as many instances of it on a page as you'd like it's not only limited to two.
Q: How do I convert a decimal number to hexadecimal, and the other way around?

A: For converting a hexadecimal number to a decimal number, you use the parseInt function with a radix of 16, like this:

var nDecimal=parseInt(sHexadecimal, 16);

where sHexadecimal is a string containing a hexadecimal number. For converting a decimal number to hexadecimal, you use the toString method with an argument of the radix you want to convert to, in this case 16, like this:

var sHexadecimal=nDecimal.toString(16);

where nDecimal is either a variable name, a number literal wrapped in parentheses, or a function giving a number as return value.

Q: How do I add ordinals (st, nd, rd, th) to a number?

A: After quite some optimisation, you could end up with a function looking something like this:

Number.prototype.toOrdinal=function(m){ return (this + ["th","st","nd","rd"][(!( ((m=this%10) >3) || (Math.floor(this%100/10)==1) ))*m]); } and you use it like this:

var nNumber=12, sFirstOrdinal=nNumber.toOrdinal(), // => '12th' sSecondOrdinal=(22).toOrdinal(); // => '22nd' Well, I won't bore you with the development procedure of this very slick and optimised function. You can check it out yourself in this thread.

Q: How do I use JavaScript in external files?

A: This is a question that is seldom answered satisfactory. Well, first of all, you should not include any HTML in your JavaScript file. This means that you should not include things like <script type="text/javascript"><!-- or --></script> in the file. Those belong in the HTML file only. Now, the exact same code should behave exactly the same whether it's included in the document or in a separate file. However, there is one issue you must be aware of with JavaScript files: If the JavaScript is placed in the head of the document, the files will be downloaded as soon as the HTML parser reaches them, and they will be executed as soon as they are finished downloading. This means that you can not rely on them being executed in the order they appear in the head. To get around this, you can make sure no code that should actually execute is present in the JavaScript file, only variable declarations and functions. Then you move the execution of code into the window.onload function where you can rely on all of the JavaScript files being referenced in the head to be loaded. Note that this goes only for scripts included in the head of the document, not scripts in the body of the document.

Q. How can I use Javascript to protect my web pages? A. Short answer, you can't. Long Answer: Since visitors to your web site can disable Javascript in their browser, javascript can't be used as a protection mechanism.

Even without disabling Javascript I can easily see the whole code for your web page by simply running another javascript which will undo anything you did to make the page unavailable. Search for "Bookmarklets" in Google for a bunch of simple but useful scripts like that which can be set up as Bookmarks (Favorites for you IE users). Please note that "No Right Click" scripts (one of the favorite uses of javascript to "protect" a web page) are considered at best a "waste of time" but more often as "user antagonistic" by most of the regulars here. You can get answers on how to write them, fix them and the like eventually but you may find yourself running a gauntlet of questions about why you would want to do such a thing before you get assistance. Scripts that make it harder to provide help do not endear you to the volunteers who provide the help.
Q: How do I shorten my lengthly if() statements?

A: There are a number of 'tricks' you can use to do this.

Take this code:
PHP Code:

<script type="text/javascript"> var a=prompt("Enter number",""); var b=prompt("Enter number",""); if(a==b){ alert(true); } else{ alert(false); } </script>
As if() statements always return either true or false, you can just do this:
PHP Code:

<script type="text/javascript"> var a=prompt("Enter number 2",""); var b=prompt("Enter number 2",""); alert(a==b); </script>
This is alerting the result of the test, which is (a==b).


PHP Code:

<script type="text/javascript"> var a=prompt("Enter number 3",""); var b=prompt("Enter number 3",""); if(!a||!b){ alert("Enter a number") } else if(a==b){ alert("Equal"); } else{ alert("Not equal");

} </script>
As you can see, this tests whether two inputted numbers are equal, alerting a different message depending on: A) If they don't enter two numbers B) If the numbers are equal C) If the numbers are not equal. As in each if(), else if(), else statement, we are doing the same thing (alerting) but alerting something different we can use this:
PHP Code:

<script type="text/javascript"> var a=prompt("Enter number 4",""); var b=prompt("Enter number 4",""); [B]alert((!a||!b)?"Enter a number":(a==b)?"Equal":"Not equal");[/B] </script>
Note the line in bold. This is how we write it: First we start with alert(. We then put our first condition (inside the first if()) in brackets. So: alert((!a||!b) We then put a question mark after, to show it's an if() statement. We then put the text to alert if this condition is true, so: alert((!a||!b)?"Enter a number" Instead of else, we put a colon : . We then repeat what we have already done. So: alert((!a||!b)?"Enter a number":(a==b)?"Equal" The bit in bold is the condition for the else if() statement. The bit after is the resulting alert. If there are more else if() statements, we put a colon, and repeat. When we get to the last else, we just put a colon and the text to alert if the previous if() and else if()s were all false. In this case, we put a bracket to close the alert() function. We end up with: alert((!a||!b)?"Enter a number":(a==b)?"Equal":"Not equal");


In if() statements or similar, we never need to use the following: if(a==true) if(b==false) Instead of the first, we just need the a. So: if(a) Instead of the second, we put an ! in front of the variable. So: if(!b)


Take this:

PHP Code:

<script type="text/javascript"> function disdate(){ var d=new Date(); var day=d.getDate(); if(d.getMonth()==0){ var months="Jan" } else if(d.getMonth()==1){ var months="Feb" } else if(d.getMonth()==2){ var months="Mar" } //repeat right up until: else if(d.getMonth()==11){ var months="Dec" } document.getElementById("thedate").value=months; } </script>
As we are testing a variable against numbers 0-11, we can use an array to store all our months:
PHP Code:

<script type="text/javascript"> function disdate(){ var d=new Date(); var day=d2.getDate(); var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov" ,"Dec"]; document.getElementById("thedate").value=months[d.getMonth()] } </script>
All the months are stored in an array named months. We refer to each item like this: months[0] for the first months[1] for the second months[2] for the third etc. Instead of the number, we use d.getMonth() inside the square brackets, as this returns the number of the item we want.

JavaScript Interview Questions for both Experienced Programmers and Freshers

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

2) What is the difference between JavaScript and Jscript? Ans:Both JavaScript and Jscript are almost similar. JavaScript was developed by Netscape. Microsoft reverse engineered Javascript and called it JScript. 3) How do we add JavaScript onto a web page? Ans:There are several way for adding JavaScript on a web page, but there are two ways which are commonly used by developers If your script code is very short and only for single page, then following ways are the best: a) You can place <script type="text/javascript"> tag inside the <head> element. Code
Collapse | Copy Code

<head> <title>Page Title</title> <script language="JavaScript" type="text/javascript"> var name = "Vikas Ahlawta" alert(name); </script> </head>

b) If your script code is very large, then you can make a JavaScript file and add its path in the following way: Code
Collapse | Copy Code

<head> <title>Page Title</title> <script type="text/javascript" src="myjavascript.js"></script> </head>

4) Is JavaScript case sensitive? Ans:Yes! A function getElementById is not the same as getElementbyID. 5) What are the types used in JavaScript? Ans:String, Number, Boolean, Function, Object, Null, Undefined. 6) What are the boolean operators supported by JavaScript? And Operator: && Or Operator: || Not Operator: ! 7) What is the difference between == and ===? Ans: == checks equality only, === checks for equality as well as the type. 8) How to access the value of a textbox using JavaScript? Ans: ex:Code
Collapse | Copy Code

<!DOCTYPE html> <html> <body> Full name: <input type="text" id="txtFullName" name="FirstName" value="Vikas Ahlawat"> </body> </html>

There are following ways to access the value of the above textbox:
Collapse | Copy Code

var name = document.getElementById('txtFullName').value; alert(name);

or: we can use the old way:

Collapse | Copy Code

document.forms[0].mybutton. var name = document.forms[0].FirstName.value; alert(name);

Note: This uses the "name" attribute of the element to locate it. 9) What are the ways of making comments in JavaScript? Ans:
Collapse | Copy Code

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

is used for block comments

Collapse | Copy Code

ex:var x= 10; /* this is block comment example.*/

10) How will you get the Checkbox status whether it is checked or not? Ans:
Collapse | Copy Code

var status = document.getElementById('checkbox1').checked; alert(status);

will return true or false.

11) How to create arrays in JavaScript? Ans:There are two ways to create array in JavaScript like other languages: a) The first way to create array Declare Array: Code
Collapse | Copy Code

var names = new Array(); Add Elements in Array:names[0] = "Vikas"; names[1] = "Ashish"; names[2] = "Nikhil";

b) This is the second way:

Collapse | Copy Code

var names = new Array("Vikas", "Ashish", "Nikhil");

12) If an array with name as "names" contain three elements, then how will you print the third element of this array? Ans: Print third array element document.write(names[2]); Note:- Array index starts with 0. 13) How do you submit a form using JavaScript? Ans:Use document.forms[0].submit(); 14) What does isNaN function do? Ans: It returns true if the argument is not a number. Example: Code
Collapse | Copy Code

document.write(isNaN("Hello")+ "<br>"); document.write(isNaN("2013/06/23")+ "<br>"); document.write(isNaN(123)+ "<br>");

The output will be:

Collapse | Copy Code

true true false

15) What is the use of Math Object in JavaScript? Ans: The math object provides you properties and methods for mathematical constants and functions. ex:Code

Collapse | Copy Code

var x = Math.PI; // Returns PI var y = Math.sqrt(16); // Returns the square root of 16 var z = Math.sin(90); Returns the sine of 90

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

Collapse | Copy Code

var obj = { outerWidth : 20 }; function say() { alert(this.outerWidth); } say();//will alert window.outerWidth say.apply(obj);//will alert obj.outerWidth

17) What does "1"+2+4 evaluate to? Ans: Since 1 is a string, everything is a string, so the result is 124. 18) What does 3+4+"7" evaluate to? Ans: Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it is concatenation, so 77 is the result. 19) How do you change the style/class on any element using JavaScript? Ans: Code
Collapse | Copy Code

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

-orCollapse | Copy Code

document.getElementById(myText).className = anyclass;

20) Does JavaScript support foreach loop? Ans: JavaScript 1.6(ECMAScript 5th Edition) support foreach loop, See example here 21) What looping structures are there in JavaScript? Ans: for, while, do-while loops 22) What is an object in JavaScript, give an example? Ans: An object is just a container for a collection of named values:

// Create the man object Code

Collapse | Copy Code

var man = new Object(); = 'Vikas Ahlawat'; = true; man.age = 27;

23) How you will add function as a property in a JavaScript object? Give an example. Ans: Code
Collapse | Copy Code

var man = new Object(); = 'Vikas Ahlawat'; = true; man.age = 27; man.getName = function() { return;} console.log(man.getName()); // Logs 'Vikas Ahlawat'.

24) What is the similarity between the 1st and 2nd statement? 1st:- var myString = new String('male'); // An object. 2nd:- var myStringLiteral = 'male'; // Primitive string value, not an object. Ans: Both will call String() constructor function You can confirm it by running the following statement:
Collapse | Copy Code

console.log(myString.constructor, myStringLiteral.constructor);

25) What will be the output of the following statements? Code

Collapse | Copy Code

var myString = 'Vikas' // Create a primitive string object. var myStringCopy = myString; // Copy its value into a new variable. var myString = null; // Manipulate the value console.log(myString, myStringCopy); Ans: // Logs 'null Vikas'

26) Consider the following statements and tell what would be the output of the logs statements?
Collapse | Copy Code

var price1 = 10; var price2 = 10; var price3 = new Number('10'); // A complex numeric object because new was used. console.log(price1 === price2); console.log(price1 === price3);


Collapse | Copy Code

console.log(price1 === price2); // Logs true. console.log(price1 === price3); /* Logs false because price3 contains a complex number object and price 1 is a primitive value. */

27) What would be the output of the following statements?

Collapse | Copy Code

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

Ans: // Logs false, JavaScript does not care that they are identical and of the same object type. When comparing complex objects, they are equal only when they reference the same object (i.e., have the same address). Two variables containing identical objects are not equal to each other since they do not actually point at the same object. 28) What would be the output of the following statements? Code
Collapse | Copy Code

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

Ans: // Logs true 29) What is this?

Collapse | Copy Code

var myArray = [[[]]];

Ans: Three dimensional array 30) Name any two JavaScript functions which are used to convert nonnumeric values into numbers? Ans:
Collapse | Copy Code

Number() parseInt() parseFloat()

Collapse | Copy Code

var var var var var

n1 n2 n3 n4 n5

= = = = =

Number(Hello world!); Number(); Number(000010); Number(true); Number(NaN);

//NaN //0 //10 //1 //NaN

31) Does JavaScript Support automatic type conversion, If yes give example. Ans: Yes! Javascript support automatic type conversion. You should take advantage of it, It is most common way of type conversion used by Javascript developers. Ex.
Collapse | Copy Code

var s = '5'; var a = s*1; var b = +s; typeof(s); //"string" typeof(a); //"number" typeof(b); //"number"

*Question(31) suggested by Florian Rappl