0

Lets say that I have some array, and I need to go through every element store it in var and print it then. Which of these 2 ways is better in terms of memory efficiency, speed? First way:

var arr=[x,y,z];
for(var i=0; i<arr.length; i++){
  var x=arr[i];
  console.log(x)
}

Or second way:

var arr=[x,y,z];
var x;
for(var i=0; i<arr.length; i++){
  x=arr[i];
  console.log(x)
}
  • 1
    There's no difference. Variable scope in JS is by function, not by block, so the variable declaration in the first version is hoisted to the top of the function. – Barmar Dec 04 '14 at 08:38

1 Answers1

0

here is absolutely no difference in meaning or performance, in JavaScript or ActionScript.

var is a directive for the parser, and not a command executed at run-time. If a particular identifier has been declared var once or more anywhere in a function body(*), then all use of that identifier in the block will be referring to the local variable. It makes no difference whether value is declared to be var inside the loop, outside the loop, or both.

JavaScript variables declare outside or inside loop?

http://www.w3schools.com/js/js_scope.asp

Community
  • 1
  • 1
Mohammad Ashfaq
  • 1,333
  • 2
  • 14
  • 38