DEV Community

Discussion on: Demystifying the Long Arrow "Operator"

Collapse
 
okdewit profile image
Orian de Wit

Watch out with that notation though, it's best to only use it on integers declared as a constant.

let x = 2

// Wait, you have to pay taxes over your loops!
x *= 1.1

while (x--) { 
  console.log("Nothing can be said to be certain, except death and taxes")
} 
Collapse
 
dimpiax profile image
Dmytro Pylypenko

You need to know what you are doing with your code.

Thread Thread
 
okdewit profile image
Orian de Wit

Certainly! But with Javascript not having an int type, it can lead to unexpected bugs.

Sometimes the space between the declared variable and the loop fills up with other code, especially in a project that's not squeaky clean to begin with.
Or the variable was passed in as an argument to a function, and eventually someone calls the function with unexpected input.

Maybe a coworker wants to loop over something in batched chunks, and naively divides x by a chunkSize.

Assuming that x in while(x--) is an integer which will hit zero isn't necessarily bad, just something to be careful with.

Thread Thread
 
dimpiax profile image
Dmytro Pylypenko • Edited

It's true that it is dangerous.
I see a reason to use tools (approaches) in related situations.
Construction without zero only in the case, when you know what you do. For example, iterate through array elements from the end:

const arr = ["this", "is", "c", "h", "a", "r"]
let n = arr.length
while(n--) {
  const el = arr[n]
  ...
}

or count input value as a number. In this case, input can be any, the function must know the type and cast to it. If float – make it as int by parseInt or Math functions.