I have this code:
var phrase = function (variable, defaultPhrase) {
if (typeof variable === "undefined") {
return defaultPhrase;
}
else {
return variable;
}
}
It's called like this:
Ext.Msg.show({title: phrase(js_shutdown,'Shutdown'), //...
What I want to do is to use a default phrase when the variable is not defined, but when I pass an undefined variable to phrase(), JS throws an undefined variable error. How do I fix this? Any other ideas to do this?
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).
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"
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.
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).
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.
Shouldn't it be:
var phrase = function (variable, defaultPhrase){
if(variable == undefined){
return defaultPhrase;
}else{
return variable;
}
}
Related
I did some research but I didn't find a satisfying answer yet. I have a javascript project file and a library where some functions are defined like this:
//Library.js
FElib = {
initLib: function(param1, param2){
var init = param1 || true;
console.log(init);
}
}
Now in my project.js file I call the function and pass false as a parameter
FElib.initLib(false, 'test');
In this case param1 is giving me 'false' if I log it before the variable declaration. Afterwards it's using the default 'true'. It seems like it is interpreting false as undefined were I thought that it's only checking for undefined..
Why is the behaviour like this?
When I'm using a string it's perfectly working. Using 0 or 1 as a parameter is also not working and it's using the default variable declaration..
As a workaround I declared the variable as an object which is workin fine again like so:
//Library.js
FElib = {
initLib: function(options){
var defaults = {
param1: true,
param2: 'string',
};
var options = $.extend({}, defaults, options);
}
}
Now calling the function is working fine even with boolean arguments:
FElib.initLib({'param1':false, 'param2':'string123'});
The 2nd approach seems to have a little overhead thinking of a function with only 1 boolean variable as an argument.
Can anybody explain this behaviour?
UH... because init = param1 || true isn't checking for undefinedness, it's checking for falsiness.
false is, obviously, falsy, and it is therefore replaced with true.
If you want to check for undefinedness, there is no real shorthand to it:
var init = typeof param1 === "undefined" ? true : param1;
The problem is here:
var init = param1 || true;
The boolean OR operator (||) returns true there, since it's evaluating: false || true;
"False or True" is always "True".
If you want to check if the parameter is undefined, use something like this:
var init = (typeof param1 === "undefined") ? true : param1;
Because the || operator is testing for truthyness, not definedness.
You will get the right hand side of the || operator if the left hand side evaluates as false, which false does.
If you want to test if a value is defined use:
var init = param1;
if (typeof param1 === "undefined") {
init = true;
}
or
var init = (typeof param1 === "undefined") ? true : param1;
This question already has answers here:
How can I check for "undefined" in JavaScript? [duplicate]
(16 answers)
Closed 9 years ago.
in another question on SO, I was determining how to toggle off a function, and the working solution is this:
I place var disabledFlag = true; in the head section of my page and before calling shell.js, then in shell.js I have:
/*******************************/
/* TOGGLE BUTTON
/*******************************/
var toggleBlock = function() {
console.log(disabledFlag);
if(!disabledFlag){
var windowsize = $(window).width(),
isDesktop = windowsize > 765;
$("#quicksearch").toggleClass("collapse in", isDesktop);
$("#quicksearch").toggleClass("collapse out", !isDesktop);
$("#sidebar").toggleClass("collapse in", isDesktop);
$("#sidebar").toggleClass("collapse out", !isDesktop);
}
else {
$("#quicksearch").addClass("collapse out");
$("#sidebar").addClass("collapse out");
}
}
$(document).ready(toggleBlock);
$(window).on("resize.showContent", toggleBlock);
toggleBlock();
shell.js is an common file that is shared with other sites and may not have the variable defined. how do I check if the variable is defined, and if not assign it to false and then execute the code above?
try
if (typeof disabledFlag === 'undefined')
disabledFlag = false;
There are easier ways to do it than using ternaries or if else statements.
As far as your specific function goes, you could do something like this:
var toggleBlock = function() {
var disabledFlag = disabledFlag||false;
if(!disabledFlag){
//etc.
undefined is falsy, so it works with the logical || operator. That || operator makes the new var disabledFlag be set to disabledFlag (if it exists), and if not, it will set the var to false
This same concept is used in many different contexts. For example:
Situation 1 -
var obj = {hello: 'world'};
function fn(object) {
var object = object || {foo: 'bar'};
return object;
}
fn(obj) // ==> {hello: 'world'}
Situation 2 -
function fn(object) {
var object = object || {foo: 'bar'};
return object;
}
fn(objectThatDoesntExist); // ==> {foo: 'bar'}
In JavaScript libraries and module-pattern projects, this concept is used quite frequently in many different ways.
You don't need typeof
if (window.disabledFlag === undefined) window.disabledFlag = false;
you can check if a variable is undefined with the typeof keyword, like this:
if(typeof neverDeclared == "undefined") //no errors
if(neverDeclared == null) //throws ReferenceError: neverDeclared is not defined
take a look here for more info on typeof
I am writing a script that deals with a variable gameRegion like so:
//In the main of the script
var variable= new work();
variable.onCrash(crashHandler,{xPos:650,yPos:300});
// In function work()
var gameRegion;
var onCrashCallback;
this.onCrash = function(crashCallback,fieldSize) {
gameRegion = fieldSize;
onCrashCallback = crashCallback;
};
crashHandler(){
//unimportant
}
this.atBottom = function(ypos) {
if(ypos>gameRegion.yPos) //line with the problem
return true;
return false;
};
I am getting the console error: TypeError: 'undefined' is not an object (evaluating 'gameRegion.yPos'). Presumably that means I am not properly defining gameRegion or its variable yPos. I've been looking at this code for a while now and I can't seem to find what the problem is.
Hopefully you'll see something that I don't, but if I'm not including necessary code for context, please tell me. Thanks for any help in advance.
You have to handle 'undefined'. Which can be done in these ways:
typeof(foo) == 'undefined'
typeof foo !== 'undefined'
window.foo !== undefined
'foo' in window
The first three should be equivalent (as long as foo isn't shadowed by a local variable), whereas the last one will return true if the global varible is defined, but not initialized (or explicitly set to undefined).
You can use typeof like so -
return (typeof (gameRegion) !== "undefined" &&
typeof(gameRegion.yPos) !== "undefined" &&
ypos > gameRegion.yPos);
I have this code:
var phrase = function (variable, defaultPhrase) {
if (typeof variable === "undefined") {
return defaultPhrase;
}
else {
return variable;
}
}
It's called like this:
Ext.Msg.show({title: phrase(js_shutdown,'Shutdown'), //...
What I want to do is to use a default phrase when the variable is not defined, but when I pass an undefined variable to phrase(), JS throws an undefined variable error. How do I fix this? Any other ideas to do this?
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).
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"
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.
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).
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.
Shouldn't it be:
var phrase = function (variable, defaultPhrase){
if(variable == undefined){
return defaultPhrase;
}else{
return variable;
}
}
Got confused by this behaviour. I thought doing something like:
if (variable name)
{
... do this...
}
should work. However if the variable is not defined, I just get 'ReferenceError: Can't find variable: "variable name, and the else block won't even be executed. For example the following snippet that I got off another StackOverflow question doesn't work when I test it. Any suggestions?
if(persons_name)
{
var name = persons_name;
}
else
{
var name = "John Doe";
}
if (typeof persons_name !== 'undefined') {
...
} else {
...
}
Note that you don't need braces with typeof.
Unlike a property, an unqualified name has to be defined before you can use it. So you if you were looking for a global variable persons_name you could write
if (window.persons_name)
and it would evaluate to undefined if persons_name didn't exist. Alternatively, you can simply declare persons_name if you expect it to exist.
var persons_name;
This won't change the value of persons_name if it already exists.
var name = (typeof persons_name !== 'undefined' || !(!!persons_name)) ?
persons_name :
'John Doe';
by saying var name; you define the variable; and by saying var name = "john doe"; you assign it a value.