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
Related
This question already has answers here:
ES6 arrow function and lexical scope inside a function [duplicate]
(2 answers)
Closed 4 years ago.
How can I get the reference to what's being return to the method call? Like how we have the arguments variable to get all arguments being passed to a function. How can I get what's being returned to so I can chain a function?
let myFunc = function(obj, num){
if (typeof obj === 'number' && typeof num === 'undefined') {
num = obj;
obj = this;
}
console.log(obj.name);
console.log(num);
console.log(Object(this));
return obj;
};
let myObj = {
name: 'Devin',
};
myFunc(myObj, 1);
myObj.myFunc = myFunc;
myObj.myFunc(2).myFunc(3);
edit: It's written out this because it's currently used in many places that I will have to refactor down the road but do not have time to right now. So I'm trying to do a few changes that don't affect current code but will work the way I want moving forward. myFunc(myObj, 1) is current but I have done a minor refactor to inline like so... myObj.myFunc(myObj, 2).myFunc(myObj, 3) ... but I thought I could remove myObj as an argument since it's being returned.
edit 2: Changed arrow es6 function to using function keyword to keep this context and added console.log(Object(this)). But still getting undefined from myObj.name and Object(this) only gives the argument
ANSWER: The problem was that I was using an arrow function and that I had typeof num === 'number' instead of equal to 'undefined'. Thank you.
myFunc.bind(myObj) doesn't serve any good purpose because arrows cannot be bound. In order to use dynamic this it should be regular function, e.g. shorthand syntax:
let myObj = {
name: 'Devin',
myFunc(num) {
console.log(num);
return this;
}
};
myObj.myFunc(2).myFunc(3); // basically a noop
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;
}
}
This question already has answers here:
Is there an equivalent of the __noSuchMethod__ feature for properties, or a way to implement it in JS?
(6 answers)
Closed 7 years ago.
I would like to override accessor of a javascript object so that instead of override it should return a fixed value.
eg.
var obj = {};
console.log(obj.someProperty) //will print undefined expected value false
If a property is undefined there is no way to have it return false by default but it will be "falsey".
For example:
var obj = {};
if (!obj.someProperty) {
console.log("expression is falsey");
}
A more explicit way to test truthiness is to use the double bang operator:
var obj = {};
console.log(!!obj.someProperty) // print's undefined, but evaluates to false
But in short, what you are going after will not work because in JavaScript you cannot redefine undefined.
I would do this with the following:
var obj = {};
if (!obj.hasOwnProperty('itdoesnthavethis')) console.log('property is not there')
This will always return a boolean and will not check through the object's prototype chain for the property, just the object itself.
Read more here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
With ES6 and its Proxy feature you can do something like this:
var obj = {};
obj = new Proxy(obj, {
get: function(target, prop) {
var pv = target[prop];
return pv === undefined ? false : pv;
}
});
that will essentially create proxy wrapper around your object handling property get operations.
With ES5 something like that is impossible to achieve for an arbitrary property.
But if set of properties is known you can design your own object class:
function MyObject() {}
MyObject.prototype.foo = false;
MyObject.prototype.bar = false;
MyObject.prototype.baz = false;
and use it as:
var obj = new MyObject();
console.log(obj.foo); // false
console.log(obj.bar); // false
console.log(obj.foobar); // undefined
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;
}
}