homepage Welcome to WebmasterWorld Guest from 54.234.147.84
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Why is i++ different from i+1?
You're incrementing by one. I don't see the difference...
1337Mac




msg:3889234
 7:09 pm on Apr 9, 2009 (gmt 0)

I was playing with this example on W3 Schools...

[w3schools.com...]

and I noticed that if you change the i++ part of the script to i+2 or even i+1 it causes an infinite loop.

Why on Earth would that be?

 

1337Mac




msg:3889240
 7:12 pm on Apr 9, 2009 (gmt 0)

Wait...
is it because you need to type i=i+1;
?

1337Mac




msg:3889241
 7:14 pm on Apr 9, 2009 (gmt 0)

D'oh! Yes... I understand now. Sorry for the n00b question.

DrDoc




msg:3889244
 7:16 pm on Apr 9, 2009 (gmt 0)

i++ is short for i = i + 1, or i += 1. Simply saying i + 1 does not actually increase the value of i.

for(i = 0; i < 5; i++) { 
document.write(i);
}
for(i = 0; i < 5; i+=1) {
document.write(i);
}
for(i = 0; i < 5; i+=2) {
document.write(i);
}

Those are all viable options.

astupidname




msg:3889250
 7:27 pm on Apr 9, 2009 (gmt 0)

If you need the next level of understanding how incrementing of variables works, you may be interested in this thread also:
complete newbie - increments [webmasterworld.com]

1337Mac




msg:3889606
 4:38 am on Apr 10, 2009 (gmt 0)

Thank you both.

@astupidname: I browsed that thread (being a newbie I felt it was my duty) and I did learn something new! : Didn't realize you could do y=++x

jalarie




msg:3890246
 10:42 pm on Apr 10, 2009 (gmt 0)

Also notice that i++ can produce different results from what you get with i+=1. The i++ forces i to be numeric and then adds 1 to it; the i+=1 may, in some situations, think that i is a character string and tack a 1 on the end.

coopster




msg:3890258
 11:05 pm on Apr 10, 2009 (gmt 0)

Not to add confusion, but perhaps some enlightenment -- if you ever come across a single plus sign in front of a variable you are likely viewing an example of the unary [webmasterworld.com] operator.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved