Is the same anonimous variable calculated twice

35 Views Asked by At

I have an imaginary code in Javascript like this

let z = 99999;
if (str.lastIndexOf('_') !== -1)
  z = str.lastIndexOf('_');     
}

Will be this snip of code: str.lastIndexOf('_') be calculated twice?
Or in this cause: z = str.lastIndexOf('_') !== -1 ? str.lastIndexOf('_') !== -1 : 99999;

If this will be calculated twice is it mean that the best way is to put str.lastIndexOf('_') into a separate variable and use it in conditions?

I want to know that a deliberate ignoring of execution mode could be justified by lexical purpose.

1

There are 1 best solutions below

0
Konrad On

We can test that by overwriting lastIndexOf

const orig = String.prototype.lastIndexOf
String.prototype.lastIndexOf = function(...args) {
  console.log('running lastIndexOf')
  orig.call(this, ...args);
}

const str = '31231231231312_1312312'
let z = 99999;
if (str.lastIndexOf('_') !== -1) {
  z = str.lastIndexOf('_');     
}

As you can see, it prints 2 times