-2

Inner function variable can access outer function variable, it is possible or not in java script.I am confusing for the closures.

function a(){
var x=10;
console.log(x,y);
return function b(){
var y=20;
console.log(x,y);
}
}

1 Answers1

0

Yes, inner function variables can access outer function variables, BUT NOT THE OTHER WAY AROUND. Very good clarifying question. Below is a simple example of a function accessing a variable in an encompassing scope.

var name = 'John';
var Person = function(){
  this.name = name;
}
var guy = new Person();
guy.name //John

function a(){
  var x=10;
  console.log(x);
  return function b(){
    var y=20;
    console.log(x,y);
  }
}
var x = a();
console.log('x defined')
x();

Try running this to see the sequence of interpretation in javascript

Liam Schauerman
  • 851
  • 5
  • 10
  • For the above Example i have print 10 & 20 but 10 is printed and Y is not defined,why? – baji kommadhi Dec 13 '14 at 19:22
  • javascript will run the line console.log(x,y) before y is defined, so y will be logged as undefined. if you run the returned function, y will be defined at that point, and the second console.log will log properly – Liam Schauerman Dec 13 '14 at 20:46