Javascript check if undefined doesnt work - javascript

I want to check if a object is defined or not..
content of the Object:
so I'll do:
if (e.model.item.state != "undefined"){
var stateID = e.model.item.state.id;
....
}
else{
}
Then e.model.item.state is undefined but it does enter the if clause and stops here:
var stateID = e.model.item.state.id;
because of undefined..!
I tried also:
!== "undefined"
!=== "undefined"

Better use this to avoid unnecessary undefined error:-
if (e && e.model && e.model.item & e.model.item.state) {
// e.model.item.state is NOT `undefined`, `null`, `false` or `0`
}

In JS, you can check whether a variable is either undefined, null, false or 0 by just simply doing,
if (e.model.item.state) {
// e.model.item.state is NOT `undefined`, `null`, `false` or `0`
}
else {
// e.model.item.state is either `undefined`, `null`, `false` or `0`
}

"undefined" is not the same as undefined. The first one is a string with the word 'undefined' in it, the other is a reserved js term for undefined var.
Doing something == "undefined" is comparing it to a string. You should remove the quotes.

You check for undefined in one of following ways:
var a;
if( a === undefined )
OR
if( typeof a === "undefined" )
"undefined" is not equal to undefined. So, if you compare directly for equality, use it without quotes. If you are using typeof operator, you need to use quotes because typeof always returns a string value.

Related

Why is (null==undefined) true in JavaScript? [duplicate]

How do I check a variable if it's null or undefined and what is the difference between the null and undefined?
What is the difference between == and === (it's hard to search Google for "===" )?
How do I check a variable if it's null or undefined...
Is the variable null:
if (a === null)
// or
if (a == null) // but see note below
...but note the latter will also be true if a is undefined.
Is it undefined:
if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below
...but again, note that the last one is vague; it will also be true if a is null.
Now, despite the above, the usual way to check for those is to use the fact that they're falsey:
if (!a) {
// `a` is falsey, which includes `undefined` and `null`
// (and `""`, and `0`, and `NaN`, and [of course] `false`)
}
This is defined by ToBoolean in the spec.
...and what is the difference between the null and undefined?
They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)
null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference — either a valid one (if it found the DOM element), or null (if it didn't).
Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.
What is the difference between "==" and "==="
The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.
Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).
More in the spec:
Abstract Equality Comparison (==, also called "loose" equality)
Strict Equality Comparison (===)
The difference is subtle.
In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value.
But if you then assign a = null; then a will now be null. In JavaScript null is an object (try typeof null in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined is a value).
Example:
var a;
typeof a; # => "undefined"
a = null;
typeof null; # => "object"
This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:
function doSomething(first, second, optional) {
if (typeof optional === "undefined") {
optional = "three";
}
// do something
}
If you omit the optional parameter doSomething(1, 2) thenoptional will be the "three" string but if you pass doSomething(1, 2, null) then optional will be null.
As for the equal == and strictly equal === comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0" will return true; while 0 === "0" will return false, because a number is not a string.
You may use those operators to check between undefined an null. For example:
null === null # => true
undefined === undefined # => true
undefined === null # => false
undefined == null # => true
The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:
function test(val) {
return val == null;
}
test(null); # => true
test(undefined); # => true
The spec is the place to go for full answers to these questions. Here's a summary:
For a variable x, you can:
check whether it's null by direct comparison using ===. Example: x === null
check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.
The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.
More reading:
Angus Croll's Truth, Equality and JavaScript
Andrea Giammarchi's JavaScript Coercion Demystified
comp.lang.javascript FAQs: JavaScript Type-Conversion
How do I check a variable if it's null or undefined
just check if a variable has a valid value like this :
if(variable)
it will return true if variable does't contain :
null
undefined
0
false
"" (an empty string)
NaN
undefined
It means the variable is not yet intialized .
Example :
var x;
if(x){ //you can check like this
//code.
}
equals(==)
It only check value is equals not datatype .
Example :
var x = true;
var y = new Boolean(true);
x == y ; //returns true
Because it checks only value .
Strict Equals(===)
Checks the value and datatype should be same .
Example :
var x = true;
var y = new Boolean(true);
x===y; //returns false.
Because it checks the datatype x is a primitive type and y is a boolean object .
Ad 1. null is not an identifier for a property of the global object, like undefined can be
let x; // undefined
let y=null; // null
let z=3; // has value
// 'w' // is undeclared
if(!x) console.log('x is null or undefined');
if(!y) console.log('y is null or undefined');
if(!z) console.log('z is null or undefined');
try { if(w) 0 } catch(e) { console.log('w is undeclared') }
// typeof not throw exception for undelared variabels
if(typeof w === 'undefined') console.log('w is undefined');
Ad 2. The === check values and types. The == dont require same types and made implicit conversion before comparison (using .valueOf() and .toString()). Here you have all (src):
if
== (its negation !=)
=== (its negation !==)
If your (logical) check is for a negation (!) and you want to capture both JS null and undefined (as different Browsers will give you different results) you would use the less restrictive comparison:
e.g.:
var ItemID = Item.get_id();
if (ItemID != null)
{
//do stuff
}
This will capture both null and undefined
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
//If data has valid value
alert("data "+data);
}
else
{
//If data has null, blank, undefined, zero etc.
alert("data is "+data);
}
}

Why checking undefined type instead of just value?

I got recently such legacy code:
if (typeof value != "undefined" && value.someOperation()) { }
I understand that its preventing undefined object issue, however isn't simple to do such thing:
if (value && value.someOperation()) { }
Is somewhere in deep javascript a hack or some situation that it would not work at all? There is no possible to get 0 or false instead of that object here. I wonder if I can change the first expression to the second one and I wouldn't break anything.
In this line
if (typeof value != "undefined" && value.someOperation()) { }
typeof value != "undefined" is evaluated to false if and only if value is either null or undefined. However, if the value is either 0 or false then it will evaluate to true, and hence move on to second condition value.someOperation().
There is no possible to get 0 or false instead of that object here.
If the value of value cannot be 0 or false, even then you might want to check value.someOperation before checking value.someOperation() since value.someOperation() it may give following error
TypeError: undefined is not a function
In fact, in both cases you might want to check if value.someOperation first before value.someOperation() i.e.
if (value && value.someOperation && value.someOperation()) { }
or
if (typeof value != "undefined" && value.someOperation && value.someOperation()) { }

How to easily check if undefined in javascript object?

Assuming I have a javascript object "myobject" that just contains an empty object "{}".
I ideally in my code I want to do the following:
if (theobject[keyvar][subkeyvar]) {
// do something
}
The issue now is that because keyvar and subkeyvar do not actually exist within the object, it fails and comains that the properties are undefined. What is the simplest/least lines of code/best way to be able to do have it just "know it is undefined" and continue to execute the //do something or not without crashing?
I dont want to get too carried away with checking like:
if( keyvar in theobject ) {
if(subkeyvar in theobject) {
if.....
}
}
if (typeof theobject[keyvar] !== "undefined" && typeof theobject[keyvar][subkeyvar] !== "undefined") {
// keyvar and subkeyvar defined
}
first we check if keyvar typeof is undefined and then if subkeyvar is undefined and if they are both defined typeof theobject[keyvar] !== "undefined" && typeof theobject[keyvar][subkeyvar] !== "undefined" is true.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
you can try this :
if (theobject[keyvar] && theobject[keyvar][subkeyvar]) {
// do something
}
If they both can possibly be undefined, you have to test one, then the other.
if (theobject[keyvar] && theobject[keyvar][subkeyvar]) {
This will of course fail on a key containing 0 or "" (or several other falsey but not undefined values) so you may want to use typeof on the second test.
Try:
if (theobject[keyvar] !== undefined && theobject[keyvar][subkeyvar] !== undefined) {
// do something
}
Since the && operator is used, the if will not check the second value if the first value is falsey, so you will never get the 'properties are undefined` error
theObject.hasOwnProperty(keyvar) && theObject.hasOwnProperty[keyvar].hasOwnProperty(subkeyvar)

comparing against undefined

Is it unsafe to compare a variable against undefined?
if(foo == undefined)
vs
if(foo == 'undefined')
Is the first example sufficient? Or should it be something like
if('undefined' in window){
//compare against undefined
} else {
//compare against 'undefined'
}
since undefined exists on the window object? Will it exist in all browsers? Or should I simply compare to == 'undefined'? I've found some similar questions on SO, but no answers regarding the existance of the undefined property on the window object.
I think you're getting mixed up between foo == undefined and typeof foo == "undefined".
Both will yield the same result unless the variable undefined has been set to something else in the current scope. In this case, foo == undefined will compare against that, where-as typeof foo == "undefined" will still resolve correctly.
var undefined = 4;
var reallyUndefined;
reallyUndefined == undefined; // false
typeof reallyUndefined == undefined; // true
Whether it's a real world scenario that undefined will ever be set to something else is debatable, and I'd question the validity of the library/ code that does that... Because of this however, it's deemed good practise to always use typeof foo === "undefined".
I'd also be wary about using foo == undefined against foo === undefined (note the triple equals, which does not use type-coercian, compared to == which does).
Using ==, you run the risk of things like null == undefined; // true, where-as null === undefined; // false. This is a good example of why you should always use ===.
tl;dr: typeof foo === "undefined";
I'd suggest you to use typeof instead:
if (typeof foo == "undefined") {
// ...
}
Note, that typeof returns a string, so you should always compare it with string value.
if (foo === undefined)
Is safe
There are several ways to do this, but the easiest I've found is this:
if(foo === undefined){
//do stuff
}
If you have complete control of all the code and you know you won't have to worry about someone mucking about with undefined then it is safe to compare against it.
alert(window.foo === undefined);
On the other hand, if you want to be a bit more paranoid, you can do a typeof check which can't be affect by the outside word
alert(typeof window.foo == 'undefined')
The third option is to have your own, local, undefined variable.
function testme(a, undefined) {
alert(a === undefined); // Will be false.
}
testme(10);

php style function check in javascript

I don't recollect exactly what its called but php checks and exists as soon as it finds one false value in a function, like so :
// php
if(isset(a["hi"]) && isset(a["hi"]["hello"])) {
}
here if a["hi"] is not set, it will not bother to check the next a["hi"]["hello"].
to check something like this in javascript you'd need to nest
// js
if(typeof(a["hi"]) != "undefined") {
if(typeof(a["hi"]["hello"]) != "undefined") {
}
}
Can we do php style lazy checking in javascript?
(I may not be using the best method to check if an element exists in a multi-dimentional array, if there is a succinct way of doing this, would love to know.)
thanks!
You could use in to check property existence.
if(a && ('hi' in a) && ('hello' in a['hi'])) {
}
if(a.hi === undefined && a.hi.hello === undefined) {
if you know that a.hi can never be a falsey value (null / false / 0) you can do
if(!a.hi && !a.hi.hello) {
Checking the typeof a variable for the string "undefined" is equivalent to using === to check whether the variable is the same data type as the undefined keyword. You can therefore reduce the nested if statements to a single statement:
if(a.hi !== undefined && a.hi.hello !== undefined) {
// do something with a.hi.hello
}
It's worth noting that the statement above assumes that a is not null when the if statement takes place which could cause errors. It also holds true that if you require a.hi.hello to be present for the if statement to evaluate, then you can use falsy checking for a and a.hi as they would need to be object types for (which are non-falsy):
if(!!a && a.hi && a.hi.hello !== undefined) {
// do something with a.hi.hello
}

Categories

Resources