Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these lines of JavaScript code equivalent?

I've found this string in JavaScript code.

var c = (a.b !== null) ? a.b : null; 

This is a shorthand of an if-else statement, however the value null is assigned if it is null. Isn't that ALWAYS equivalent to

var c = a.b 

including all cases - exceptions, null, undefined, etc?

In another words, are these lines (always) equivalent?

var c = (a.b !== null) ? a.b : null; 

-vs-

var c = a.b 
like image 962
Haradzieniec Avatar asked Aug 11 '15 10:08

Haradzieniec


People also ask

What is the result of the given statement in JavaScript 1 undefined 1?

Now Undefined X 1 in JavaScript yields NaN(Not a Number) as result.


1 Answers

No, they AREN'T NECESSARILY EQUAL always if b is a getter that updates a variable. It's bad practice to code this way though

var log = 0; var a = {     get b() {         log++;         return log;     } }  var c = (a.b !== null) ? a.b : null; // outputs 2 console.log(c); 
var log = 0; var a = {     get b() {         log++;         return log;     } }  var c = a.b; // outputs 1 console.log(c); 
like image 135
potatopeelings Avatar answered Sep 22 '22 23:09

potatopeelings