Be careful when using || to set default values in JavaScript
(This post was originally titled "Don't use || to set default values in JavaScript". However, if you're careful to avoid the pitfalls and your whole team understands the syntax ||
can be convenient to use.)
If you're working with JavaScript I'm sure you've seen code that uses the OR operator (||) like this:
function eatFruit (fruit) { fruit = fruit || "strawberry"; ... }
What does this do? It sets a default value!
When the function is called without any arguments the value of fruit is set to "strawberry".
If the fruit
parameter is set it's just assigned its own value, so the value doesn't change.
Read full article from Be careful when using || to set default values in JavaScript
No comments:
Post a Comment