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.

Answer from T.J. Crowder on Stack Overflow
Top answer
1 of 3
24

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.

2 of 3
9
   state = (typeof state !== "undefined") ? state : '';

This way you can check undefined variable in a ternary operator.

🌐
GoLinuxCloud
golinuxcloud.com › home › javascript › how to check if undefined in javascript? [solved]
How to check if undefined in JavaScript? [SOLVED] | GoLinuxCloud
January 1, 2024 - There are different ways to check if a variable is undefined in JavaScript, including using the typeof operator, the comparison operator (===) with the value undefined, or the use of the ternary operator.
🌐
Reddit
reddit.com › r/learnjavascript › is it bad practice to use ternary with undefined or null?
r/learnjavascript on Reddit: Is it bad practice to use ternary with undefined or null?
September 28, 2023 -

For example, I have a game of snake in which each time the snake moves I check if it has eaten an apple, a powerup or itself. I could use multiple if statements, ie:

if(snakeAteSelf) {
    callFunction1
} 
if(snakeAtePowerUp) {
    callFunction2
}
if(snakeAteApple) {
    callfunction3
}

But instead I'm doing something more similar to

snakeAteSelf ? callFunction1 : null
snakeAtePowerup ? callFunction2 : null
snakeAteApple ? callFunction3 : null

But the null just stands out as odd looking to me, despite the rest of the code looking more concise.

EDIT: If anyone is interested in critiquing my game of snake you can play it here (press arrow keys to start, you wrap around edges so don't worry about hitting them) and view the code here.

🌐
Sololearn
sololearn.com › en › Discuss › 3050623 › solved-ternary-statement-returns-undefined
[SOLVED] ternary statement returns undefined? | Sololearn: Learn to code for FREE!
I don't know if the problem falls here: (userSelection !== "rock" || userSelection !== "paper" || userSelection !== "scissor")? userSelectionWrong(): (userSelection === "")? userSelectionWrong() : "Something Happen, Error"; alert(result); please check the code, to see the problem, many thanks ... Jonathan P. Jundarino ... This will always be true: (userSelection !== "rock" || userSelection !== "paper" || userSelection !== "scissor") Rethink the logic of this part. Do you fully understand "||" (OR) operator?
🌐
RunJS
runjs.app › blog › using-the-ternary-operator-in-javascript
Using the Ternary Operator in JavaScript
October 14, 2022 - If you tried to access a property on a variable that hadn't been defined, you would encounter the following error: TypeError: Cannot read properties of undefined. Ternary operators can be nested to check multiple conditions, similar to an if...else if...else statement.
Top answer
1 of 8
141

2020 Answer, It Exists!!!

You can now directly use ?. inline to test for existence. It is called the Optional Chaining Operator, supported by all modern browsers.

If a property exists, it proceeds to the next check, or returns the value. Any failure will immediately short-circuit and return undefined.

const example = {a: ["first", {b:3}, false]}

example?.a  // ["first", {b:3}, false]
example?.b  // undefined

example?.a?.[0]     // "first"
example?.a?.[1]?.a  // undefined
example?.a?.[1]?.b  // 3

domElement?.parentElement?.children?.[3]?.nextElementSibling

To ensure a default defined value, you can use ??. If you require the first truthy value, you can use ||.

example?.c ?? "c"  // "c"
example?.c || "c"  // "c"

example?.a?.[2] ?? 2  // false
example?.a?.[2] || 2  // 2

If you do not check a case, the left-side property must exist. If not, it will throw an exception.

example?.First         // undefined
example?.First.Second  // Uncaught TypeError: Cannot read property 'Second' of undefined

?. Browser Support - 94%, Oct '22

?? Browser Support - 94%

Node Support - v14+

2 of 8
32

Update 2020

This long-wished feature is now available in JavaScript!

I'll redirect to Gibolt's answer, which covers it well.

Original 2018 answer

  • There is no "null-safe navigation operator" in Javascript (EcmaScript 5 or 6), like ?. in C#, Angular templates, etc. (also sometimes called Elvis operator, when written ?:) , at least yet, unfortunately.

  • You can test for null and return some dependent expression in a single line with the ternary operator ?:, as already given in other answers :

(use === null to check only for nulls values, and == null to check for null and undefined)

    console.log(myVar == null ? myVar.myProp : 'fallBackValue');
  • in some cases, like yours, when your variable is supposed to hold an object, you can simply use the fact that any object is truthy whereas null and undefined are falsy values :

      if (myVar) 
          console.log(myVar.myProp)
      else
          console.log('fallbackValue')
    

    You can test for falsy values by coalescing to boolean with !! and make this inline :

      console.log(!!myVar ? myVar.myProp : 'fallbackValue');
    

    Be very careful though with this "falsy test", for if your variable is 0, '', or NaN, then it is falsy as well, even though it is not null/undefined.

Top answer
1 of 3
26

Let's do some fixing. First, this is how you pass optional (non-boolean) parameters in JS (the Good Waytm):

addFooListeners = function (panelType, handlers) {
    handlers        = handlers        || {};
    handlers.show   = handlers.show   || showFoo;
    handlers.hide   = handlers.hide   || hideFoo;
    handlers.commit = handlers.commit || commitFoo;

The above can be rewritten in a neater way using jQuery (not sure what the name of YUI equivalent to extend is):

handlers = $.extend({
    show  : showFoo, 
    hide  : hideFoo, 
    commit: commitFoo
}, handlers || {})

Now, using eval for this code is criminal. Say the object ns refers to is module, then you can do this instead of eval:

YAHOO.util.Event.addListener("show" + panelType, "click", handlers.show, module["panel_" + panelType], true);
YAHOO.util.Event.addListener("hide" + panelType, "click", handlers.hide, module["panel_" + panelType], true);
YAHOO.util.Event.addListener("commit" + panelType, "click", handlers.commit, module["panel_" + panelType], true);

Now, as you can see, you are assigning a lot of events in a similar fashion. Did you think of defining an addPanelListener function within your function?

function addPanelListener (event, panelType, handler) {
    YAHOO.util.Event.addListener(event + panelType, "click", handler, module["panel_" + panelType], true);
} 

addPanelListener("show"  , panelType, handlers.show);
addPanelListener("hide"  , panelType, handlers.hide);
addPanelListener("commit", panelType, handlers.commit):

Hope it helps.

2 of 3
7

It looks like you can reduce that ternary a bit by using && like this:

var handlers = {
    show:  ( overrides != null && overrides.show != null ? overrides.show : showFoo ),
    hide:  ( overrides != null && overrides.hide != null ? overrides.hide : hideFoo ),
    commit: ( overrides != null && overrides.commit != null ? overrides.commit : commitFoo )
}

I'm not too familiar with javascript but does the function parameter have to be checked against null? Like for example, can you further shorten the check by doing something like this?

show:  ( overrides && overrides.show ? overrides.show : showFoo ),
hide:  ( overrides && overrides.hide ? overrides.hide : hideFoo ),
// ...
🌐
Medium
medium.com › @dimplekollipara261 › simplify-your-javascript-code-with-ternary-and-nullish-coalescing-operators-57aaf765b416
Simplify Your JavaScript Code with Ternary(?) and Nullish Coalescing(??) Operators | by Dimple Kollipara | Medium
August 4, 2023 - The Nullish Coalescing Operator (??) is an operator introduced in ES2020 that offers a practical solution for setting default values when encountering “null” or “undefined” values in JavaScript. It differs from the logical OR operator (||) as it specifically checks for null or undefined, rather than falsy values like empty strings, 0, NaN, or false.
Find elsewhere
🌐
SitePoint
sitepoint.com › blog › javascript › quick tip: how to use the ternary operator in javascript
Quick Tip: How to Use the Ternary Operator in JavaScript — SitePoint
November 6, 2024 - Using the ternary operator, you can check that a variable is not null or undefined just by passing the variable name in the position of the condition operand.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
0; console.log(valA); // "default for A" console.log(valB); // "" (as the empty string is not null or undefined) console.log(valC); // 42 · Earlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator (||):
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Conditional_operator
Conditional (ternary) operator - JavaScript | MDN
Besides false, possible falsy expressions are: null, NaN, 0, the empty string (""), and undefined. If condition is any of these, the result of the conditional expression will be the result of executing the expression exprIfFalse. ... const greeting = (person) => { const name = person ? person.name : "stranger"; return `Howdy, ${name}`; }; console.log(greeting({ name: "Alice" })); // "Howdy, Alice" console.log(greeting(null)); // "Howdy, stranger" The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if …
🌐
GitConnected
levelup.gitconnected.com › using-the-ternary-operator-and-nullish-coalescing-b315237770fa
Using The Ternary Operator And Nullish Coalescing | by Alex Pickering | Level Up Coding
February 13, 2020 - So how does nullish coelescing differ from a normal ternary operator? Well the fundamental difference is that it will check to determine if a value is present. If the value is present, i.e. is not null or undefined then the value will be returned. If the value does not exist, the ‘fallback’ will be returned instead.
🌐
Scaler
scaler.com › topics › javascript › ternary-operator-javascript
JavaScript Ternary Operator - Scaler Topics
January 21, 2022 - So the value of the variable "name", remains undefined. This results in a false condition. Thus returning the expression_if_false statement, which is "No argument was passed". In this example we will explain about Ternary Chaining. Just like if - else if....else if - else chain, we can also chain Ternary Operator in Javascript. ... Here, we write another ternary statement in the place of "expression_if_false". We can add as many ternary operators as needed. ... Suppose you want to check ...
🌐
Refine
refine.dev › blog › javascript-ternary-operator
How to Use the JavaScript Ternary Operator | Refine
October 8, 2024 - For example, if we want to check if a value exists before performing an action, we can use a ternary operator to handle errors or defaults: const data = response ? response.data : 'No data available'; It’s a simple way to avoid undefined errors or fallback to default values when something goes wrong.
🌐
Stack Overflow
stackoverflow.com › questions › 72497351 › ternary-operator-when-variable-is-undefined
javascript - Ternary operator - when variable is undefined - Stack Overflow
const linkedinInsight = (backgroundPage && backgroundPage["_linkedin_pixel_data"] && backgroundPage["_linkedin_pixel_data"][tab.id] && backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags) || undefined; ... function check(X) { let present = X ?? `"X" does not exist`; let limit = X < 10 && X > 0 ?