JavaScript - Frequently Asked Questions
Page 1 of 1 • Share •
JavaScript - Frequently Asked Questions
Index:
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 use confirms to force a certain path to be taken. If you want to be able to cut and paste the results, you may want to use prompts.
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, for..in 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 the debugger 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's JavaScript Environment, view scripts bookmarklet, JavaScript Shell or view variables bookmarklet; or my ViewScripts bookmarklet.
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:
Code:
defaults write com.apple.Safari 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:
Code:
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 secure parts 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 Date object.
Deleting cookies is done by overwriting a cookie, setting the expiry time in the past. Thus,
Code:
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.
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.
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 non-essential 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:
Code:
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:
Code:
var
nYourNumber=300.3,
sYourFormattedNumber=nYourNumber.toDecimals(2); // => '300.30'
Q:How do I trim whitespace from the beginning and end of a string?
Q:Why does parseInt('08') generate 0?
Q:How do I read/write files?
Q:How do I get multiple scripts to work on a single page?
Q:How do I convert a decimal number to hexadecimal, and the other way around?
Q:How do I add ordinals (st, nd, rd, th) to a number?
Q:How do I use JavaScript in external files?
Q:How can I use Javascript to protect my web pages?
Q:How do I shorten my lengthly if() statements?
Q:How do I hide my JavaScript source code?
Q:How do I use 'javascript:' links?
Remaing answers will be post later
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 use confirms to force a certain path to be taken. If you want to be able to cut and paste the results, you may want to use prompts.
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, for..in 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 the debugger 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's JavaScript Environment, view scripts bookmarklet, JavaScript Shell or view variables bookmarklet; or my ViewScripts bookmarklet.
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:
Code:
defaults write com.apple.Safari 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:
Code:
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 secure parts 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 Date object.
Deleting cookies is done by overwriting a cookie, setting the expiry time in the past. Thus,
Code:
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.
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.
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 non-essential 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:
Code:
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:
Code:
var
nYourNumber=300.3,
sYourFormattedNumber=nYourNumber.toDecimals(2); // => '300.30'
Q:How do I trim whitespace from the beginning and end of a string?
Q:Why does parseInt('08') generate 0?
Q:How do I read/write files?
Q:How do I get multiple scripts to work on a single page?
Q:How do I convert a decimal number to hexadecimal, and the other way around?
Q:How do I add ordinals (st, nd, rd, th) to a number?
Q:How do I use JavaScript in external files?
Q:How can I use Javascript to protect my web pages?
Q:How do I shorten my lengthly if() statements?
Q:How do I hide my JavaScript source code?
Q:How do I use 'javascript:' links?
Remaing answers will be post later

Admin- Admin
- Posts: 95
Join date: 2007-12-02

Re: JavaScript - Frequently Asked Questions
Thanks admin
Very interesting to read this and also post remaining questions
Regards
Sakthi
Very interesting to read this and also post remaining questions
Regards
Sakthi

sakthi- Leader
- Posts: 187
Join date: 2007-12-02
Age: 25
Location: Coimbatore
Permissions of this forum:
You cannot reply to topics in this forum





