[thelist] Some confusions about JavaScript

Ben Dyer ben_dyer at imaginuity.com
Mon Mar 4 14:11:08 CST 2002


On 01:46 PM 3/4/2002, Syed Zeeshan Haider said to me:
>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"?

It is simply shorthand notation for if (x!=0) or if (x!='')...I think.  I
don't believe there are any differences between the two.

>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
>}

While loops and for loops are different, it's not really a matter of
friendliness.  The general principle is that While loops go on until a
particular condition is met (where you don't know how many times you have
to loop through) and For loops go on only a certain, prespecified number of
times.

The three parts of the for loop are:

i=0, which sets the initial start value for the index
i<10, which tells the loop how far to, well, loop
i++, which tells the loop what to do everytime it cycles through the loop.

So basically, the loop index starts at 0, does whatever it's told,
increments by 1 (that's what ++ means) until it is greater than or equal to 10.

>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?

If I remember correctly, the incrementing doesn't happen until the
JavaScript inside the loop does its business.  So, it would perform the
code and then increment i.  Therefore, the loop would end when the
conditions were no longer met (that is, when i got to 10, because 10 is not
less than 10).

So, the loop will start at 0 and will end after it's done with 9.

Clear as mud?  Maybe someone else can explain that better than me...

--Ben


Ben Dyer, Senior Internet Developer, Imaginuity Interactive
http://www.imaginuity.com/

     If you save the world too often, it begins to expect it.
-----------------------------------------------------------------
   http://members.evolt.org/OKolzig37/     http://www.evolt.org/




More information about the thelist mailing list