I know that it is bad practice to write code like this:
var createBox = function(width, height, margin){
alert("Margin is set to " + margin);
//margin is undefined in this context or why?
var margin = margin || 2;
alert("Margin is now " + margin);
}
createBox(0,0,0);
But can someone please explain, why margin is always set to 2?
Is it because it is undefined in the direct context of initializing a variable with the same name inside the function?
edit: sorry, I got the problem wrong …
Please give a small hint 🙂
Regards, Tom
The
||operator in JavaScript returns the value of the first operand if the first operand is truthy. Otherwise it returns the value of the second operand. It doesn’t return1/0, ortrue/false, as in some other languages.Therefore when the
marginargument holds a falsy value, such as0orundefined, it will return2, since these are both falsy values in JavaScript.The falsy values in JavaScript are: an empty string
"", thenullvalue, a value of0, theNaNvalue, the boolean valuefalse, and alsoundefined.What you describe is a very common idiom in JavaScript. In fact the
||operator is sometimes called the default operator1. You can use it to assign default values to variables when they areundefined. The problem in this case is that since0is a valid argument, the default operator is not behaving as required. You may want to do the following instead:1 Douglas Crockford: The Elements of JavaScript Style – Part 2 – Idioms.