0

Local variable oopsGlobal, gives an error when used outside of function fun1 but the other variable name defined in the same way does not give an error and is accessible outside of the function?

Am I missing something here?

function functionName() {
  // variables created without Var always global scope
  var name = "sudeep";
  console.log("myfirst function");
}

function functionName1() {
  // variables created without Var always global scope
  console.log("Local variable with var:" + name);
}
// Declare your variable here
var myGlobal = 10;

function fun1() {
  // Assign 5 to oopsGlobal Here
  var oopsGlobal = 5; //local scope to variable when accessed outside gives error so working fine
}

functionName();
functionName1();
console.log(name); // **does not give error at all**
fun1();
console.log(name); //**does not give error at all**
console.log(oopsGlobal); //give error so works fine

enter image description here

Ivan
  • 34,531
  • 8
  • 55
  • 100
  • 2
    The only difference is that [`name` already is a global variable](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) – Bergi Jun 01 '18 at 14:19
  • @Bergi, you gave a link to the `name` property of `Window`, what does this have to do with the variable `name`? – Ivan Jun 01 '18 at 14:23
  • 1
    Thanks Bergi, that is what i was looking for but i do not know exactly why it is referring to window objectsname property. Does that means that we cannot define a local variable in JS with variable named "name", strange to me and if referring window.name property how does it prints my name in console when referring to "name" variable? Here i wanted to create a local variable with "name" in function with var so that no other function can use this variable outside of function. – sudeep patel Jun 01 '18 at 14:27
  • 1
    @Ivan A property on the global object acts as a global variable - it's like `var name;` in the global scope and therefore affecting assignment to the "undeclared" identifier `name`. – Bergi Jun 01 '18 at 14:28
  • Just verified and yes it is referring to window.name property. Is there a way to create local variable in a function named "name" and does not refer to window.name? – sudeep patel Jun 01 '18 at 14:39

0 Answers0