Is it possible to check for null inline in javascript?
Asked Answered
I

8

74

I have a function which parses the address components of the Google Maps API JSON and then returns the city / locality / route name.

The getAddressComponent() returns a null if it cannot find the key.

let route = getAddressComponent(addressComponents, 'route').value.long_name;

So let's say it didn't find the key, then I get a Error: TypeError: Cannot read property 'long_name' of undefined obviously because it's not defined.

How do I check for null in javascript other than the conditional method (a === null)?

How can I simply check like this with ?

EDIT : Safe Navigation Operator

let route = getAddressComponent(addressComponents, 'route')?.value.long_name;

And if it doesn't exists, it could probably set route to null instead of throwing a Error ?

Increscent answered 19/1, 2018 at 13:8 Comment(6)
Possible duplicate of JavaScript check if value is only undefined, null or falseUlund
Is getAddressComponent async or not?Highpressure
Do you mean (element != null ? element.value.long_name : null)?Hippel
@Highpressure No it is notIncrescent
@Hippel No, I meant if I could somehow do something like this tc39.github.io/proposal-optional-chainingIncrescent
@JennyO'Reilly Sorry, It returns nullIncrescent
P
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+

Pro answered 9/7, 2020 at 21:23 Comment(1)
Sadly you cannot do ?? throw new Error("...").Lahdidah
I
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.

Implication answered 19/1, 2018 at 13:36 Comment(0)
O
10

Code below simplified return num ? num : 0 for me:

return num || 0;

As of today more correct semantically;

return num ?? 0

Oran answered 9/10, 2019 at 12:56 Comment(2)
What are you trying to accomplish? Assuming num is of type int, then return num || 0 is equivalent to return num ...Bucolic
the question tags are javascript and null. I wouldn't assume it is int :)Oran
F
4
let component = getAddressComponent(addressComponents, 'route');
let route = component ? component : null

you can use the ? operator to check the value is true or false then set the value in javascript null will be false

Fauces answered 19/1, 2018 at 13:12 Comment(0)
A
3

What you want is a null coalescent operator. Javascript doesn't have one. Most of the time peoples use the logical OR || for this purpose but it doesn't work on property access.

There's proposal for adding null coalescing to the language, but it's nowhere near: https://github.com/tc39/proposal-nullish-coalescing
https://tc39.github.io/proposal-nullish-coalescing/

If you really, really, absolutly want to use it you can use this Babel plugin: https://www.npmjs.com/package/babel-plugin-transform-optional-chaining
But I would strongly suggest you don't: this may never make it to the language and you would have unvalid code in your codebase.

Adventuresome answered 19/1, 2018 at 13:14 Comment(0)
P
3

For empty strings you can use !:

var foo = 'yo';
console.log(!foo);

var foo = null;
console.log(!foo);

And for the ? you asked about, it's the Conditional (ternary) Operator, the syntax is condition ? if true : if false you can use it as follows:

var foo = 'yo';
console.log('1 : ' + (!foo ? 'Null' : 'Not Null'));
console.log('2 : ' + (foo === null ? 'Null' : 'Not Null'));
console.log('3 : ' + (foo == null ? 'Null' : 'Not Null'));

var foo = null;
console.log('1 : ' + (!foo ? 'Null' : 'Not Null'));
console.log('2 : ' + (foo === null ? 'Null' : 'Not Null'));
console.log('3 : ' + (foo == null ? 'Null' : 'Not Null'));
Prudhoe answered 19/1, 2018 at 13:15 Comment(1)
Note that "empty string" is not the same as "null value", but they are both falsy when coerced to Boolean (like when you apply !, or in a if). var foobar = ''; console.log((!foobar ? 'falsy like null' : 'not falsy')); console.log((foobar === null ? '===Null' : '!==Null')); console.log((foobar == null ? '==Null' : '!=Null')); .Implication
D
0

.? cannot be used in javascript, for that, you might look into typescript.

For example, you can use try...catch construction:

let route

try {
  route = getAddressComponent(addressComponents, 'route').value.long_name
} catch (error) {
  route = null
}
Divorcement answered 19/1, 2018 at 13:15 Comment(0)
P
0

As an answer to jeroen:

You can not ?? throw new Error("..."). But you can do:

const throwError = (missingParam) => { throw new Error(`Parameter ${missingParam} is missing`); };

{
    someParam: a.anotherParam ?? throwError('anotherParam')
}
Precursor answered 9/11, 2022 at 16:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.