Kevin
Kevin

Reputation: 73

Javascript Scope undefined

I have a problem with the online document of the website of jquery about javascript scope.There are codes;

(function() {

var baz = 1;

var bim = function() {
    console.log( baz );
};

bar = function() {
    console.log( baz );
};

})();

And says:

console.log( baz ); // baz is not defined outside of the function

the thing that I don't understand is that even though baz is defined, why console.log(baz) is undefined. Because I think the scope is the same. Did I miss something?

Upvotes: 4

Views: 183

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206102

the thing that I don't understand is that even though baz is defined, why console.log(baz) is undefined

It's undefined cause it's range is restricted (private) to the IIFE (Immediately Invoked Function Expression) scope.

If you chain your variable to the Window object, it'll be accessible globally.

DEMO

(function() {

  window.baz = 1; // Global
  var pub    = 2; // private

  var bim = function() {
    console.log( baz );
  };

  var bar = function() {
    console.log( pub ); 
  };

  bim(); // 1 //////////
  bar(); // 2 //////////

})(); 


console.log( baz ); // 1 //////////
console.log( pub ); // Ref.Error //

Upvotes: 0

Alex
Alex

Reputation: 11245

May be you are under "strict mode" ? In Chrome console everything is right. Calling of "baz" write 1 .

jsfiddle to check jsfiddle.net/Yjq2v/

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148524

The trap is the IIFE - immediate invoked function expressions which creates their own scope.

JS is using function scope

So baz is not defined outside that IIFE.

change this to :

(function() {

 window.baz = 1;     <----

var bim = function() {
    console.log( baz );
};

bar = function() {
    console.log( baz );
};

})();

And it will work.

p.s.

This is how jQuery attach ( when they finish with bla bla..) the $ /jQuery to the window. ( only that the window.$ is at its last lines).

Upvotes: 5

Related Questions