What I want to achieve is clean code with several possible null returns where I'm not returning in more than one place, the code is easy to follow and is not a nested nightmare. For example consider
var topLevel = testdata['key'];//testdata['key'] may be null
var nextLevel = topLevel['subkey']; //topLevel['subkey'] may be null
var subSubLevel = ...
My initial thoughts are to do something like
var topLevel = testdata['key'] || 'error';
This will at least stop the "cannot get x of null" errors but then I'll have a block at the end where I'll need to check if each of these vars is error and if so return null and provide an appropriate error message (probably with an associative object).
Does anyone have a smarter, more concise way of achieving the same end result?
I'd probably do it with JavaScript's curiously-powerful && operator (the cousin of the curiously-powerful || operator you're already using):
var topLevel = testdata['key'];
var nextLevel = topLevel && topLevel['subkey'];
// ...
If topLevel is falsey (null, undefined, and so on), nextLevel will get that falsey value (the left-hand operand); if not, the right-hand operand is evaluated and nextLevel receives the value of that. Using these kinds of guards, you can keep going as long as you want.
var topLevel = testdata['key'];
var nextLevel = topLevel && topLevel['subkey'];
var nextNextLevel = nextLevel && nextLevel['key3'];
var nextNextNextLevel = nextNextLevel && nextNextLevel['key4'];
This is really handy when you're expecting an object reference, null, or undefined.
Related
I am just wondering why when I call the 'hasOwnProperty' method multiple times, I am only being returned one boolean value in the console? It is always the final call that returns.
The rest of my code is fully functional and if I switch round the order I call to check on where the 3 properties are it returns whichever call came last.
spot.hasOwnProperty("sit");
spot.hasOwnProperty("name");
spot.hasOwnProperty("species");
Cheers guys.
They all return but the console just displays output of the latest command; You can put them in an array to see all responses at once
[spot.hasOwnProperty('sit'), spot.hasOwnProperty('name')]
Lacking context, I'm assuming this comes down to just Boolean logic. If you check your actions one at a time you will get the correct value.
var spot = {};
spot.sit = true;
//spot.name = "Spot";
spot.species = "dog";
console.log(spot.hasOwnProperty('sit'));
console.log(spot.hasOwnProperty('name'));
console.log(spot.hasOwnProperty('species'));
There are 2 options if you are checking all values at once: Boolean AND (&&) or Boolean OR (||).
var spot = {};
//spot.sit = true;
spot.name = "Spot";
spot.species = "dog";
// Boolean OR
console.log(spot.hasOwnProperty('sit') || spot.hasOwnProperty('name') || spot.hasOwnProperty('species'));
// Boolean AND
console.log(spot.hasOwnProperty('sit') && spot.hasOwnProperty('name') && spot.hasOwnProperty('species'));
Given this function:
var test = function(param1, param2_maybe_not_set) {
var my_object = {};
// code here...
}
What's the best, in your opinion?
my_object.new_key = (param2_maybe_not_set === undefined) ? null : param2_maybe_not_set;
OR
my_object.new_key = (param2_maybe_not_set === void 0) ? null : param2_maybe_not_set;
OR
my_object.new_key = (typeof param2_maybe_not_set === 'undefined') ? null : param2_maybe_not_set;
Alternatively, would this shortened expression be correct?
my_object.new_key = param2_maybe_not_set || null;
All four methods work (in the NodeJS console at least). Also jsPerf doesn't show a big gap between any of these (http://jsperf.com/typeof-performance/8)
Which one should be used, as a good practice?
They are not strictly equivalent, but can often be used interchangeably. Here are the major differences between them:
x === undefined: this performs a strict-equality comparison between the value and undefined, meaning that only a actual value of undefined will be true, whereas similar values like null or 0 will be false.
In the case of a function call, this check does not differentiate between f(a) and f(a, undefined) (in fact, none of the examples will; to differentiate, you'll have to look at arguments).
x === void 0: this uses the void keyword, which evaluates any expression and returns undefined. This was mostly done in the olden days to prevent surprises from people redefining the global undefined variable, but is not so useful nowadays (ECMAScript 5 mandates that undefined be read-only)
typeof x === 'undefined': this uses the typeof keyword, which has a unique ability - namely, that the operand is unevaluated. This means that something like typeof foobarbaz returns 'undefined' even if no such variable foobarbaz exists at all. Contrast this with foobarbaz === undefined, which will throw a ReferenceError if the variable name has never been declared.
x || null: this is the simplest and probably most readable alternative. The || operator is often used to "set defaults" on arguments, and can be chained like x || y || z || null.
In most cases, this is the idiomatic technique used. However, note that || performs implicit conversions, which means that any "falsy" values will trigger the next value (meaning that it can't differentiate between undefined, false, null, 0, '', and NaN). So, if your function expects to receive falsy values as arguments, it may be more prudent to explicitly check for undefined.
The option chosen to be an idiom in Javascript development to force a value for an unspecified argument is actually the last:
my_object.new_key = param2_maybe_not_set || null;
So this one should be preferrable since a lot of Javascript developers will immediately get its purpose.
Best.
Consider the code at the bottom, inside a regular function, that checks if some argument was provided or not, and assigns a default value to a variable named message. If the argument is truthy or an empty string, It is simply converted to a string and is stored in the message variable, otherwise the type of argument will be stored in message.
I know it's possible to shorten if else statements to assign default values to variables, like:
var message = arguments[0] || jQuery.type(arguments[0]);
which if only the arguments[0] is truthy will be stored in message. But how to make an exception for an empty string which is a falsy value, without having to use a long if else statement?
if(arguments[0] || arguments[0] === '')
var message = arguments[0].toString();
else
var message = jQuery.type(arguments[0]);
var message = ((arguments[0] || arguments[0] === '') ? arguments[0].toString() : jQuery.type(arguments[0]));
It sounds like you're looking for a shorthand if/else. If so, you can find the answer to your question here. Basically what you need is a ternary operator.
Excerpt below:
var x = y !== undefined ? y : 1;
How to check if javascript variable exist, empty, array, (array but empty), undefined, object and so on
As mentioned in the title, I need a general overview how to check javascript variables in several cases without returning any error causing the browser to stop processing the pageload.
(now I have several issues in this topic.
For example IE stops with error in case _os is undefined, other browsers doesnt:
var _os = fbuser.orders;
var o =0;
var _ret = false;
for (var i = 0; i < _os.length; i++){
...
Furthermore i also need a guide of the proper using operators like == , ===.
As mentioned in the title, I need a general overview how to check
javascript variables in several cases without returning any error
causing the browser to stop processing the pageload.
To check whether or not variables is there, you can simply use typeof:
if (typeof _os != 'undefined'){
// your code
}
The typeof will also help you avoid var undefined error when checking that way.
Furthermore i also need a guide of the proper using operators like ==
, ===.
Both are equality operators. First one does loose comparison to check for values while latter not only checks value but also type of operands being compared.
Here is an example:
4 == "4" // true
4 === "4" // false because types are different eg number and string
With == javascript does type cohersion automatically. When you are sure about type and value of both operands, always use strict equality operator eg ===.
Generally, using typeof is problematic, you should ONLY use it to check whether or not a variables is present.
Read More at MDN:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof
The typeof operator is very helpful here:
typeof asdf
// "undefined"
Perhaps you want something like this in your case:
// Handle cases where `fbuser.orders` is not an array:
var _os = fbuser.orders || []
[Bounty Edit]
I'm looking for a good explanation when you should set/use null or undefined and where you need to check for it. Basically what are common practices for these two and is really possible to treat them separately in generic maintainable codee?
When can I safely check for === null, safely check for === undefined and when do I need to check for both with == null
When should you use the keyword undefined and when should one use the keyword null
I have various checks in the format of
if (someObj == null) or if (someObj != null) which check for both null and undefined. I would like to change all these to either === undefined or === null but I'm not sure how to guarantee that it will only ever be one of the two but not both.
Where should you use checks for null and where should you use checks for undefined
A concrete example:
var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
for (var i = 0; i < List.length; i++) {
if (List[i] == null) continue;
if (id === List[i].getId()) {
return List[i];
}
}
return null;
}
var deleteObject = function(id) {
var index = getIndex(id) // pretty obvouis function
// List[index] = null; // should I set it to null?
delete List[index]; // should I set it to undefined?
}
This is just one example of where I can use both null or undefined and I don't know which is correct.
Are there any cases where you must check for both null and undefined because you have no choice?
Functions implicitly return undefined. Undefined keys in arrays are undefined. Undefined attributes in objects are undefined.
function foo () {
};
var bar = [];
var baz = {};
//foo() === undefined && bar[100] === undefined && baz.something === undefined
document.getElementById returns null if no elements are found.
var el = document.getElementById("foo");
// el === null || el instanceof HTMLElement
You should never have to check for undefined or null (unless you're aggregating data from both a source that may return null, and a source which may return undefined).
I recommend you avoid null; use undefined.
Some DOM methods return null. All properties of an object that have not been set return undefined when you attempt to access them, including properties of an Array. A function with no return statement implicitly returns undefined.
I would suggest making sure you know exactly what values are possible for the variable or property you're testing and testing for these values explicitly and with confidence. For testing null, use foo === null. For testing for undefined, I would recommend using typeof foo == "undefined" in most situations, because undefined (unlike null) is not a reserved word and is instead a simple property of the global object that may be altered, and also for other reasons I wrote about recently here: variable === undefined vs. typeof variable === "undefined"
The difference between null and undefined is that null is itself a value and has to be assigned. It's not the default. A brand new variable with no value assigned to it is undefined.
var x;
// value undefined - NOT null.
x = null;
// value null - NOT undefined.
I think it's interesting to note that, when Windows was first written, it didn't do a lot of checks for invalid/NULL pointers. Afterall, no programmer would be dumb enough to pass NULL where a valid string was needed. And testing for NULL just makes the code larger and slower.
The result was that many UAEs were due to errors in client programs, but all the heat went to Microsoft. Since then, Microsoft has changed Windows to pretty much check every argument for NULL.
I think the lesson is that, unless you are really sure an argument will always be valid, it's probably worth verifying that it is. Of course, Windows is used by a lot of programmers while your function may only be used by you. So that certainly factors in regarding how likely an invalid argument is.
In languages like C and C++, you can use ASSERTs and I use them ALL the time when using these languages. These are statements that verify certain conditions that you never expect to happen. During debugging, you can test that, in fact, they never do. Then when you do a release build these statements are not included in the compiled code. In some ways, this seems like the best of both worlds to me.
If you call a function with no explicit return then it implicitly returns undefined. So if I have a function that needs to say that it did its task and there is nothing result, e.g. a XMLHTTPRequest that returned nothing when you normally expect that there would be something (like a database call), then I would explicitly return null.
Undefined is different from null when using !== but not when using the weaker != because JavaScript does some implicit casting in this case.
The main difference between null and undefined is that undefined can also mean something which has not been assigned to.
undefined false
(SomeObject.foo) false false
(SomeObject.foo != null) false true
(SomeObject.foo !== null) true true
(SomeObject.foo != false) true false
(SomeObject.foo !== false) true false
This is taken from this weblog
The problem is that you claim to see the difference, but you don't. Take your example. It should really be:
var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
for (var i = 1; i < List.length; i+=2) {
if (id === List[i].getId()) {
return List[i];
}
}
// returns undefined by default
}
Your algorithm is flawed because you check even indexes (even though you know there's nothing there), and you also misuse null as a return value.
These kind of functions should really return undefined because it means: there's no such data
And there you are in the heart of the problem. If you don't fully understand null and undefined and may use them wrongly sometimes, how can you be so sure that others will use it correctly? You can't.
Then there are Host objects with their nasty behavior, if you ask me, you better off checking for both. It doesn't hurt, in fact, it saves you some headaches dealing with third party code, or the aformentioned non-native objects.
Except for these two cases, in your own code, you can do what #bobince said:
Keep undefined as a special value for signalling when other languages might throw an exception instead.
When to set/use them...
Note that a method without a return statement returns undefined, you shouldn't force this as an expected response, if you use it in a method that should always return a value, then it should represent an error state internally.
Use null for an intentional or non-match response.
As for how/when to check...
undefined, null, 0, an empty string, NaN and false will be FALSE via coercion. These are known as "falsy" values... everything else is true.
Your best bet is coercion then testing for valid exception values...
var something; //undefined
something = !!something; //something coerced into a boolean
//true if false, null, NaN or undefined
function isFalsish(value) {
return (!value && value !== "" && value !== 0);
}
//get number or default
function getNumber(val, defaultVal) {
defaultVal = isFalsish(defaultVal) ? 0 : defaultVal;
return (isFalsish(val) || isNaN(val)) ? defaultVal : +val;
}
Numeric testing is the real bugger, since true, false and null can be coerced into a number, and 0 coerces to false.
I would treat them as 2 completely different values, and check for the one you know might occur.
If you're checking to see if something has been given a value yet, check against undefined.
If you're checking to see if the value is 'nothing,' check against 'null'
A slightly contrived example:
Say you have a series of ajax requests, and you're morally opposed to using callbacks so you have a timeout running that checks for their completion.
Your check would look something like this:
if (result !== undefined){
//The ajax requests have completed
doOnCompleteStuff();
if (result !== null){
//There is actually data to process
doSomething(result);
}
}
tldr; They are two different values, undefined means no value has been given, null means a value has been given, but the value is 'nothing'.