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
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);
These statements are logically equivalent.
That being said, and as mentioned in another answer, if a.b
has side effects, the statements will not result in the same program state.
This could be readily obvious in the form of var c
having a different value depending on which of these statements are executed, or more hidden, if a.b
modifies something elsewhere in the program.
Refactoring
As refactoring has been discussed, I'll touch on it briefly. As the above has hopefully made obvious, directly refactoring would not be safe in all scenarios. However, I would still recommend a refactor of one kind or another.
The two possible situations as I see them are:
-
a.b
has no side effects, direct refactoring is safe -
a.b
has hidden side effects. This represents very unclear, confusing, and just downright bad code. It should be refactored so that all changes happening during the statement are clear and obvious to a reader (hopefully intuitively so, as well as supported by comments).