chuanxshi / javascript-patterns

JavaScript Design Patterns

Home Page:http://shichuan.github.io/javascript-patterns

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

For loops question

DjebbZ opened this issue · comments

You say

substitute i++ with i = i + 1 or i += 1 to avoid excessive trickiness

So why not substituting i-- with i = i -1 or i -= 1 in the 2 preferred methods ?

Agreed with this, seems you are relying on 2 types of trickiness for the i-- examples: 0 being falsy, and i-- returning the value of i before the decrement operation.

@DjebbZ @Feodoric problem is, if you try i = i -1 or i -= 1 with an array, it will not return the first item in the array.

I understand. In the last loop iteration, after i-- is evaluated, i equals 0, which is falsy. Can you confirm ?

Typically, I don't even do i--, I do --i instead
Crockford roughly went through the reason with "++" in http://www.youtube.com/watch?v=taaEzHI9xyY&t=50m42s

What makes "++" a special case is that "+" is also used for string concatenation, so I suppose it is easier to make mistake. Coming from C++ world, I don't see it as a big deal. However, both Crockford and I would agree that ++i and --i are not the same as i++ and i-- (the former usage is preferred, whereas later should be avoided)

Thanks for the answers. Closing since it's been open for a long time.