0
var bark = function() {
  var animals = "Dogs";
  var sound   = "Bark"
  console.log(animals + " go " + sound);
};

console.log(animals);
console.log(sound);

When I log the variables to console, no cigar...

ReferenceError: animals is not defined

ReferenceError: sound is not defined

  • What "issue" is there? This seems like very sane [non-global] variable behavior.. also, the code is *never calling* `bark`, so even if they were [meant to be] global variables/properties they would not be assigned. – user2864740 Mar 26 '14 at 06:18
  • how a function is supposed to work if its not getting called? – Nagama Inamdar Mar 26 '14 at 06:20

5 Answers5

2

That is called a closure. Take a look at this article. Basically, the way you've written that function only the inside of that function can access those two variables. Also, you haven't actually called the function bark in this scenario, you just defined the function that has a name of bark. Had you written it this way...

var bark = function() {
    this.animals = "Dogs";
    this.sound = "Bark";
}
var myBark = new bark();

Then you could console.log the results. For instance...

console.log(myBark.animals);
console.log(myBark.sound);

Now as you can see because of the this and the new, animals and sound belong to the instance of myBark. You could also do it like this.

var bark = function() {
    var animals = "Dogs";
    var sound = "Bark";
    this.logInfo = function() { console.log( animals + " go " + sound ); };
    this.getAnimals = function() { return animals; };
    this.getSound = function() { return sound; };
}

With this way you now have the variables closed off but you have access to them through these member functions. If I say...

var myBark = new bark();

I can then print stuff and get stuff like so...

myBark.logInfo();
console.log(myBark.getAnimals());
console.log(myBark.getSound());
Ryan Bartley
  • 606
  • 8
  • 17
0

If you define the variables outside the function scope, it should work.

Zafer
  • 2,180
  • 16
  • 28
0

variable defined inside the function's block is local to that function only.

Define var animals, sound; above of function.

Dhanu Gurung
  • 8,480
  • 10
  • 47
  • 60
0

var animals = "Dogs"; var sound = "Bark" are scoped to function bark so not available outside function.

rt2800
  • 3,045
  • 2
  • 19
  • 26
0

Variable in JavaScript is accessible within current scope or child level scope. Here you trying to access children variable in Parent which is not possible.

as you can verify by:

var bark = function() {
  var animals = "Dogs";
  var sound   = "Bark"
  console.log(animals + " go " + sound);
};

bark();

if you need to log outside of function then try:

var animals,sound;
var bark = function() {
  animals = "Dogs";
  sound   = "Bark"
  console.log(animals + " go " + sound);
};
bark();
console.log(animals);
console.log(sound);

Here is fiddle demo

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110