Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to check for null inline in javascript?

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 ?

like image 763
darkermuffin Avatar asked Jan 19 '18 13:01

darkermuffin


People also ask

How do you check if something is null in JavaScript?

JavaScript uses the null value to represent a missing object. Use the strict equality operator ( === ) to check if a value is null . The typeof null returns 'object' , which is historical bug in JavaScript that may never be fixed.

IS null == null in JavaScript?

Summary. null is a special value in JavaScript that represents a missing object. The strict equality operator determines whether a variable is null: variable === null .

Can we compare null in JavaScript?

Comparing Equality of Null and Undefined Values Null and undefined values are equal when compared using the JavaScript equality operator. Use the equality operator (==) to compare if null and undefined values are equal in JavaScript.

How to check for null in JavaScript?

While checking for an object in a JavaScript code, you may require a check for a null. Three methods can help you check for null in JavaScript. triple equality operator/ strict equality operator (=== or !==) the double equality operator or loose equality operator (== or !=). This operator can check for null and undefined at the same time.

How to check if a JavaScript variable is null or undefined?

However, if you want to check for null values, the Object.is () behaves similar to the triple equality operator (===). The use JavaScript Object.is () method can be explicitly used to cheche whether a variable is null or undefined. The Object.is () works similarly to the strict equality operator when comparing null and undefined.

How to check if a variable is null or empty?

A nother method of checking for null is based on the fact that null is falsy, but empty objects are truthy, so null is the only falsy object. This can be conveniently checked using the logical NOT ! operator: Using typeof can be a helpful trick, because if a variable is undeclared, then trying to reference it will throw a ReferenceError.

Is null a falsy value in JavaScript?

“ null is a falsy value (i.e. it evaluates to false if coerced to a boolean)” — Josh Clanton at A Drip of JavaScript T he simplest way to check for null is to know that null evaluates to false in conditionals or if coerced to a boolean value: Of course, that does not differentiate null from the other falsy values.


4 Answers

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 - 92%, Dec 2021

?? Browser Support - 92%

Node Support - v14+

like image 110
Gibolt Avatar answered Oct 19 '22 17:10

Gibolt


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.

like image 34
Pac0 Avatar answered Oct 19 '22 17:10

Pac0


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

return num || 0;

As of today more correct semantically;

return num ?? 0

like image 10
ilkerkaran Avatar answered Oct 19 '22 15:10

ilkerkaran


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

like image 4
zabusa Avatar answered Oct 19 '22 15:10

zabusa