1

I am from C++ background and new to java script and having difficulty understand for loop scope. What is the scope of variable initialized inside for loop.

//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];


function lookUpProfile(firstName, prop){
  for(var i=0;i<contacts.length;i++){
      if(contacts[i].firstName==firstName){
          if(contacts[i].hasOwnProperty(prop))
            return contacts[i][prop];
          else
             return "No such property";
        }
    }
  
    if (i === contacts.length)
    return "No such contact";

}

// Change these values to test your function
lookUpProfile("Akira", "likes");

I am confused how if (i === contacts.length) variable "i" is used outside for loop, variable "i" is initialize inside for loop and if statement is written out of scope of for loop. Value of document.write(i) is equal to 4 when printed outside loop.Can somebody please explain this?

Priyansh
  • 1,163
  • 11
  • 28

2 Answers2

3

Before ECMAScript 6, javascript only supports function scoping. A variable declared inside a function is visible anywhere inside that function. Even this:

function foo() {
  if(true) {
    if(true) {
      var v = 7;
    }
  }

  console.log(v); // 7
}
foo();

ECMAScript 6 introduced a new way of declaring variables using let which respects block scopes. So:

function foo() {
  if (true) {
    if (true) {
      let v = 7;
    }
  }

  console.log(v); // error
}
foo();
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • But var in ECMA Script 6 doesn't respect the scope of variable. It meant once I declare a variable at any point in function, I will always be able to use that variable anywhere outside the scope of variable? – Priyansh Apr 22 '17 at 17:50
  • @Priyansh As I said the only scope when using `var` is the function scope. Even in ES 6 declaring with `var` will make the variable visible from anywhere inside that function as long as you don't enter the scope of some other function. – ibrahim mahrir Apr 22 '17 at 17:54
  • @Priyansh nope its in its *function scope* and its only accessible there – Jonas Wilms Apr 22 '17 at 17:56
  • @Jonas but I initialized it in for loop and keeping C++ perspective variable "I" is out of scope. Is scopes are different in Javascript – Priyansh Apr 22 '17 at 17:58
  • @Priyansh C++ have block scopes, JS doesn't – ibrahim mahrir Apr 22 '17 at 17:58
  • 1
    @Priyansh yes. Have a look at *hoisting* . In fact it is declared at the beginning of the function with the value of *undefined* : Its then assigned to 0 at the beginning of the for loop... i think you should use *let* instead of *var* as it uses block scoping, just like in C++ – Jonas Wilms Apr 22 '17 at 17:59
  • @Jonasw hoisting is another story. – ibrahim mahrir Apr 22 '17 at 18:01
  • @ibrahimmahrir yep but it makes it easier to understand scoping in js in my opinion – Jonas Wilms Apr 22 '17 at 18:02
  • 2
    *javascript only supports function scoping* Incorrect. In `catch (e) { }`, `e` is scoped only to the catch block. –  Apr 22 '17 at 18:03
2

var scopes a variable to the current function, not the current block (unlike let).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335