[thelist] Some confusions about JavaScript

Liorean Liorean at user.bip.net
Mon Mar 4 14:49:10 CST 2002


At 00:46 2002-03-05 +0500, Syed Zeeshan Haider wrote:
>Hello Experts,
>I have some confusions about JavaScript.
>1.    I many times observe following situation in JS written by others:
>if(!x){
>//then do whatever
>}
>Here x is a variable declared by var. "!x" is confusing. Where do
>JavaScripters use such syntax of JS? Which situations need things like
>"!x"?

! is a negating operator, meaning that it converts false to true and true
to false.
But not only does it that. It's useful for checking if an object/variable
exists since [undefined, null, 0, '', "", false] gets converted to the
boolean value false before negating, and anything else gets converted to
the boolean value true before negating.

Example:
if(!document.layers){
/* code to execute only if document.layers doesn't exist */
}


>2.    I often use "while" instead of "for" in JavaScript, because "for"
>is not very friendly to me. Consider this example:
>for(i=0;i<10;i++)
>{
>// do whatever
>}
>Will the loop between {} start at i=0 or it will start at i=1?
>In the same way, when will the loop end? At i=10 or i=9?

It will start at 0, as that is the initial value set in the first argument.
It will end at 9, since the second argument will be false at 10 and thus
the loop will not continue.

// Liorean




More information about the thelist mailing list