Should I declare a variable or access object method?

  • A+

Which is the better option and why?

Declare a variable:

exampleFunction(requestData: Object) {   const username = requestData.username;    doSomething(username); } 

Or access the object property directly?

exampleFunction(requestData: Object) {   doSomething(requestData.username); } 

What if the code I use is over 50 lines long and the variable is used multiple times. Should I use the variable 'username' multiple times or use 'requestData.username' multiple times?


V8 Javascript Engine performs some optimization pre-processing the code and checking if some variable can be deleted or if there's some regular pattern in the code, in order to reduce the execution payload.

For this reason, there are no memory issues in using a form or another, at least using V8 engine (for example, Chrome or NodeJS).

Even if this optimization isn't performed, it's just a pointer or a primitive variable, so it won't cost more than few bytes.

It's different if we talk about the cost of transmitting code. We know that JavaScript isn't a compiled language and it needs to reach the client's computer to be executed, so every space, indentation, semicolon, will cost in order of time used to transfer.

To reduce this cost, you can uglify and minify your code, but usually this type of optimization isn't performed.

Finally, it's impossible to think a scenario where it can make a difference, so I advise you to use the form that you think it's more readable and no matter of other parameters.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: