Are these lines of JavaScript code equivalent? Are these lines of JavaScript code equivalent? javascript javascript

Are these lines of JavaScript code equivalent?


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 2console.log(c);
var log = 0;var a = {    get b() {        log++;        return log;    }}var c = a.b;// outputs 1console.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:

  1. a.b has no side effects, direct refactoring is safe
  2. a.b has hidden side effects. This represents very unclear, confusing,and just downright bad code. It should be refactored so that allchanges happening during the statement are clear and obvious to areader (hopefully intuitively so, as well as supported by comments).


As @potatopeelings already pointed out, the two possible statements are not always equivalent, since one can write obscure code, which will have different results.

However, if I see a code, like

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

I will assume that the code's intention is

var c = a.b;

so I will change it to make the code prettier. If I will be negatively surprised, that is, the code does not pass the testing phases due to this change, then I will try to find the author of a.b with git blame.

So, my answer is, that the two statements are not equivalent, but should be equivalent in well-written code.