-1

var myVar = null;
console.log(myVar.test)

The above code returns this error: Uncaught TypeError: Cannot read property 'test' of null. How can I just get it to return null without any errors?

I could use a try/catch or an if statement to first check myVar, but is there a simpler way?

nachshon f
  • 3,540
  • 7
  • 35
  • 67

1 Answers1

1
console.log(myvar ? myvar.test : 'myvar is null')

You can use an inline ternary operation to check if it's null.

If it's not null, test is printed. If it is, "myvar is null" is printed. This has the advantage over myvar && myvar.test of allowing you to determine the output if myvar is null.

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
  • Thanks! Just what I'm looking for. – nachshon f Aug 13 '19 at 17:21
  • 1
    @3limin4t0r That also wouldn't work if `myVar.test === 0` or any other falsey value (at least, it would evaluate to "myvar is null" for `myVar = {test:0}`). – Paul Aug 13 '19 at 17:27
  • I can confirm that ```myvar={test:0};``` and ```console.log(myvar && myvar.test || 'myvar is null')``` prints ```'myvar is null'```. – Michael Bianconi Aug 13 '19 at 17:35