Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using var keyword in a for loop

This is related to "var" or no "var" in JavaScript's "for-in" loop? (but talks more about scope - this question IS NOT about scope)

Is looping through an object or an array more efficient/common and why?

Option 1 - Setting var outside loop

// Object
var x;
for (x in obj) { ... }
// Array
var i;
for (i = 0; i < array.length; ++i) { ... }

Option 2 - Setting var in the loop

// Object
for (var x in obj) { ... }
// Array
for (var i = 0; i < array.length; ++i) { ... }
like image 824
Lizard Avatar asked May 03 '26 10:05

Lizard


1 Answers

var gets hoisted and is scoped to the function, not the block, so the differences will be optimised away by the compiler.

The second one is marginally faster because there are fewer characters to send over the wire. This difference is not significant enough to be an influencing factor in your decision about which to use.

like image 117
Quentin Avatar answered May 05 '26 00:05

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!