[thelist] Some confusions about JavaScript

Burhan Khalid burhankhalid at members.evolt.org
Tue Mar 5 11:48:01 CST 2002


At 03:15 PM 3/4/02 -0500, you wrote:
>On Mon, 2002-03-04 at 14:46, 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"?
>
>!x simply means not x or the negation of x. Therefore if x is declared
>to be false then !x is the same as writting if(x == false) or if(x !=
>true) all it is doing to testing to see if x is false. (or in some other
>languages - C - whether x is 0)

!x can also mean :
         If x is not valid, or is empty/has not value/is NULL


> > 2.    I often use "while" instead of "for" in JavaScript, because "for"
> > is not very friendly to me. Consider this example:
>
>Any for loop can always be replaced with a while loop. It is really just
>a matter of style and personal taste.
>
> > 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?
>
>The loop always starts at whatever you initialze x to be. Therefore, in
>this example i=0, the loop starts at zero. It then checks that
>condition: is i < 10 and if the condition is true, it proceeds through
>the loop. The very last thing it does is to increment i by one. here is
>one way to visualize the way that the loop works:
>
>for (i=0; i<10; { //do whatever } i++) //start the loop over again. In
>reality this is what is happening. Therefore, the loop will actually
>stop at i = 10 but the inside of the loop will only executed up to i =
>9. This means that if you have something like this:
>
>for(i=0;i<10;1++){
>         print i;
>}

not to be picky, but that should be an i instead of a 1 in the for loop.

>the output would be: 0 1 2 3 4 5 6 7 8 9 then i would be equal to 10 and
>the loop would quit without executing anything inside.

Another way to look at it (and the way that I teach it is) :

for (initialization value check (prime); condition; action/increment) {
         ...
}

or

for (set this variable/condition; check for this condition; do this action
while the check condition is false)

Also worthy to note here is that for(;;) is a valid for statement, and is
an infinite loop. In addition, the first part of the for loop is optional,
BUT if you choose not to include it, you must put a semi-colon, a la :

for (; x<50; x++) { do something }


hth,
Burhan Khalid




More information about the thelist mailing list