A question about "undefined" in Javascript - javascript

Today one of my friends said:
if (typeof isoft == "undefined") var isoft = new Object();
is such kind of code is writted by a freshman and writes
if(!isoft) var isoft = new Object();
I originally consider there must be some difference. But I can't find the difference. Is
there any? Or are the two examples the same?
Thanks.

See the question Javascript, check to see if a variable is an object but note that the accepted answer by Tom Ritter appears to be incomplete, check the comment on his answer. See also the community answer by Rob.

In the example involving regular objects that you provided there is little difference. However, another typical pattern can be:
var radioButtons = document.forms['formName'].elements['radioButtonName'];
if ('undefined' === typeof radioButtons.length) {
radioButtons = [ radioButtons ];
}
for (var i = 0; i < radioButtons.length; i++) {
// ...
}
If you used if (!radioButtons.length) it would evaluate true when no radio buttons were found (radioButtons.length is 0) and create an array of a single (non-existent) radio button. The same problem can arise if you choose to handle the radio buttons using:
if ('undefined' === typeof radioButtons.length) {
// there is only one
} else {
// there are many or none
}
There are other examples involving empty strings where if (!variable) is probably not recommended and it is better to test against typeof undefined or explicitly test against null.

If isoft should hold a reference to an object, both do the same. A !isoft is true for all false values, but a object can't be a false value.

In your particular example there's no significant difference, since you're evaluating Object instance, and objects are converted to Boolean true when cast to Boolean, while undefined and null are evaluated as Boolean false.
But take this for an example:
function alertSomething(something) {
//say you wanna show alert only if something is defined.
//but you do not know if something is going to be an object or
//a string or a number, so you cannot just do
//if (!something) return;
//you have to check if something is defined
if (typeof something=='undefined') return;
alert(something);
}
I like to take shortcuts and save typing wherever I can, sure, but you have to know when to take a shortcuts, and when not to ;)

Related

Javascript: var1 == true && (var2 = true)

I see in the code I am working on often the following code style;
var1 == true && (var2 = true)
After some testing I figured it comes down to:
if (var1 == true) {
var2 = true;
}
Is this correct, or is there more to it? And why would anyone use this since the readability just dramatically reduces, since your assume at first glance it is just a check on two variables. So you really have to start looking at single or double equal sings and where the parentheses are, which just kinda, you know.. Just curious here..
Yes, this is equivalent. As far as I know, it is called short-circuit evaluation, describing the fact that the interpreter will return false for the whole boolean expression as soon as one of its parts is falsy.
Indeed, in your example it DOES reduce readability. But I think of it as just another tool in your toolbox you may use when you feel it could be useful. Consider the following:
return user && user.name;
This is one example when I tend to use it. In this case, I think it's actually more readable than
if (user) {
return user.name;
} else {
return undefined; // or null or something alike
}
UPDATE
I want to give you another example when I consider this kinds of constructs useful. Think of ES6 arrow functions like user => user.name. It does not need {} to open a body since it just has one line. If you wish to log something to the console (for debugging), you would end up having
user => {
console.log(user); // or something alike
return user.name;
}
You might as well use the shorter variant
user => console.log(user) || user.name
since console.log returns undefined after logging into the console, hence user.name is returned.
Yes, as you've mentioned there's more to it.
the first part var1 == true checks whether ther result is true or false.
if the condition is false the code after it doesn't get checked or evaluated and thus var2 doesn't get set to true.
But if the first part of the condition var1 == true is true which obviously is true, the second part of the conditional statement the part after && is checked.
now the second part of the condition is an operation it sets (var2 = true) which is kind of a truthy operation.
we could edit your code a little bit to help you understand the operation more clearly:
if( var1 === true && (var2 = true)){console.log('good');}
I hope this helps

Trouble understanding if statement code

I am going through a book about HTML5 and there are two lines of code I cannot quite understand
var mp3Support,oggSupport;
var audio = document.createElement('audio');
if(audio.canPlayType) {
mp3Support = "" != audio.canPlayType('audio/mp3');
}
So, first you create an audio element and check if canPlayType method can be used?
Then, the code inside the if statement is some kind of ternary operation?
The audio.canPlayType('audio/mp3') outputs 'probably' and mp3Support is set to '' but after that line mp3Support outputs true. Any tips would be much appreciated.
So, first you create an audio element
Yes
and check if canPlayType method can be used?
The check is to see if canPlayType is a true value, but that amounts to the same thing in practical terms.
Then, the code inside the if statement is some kind of ternary operation?
No.
audio.canPlayType('audio/mp3') can return a number of values, one of which is an empty string.
"" != audio.canPlayType('audio/mp3'); tests to see if it not an empty string (and evaluates as true or false)
mp3Support = then is just assigned that true or false
It could be more clearly written as:
mp3Support = ("" != audio.canPlayType('audio/mp3'));
mp3Support = "" != audio.canPlayType('audio/mp3');
This combines a variable initialization with boolean expression.
in other way:
if(audio.canPlayType('audio/mp3')!="")
{
mp3Support=true;
}
else
{
mp3Support=false;
}

How to check if javascript variable exist, empty, array, (array but empty), undefined, object and so on

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 || []

When to check for undefined and when to check for null

[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'.

How important is checking for bad parameters when unit testing?

Let's say I've got a method that takes some arguments and stores them as instance variables. If one of them is null, some code later on is going to crash. Would you modify the method to throw an exception if null arguments are provided and add unit tests to check that or not? If I do, it's slightly more complicated since javascript has many bad values (null, undefined, NaN, etc.) and since it has dynamic typing, I can't even check if the right kind of object was passed in.
I think it really depends on what sort of API you're unit testing. If this is a component designed and built for internal use only, and you know usage will be under certain constraints, it can be overkill to unit test for bad parameters. On the other hand, if you're talking about something for distribution externally, or which is used in a wide variety of situations, some of which are hard to predict, yes, checking for bad parameters is appropriate. It all depends on usage.
I think you really have 2 different questions here.
The first is what is the best practice for parameter input validation and the second is should your unit test handle test for these situations.
I would recommend that you either throw an Argument Exception for the parameter that was not supplied correctly to your function or some other variable/message that informs the calling function/user of the situation. Normally, you do not want to throw exceptions and should try to prevent the functions from even being called when you know they will fail.
For your unit test, you should definitely include NULL value tests to make sure a graceful result occurs.
JavaScript has instanceof and typeof that can help you check what kind of objects are being passed to your functions:
'undefined' == typeof noVariable; // true
var noVariable = null;
'undefined' == typeof noVariable; // false
typeof noVariable; // 'object'
noVariable === null; // true
var myArray = [];
typeof myArray; // 'object'
myArray instanceof Object; // true
myArray instanceof Array; // true
var myObject = {};
typeof myObject; // 'object'
myObject instanceof Object; // true
myObject instanceof Array; // false
You can use these to set some default "bad" values for your instance variables:
function myFunction(foo,bar) {
foo = foo instanceof Array ? foo : []; // If 'foo' is not an array, make it an empty one
bar = bar instanceof Number ? bar : 0;
// This loop should always exit without error, although it may never do a single iteration
for (var i=0; i<foo.length; i++) {
console.log(foo[i]);
}
// Should never fail
bar++;
}
The or operator is also very useful:
function myFunction(blat) {
var blat = blat||null; // If 'blat' is 0, '', undefined, NaN, or null, force it to be null
// You can be sure that 'blat' will be at least *some* kind of object inside this block
if (null!==blat) {
}
}
Also, don't forget that with JavaScript you can pass in fewer than or more than the expected number of parameters. You can check that too, if you like.
For creating robust and secure code, checking the edge cases is definitely important task. Positive and negative testing is always good for the quality. The lack of negative tests might bite you in the long run.
So I'd say it is better play it safe - do both. It's a bit more work, but if you can afford the time, then it'll be worth it. Taking the developer hat off and putting on the cracker hat can be very interesting sometimes.

Categories