JavaScript || or Operator with an Undefined Variable

JavaScript || or operator with an undefined variable

That Opera article gives a poor description of what is happening.

While it is true that x will get the value of 10 if v is undefined. It is also true that x will be 10 if v has any "falsey" value.

The "falsey" values in javascript are:

  • 0
  • null
  • undefined
  • NaN
  • "" (empty string)
  • false

So you can see that there are many cases in which x will be set to 10 besides just undefined.

Here's some documentation detailing the logical operators. (This one is the "logical OR".) It gives several examples of its usage for such an assignment.

Quick example: http://jsfiddle.net/V76W6/

var v = 0;

var x = v || 10;

alert( x ); // alerts 10

Assign v any of the falsey values that I indicated above, and you'll get the same result.

How to check for an undefined or null variable in JavaScript?

You have to differentiate between cases:

  1. Variables can be undefined or undeclared. You'll get an error if you access an undeclared variable in any context other than typeof.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error

A variable that has been declared but not initialized is undefined.

let foo;
if (foo) //evaluates to false because foo === undefined

  1. Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about
    0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact:

    value = obj.prop || defaultValue

    which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue".

    Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead

    value = ('prop' in obj) ? obj.prop : defaultValue

How can I check for undefined in JavaScript?

If you are interested in finding out whether a variable has been declared regardless of its value, then using the in operator is the safest way to go. Consider this example:

// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"

But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in operator for a more robust check.

"theFu" in window; // true
"theFoo" in window; // false

If you are interested in knowing whether the variable hasn't been declared or has the value undefined, then use the typeof operator, which is guaranteed to return a string:

if (typeof myVar !== 'undefined')

Direct comparisons against undefined are troublesome as undefined can be overwritten.

window.undefined = "foo";
"foo" == undefined // true

As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.

if (window.myVar) will also include these falsy values, so it's not very robust:


false
0
""
NaN
null
undefined

Thanks to @CMS for pointing out that your third case - if (myVariable) can also throw an error in two cases. The first is when the variable hasn't been defined which throws a ReferenceError.

// abc was never declared.
if (abc) {
// ReferenceError: abc is not defined
}

The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,

// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", {
get: function() { throw new Error("W00t?"); },
set: undefined
});
if (myVariable) {
// Error: W00t?
}

Ternary operator - when variable is undefined

The issue is in below line, replace

const linkedinInsight =
backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags;

with

const linkedinInsight =
(backgroundPage && backgroundPage["_linkedin_pixel_data"] && backgroundPage["_linkedin_pixel_data"][tab.id] && backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags) || undefined;

Or if optional chaining is supported

const linkedinInsight =
backgroundPage?.["_linkedin_pixel_data"]?.[tab.id]?.insight_tags;

How to check undefined variable in a ternary operator?

while b and c throw ReferenceError when abc is undefined

So abc isn't just undefined, it's undeclared. There's a big difference there.

If you need to handle abc being undeclared, the only safe way to do that (without try/catch) is with typeof:

typeof abc === "undefined"

That will be true, without error, if abc is an undeclared identifier. It will also be true if abc is declared and contains the value undefined.

What is the best and short way to check if abc is undefined before accessing its properties as well as assign blank object {} if undefined?

Probably using var to ensure it's declared:

var abc = abc || {};

Duplicate var declarations are not errors (duplicate let declarations are). So with the above, if abc is undeclared, it gets declared with the initial value undefined and we assign it {}. If it's declared, we replace its value with {} if it's falsy. But, if it may or may not be declared with let or const, then the above will throw an error as well.

So to handle the case where it may or may not be declared with let or const, we need a different variable entirely:

let ourabc = typeof abc === "undefined" || !abc ? {} : abc;

That sets ourabc to {} if abc is undeclared or if it contains a falsy value. Since all non-null object references are truthy, and you've said you want to access object properties, that's probably the shortest way.

Javascript: use either a variable, or if it's undefined, a default string

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).

JavaScript OR (||) variable assignment explanation

See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.

Which is the better way to check undefined in Javascript?

There are various use case as following

  1. if (variable) is standard way to check truthiness of any variable in javascript. You can examples of what values will be truthy on Truthy | MDN Web Docs. Also, Falsy | MDN Docs

  2. The cases where you explicitly would check for undefined is when a variable has been declared but not assigned value or explicitly assigned undefined.
    In that case use if (variable !== undefined).

  3. If you are receiving response from an API which might consist of stringified value of undefined, which you are sure of, then only do the check if (variable !== 'undefined')

What it means if variable value contains OR (||) operator

This is assigning colorCollection to its own value if it already exists, otherwise it will assign it an empty object.

It works like this - in javascript, any variable is "truthy", meaning that you can say something like this:

if (colorCollection) {
// some code
}

If colorCollection has a value (ie. it isn't undefined, null, NaN, 0, "", or false), the if statement will be true, and the code in // some code will run. The || operator will return the first value if it's truthy, otherwise it will return the last value. That's why this works.

How can I determine if a variable is 'undefined' or 'null'?

You can use the qualities of the abstract equality operator to do this:

if (variable == null){
// your code here.
}

Because null == undefined is true, the above code will catch both null and undefined.



Related Topics



Leave a reply



Submit