[thelist] Some confusions about JavaScript

Chris Johnston chris at fuzzylizard.com
Mon Mar 4 14:11:01 CST 2002


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)

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

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.




More information about the thelist mailing list