I have this code:
var phrase = function (variable, defaultPhrase) {
if (typeof variable === \"undefined\") {
return defaultPhrase;
}
else
Usually using ||
is enough, like others have suggested. However, if you want to have 0, false and null as acceptable values, then you indeed need to check if the type of the variable is undefined. You can use the ternary operator to make it a one-liner:
var variable;
var defaultPhrase = "Default";
var phrase = (typeof variable === "undefined" ? defaultPhrase : variable);
console.log(phrase);
// => "Default"