I have this code:
var phrase = function (variable, defaultPhrase) {
if (typeof variable === \"undefined\") {
return defaultPhrase;
}
else
It's a javascript error to reference an undefined variable with no scope in your function call. So, if the variable js_shutdown
doesn't exist in scope, then this:
Ext.Msg.show({title: phrase(js_shutdown,'Shutdown'), //...
is an error.
For example, this code causes an error on the line that calls the phrase()
function:
var Ext = {};
Ext.Msg = {};
Ext.Msg.show = function() {console.log("success")};
function phrase(variable, defaultPhrase) {
return(variable || defaultPhrase);
}
Ext.Msg.show({title: phrase(js_shutdown,'Shutdown')});
because the javascript engine isn't able to find js_shutdown in any scope.
But, this is OK:
var Ext = {};
Ext.Msg = {};
Ext.Msg.show = function() {console.log("success")};
function phrase(variable, defaultPhrase) {
return(variable || defaultPhrase);
}
Ext.Msg.show({title: phrase(window.js_shutdown,'Shutdown')});
You can see that this works here: http://jsfiddle.net/jfriend00/JFz6R/
Because you've told the JS engine exactly where to look for js_shutdown and when it isn't there, it just passes undefined to the phrase function (as you want).
In javascript, you typically use the OR operator ||
to provide an alternative value when a variable is undefined:
return variable || defaultPhrase || ''
In case variable
is undefined, it will evaluate to false then the second part of the test will be evaluated, if it is also undefined, you can still return an empty string.
Shouldn't it be:
var phrase = function (variable, defaultPhrase){
if(variable == undefined){
return defaultPhrase;
}else{
return variable;
}
}
You don't need a function. The ||
operator is usually used:
Ext.Msg.show({ title: js_shutdown || 'Shutdown', //...
You can see ||
as:
someValue || defaultValue
For strings, defaultValue
is used if someValue === ""
.
If the variable is not defined at all, you'll need to inline the typeof x === "undefined"
check, because you cannot pass the variable to a function (that's a ReferenceError
).
Use the logical OR operator:
var phrase = variable || defaultPhrase;
Or inline:
Ext.Msg.show({title: (js_shutdown || 'Shutdown')), //...
I would usually code this like title: js_shutdown || 'Shutdown'
in the absence of possible security issues.