Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Added to the scope JS 101 article #201

Closed
wants to merge 9 commits into from

5 participants

@jackfranklin

Following on from #89 (comment), I finally found some time to quickly move over some of the content I wrote for my initial Scope and this in JS article and move it over into the Scopes article, reworking it slightly but not making any major changes.

Let me know what you think :)

page/javascript-101/scope.md
((15 lines not shown))
When a variable is declared inside of a function using the `var` keyword, it is only available to code inside of that function — code outside of that function cannot access the variable. On the other hand, functions defined inside that function will have access to to the declared variable.
+There are two types of scopes in JavaScript: Global and local. Lets talk about each of them in turn.
+
+The first scope is __Global Scope__. This is very easy to define. If a variable or function is _global_, it can be got at from anywhere. In a browser, the global scope is the `window` object. So if in your code you simply have:
@rmurphey Collaborator

Two things:

  • suggest "it can be accessed from anywhere within a program" rather than "it can be got at from anywhere"
  • this paragraph ends as though the thought will be continued after the code example, but it is not continued
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((15 lines not shown))
When a variable is declared inside of a function using the `var` keyword, it is only available to code inside of that function — code outside of that function cannot access the variable. On the other hand, functions defined inside that function will have access to to the declared variable.
+There are two types of scopes in JavaScript: Global and local. Lets talk about each of them in turn.
+
+The first scope is __Global Scope__. This is very easy to define. If a variable or function is _global_, it can be got at from anywhere. In a browser, the global scope is the `window` object. So if in your code you simply have:
+
+```
+var x = 9;
+```
+
+The only other scope we can have is __Local Scope__. JavaScript scopes at a function level. For example:
+
+```
+function myFunc() {
+ var x = 5;
+});
+console.log(x); //undefined
@rmurphey Collaborator

This won't result in undefined being logged; rather, it will result in a Reference Error, assuming x is not also defined outside of the function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((15 lines not shown))
When a variable is declared inside of a function using the `var` keyword, it is only available to code inside of that function — code outside of that function cannot access the variable. On the other hand, functions defined inside that function will have access to to the declared variable.
+There are two types of scopes in JavaScript: Global and local. Lets talk about each of them in turn.
+
+The first scope is __Global Scope__. This is very easy to define. If a variable or function is _global_, it can be got at from anywhere. In a browser, the global scope is the `window` object. So if in your code you simply have:
+
+```
+var x = 9;
+```
+
+The only other scope we can have is __Local Scope__. JavaScript scopes at a function level. For example:
+
+```
+function myFunc() {
+ var x = 5;
+});
@rmurphey Collaborator

syntax error -- unnecessary )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@rmurphey rmurphey commented on the diff
page/javascript-101/scope.md
@@ -1,15 +1,80 @@
---
-title: Scope
-level: beginner
-source: http://jqfundamentals.com/legacy
-attribution:
+title: Scope
+level: beginner
+source: http://jqfundamentals.com/legacy, http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this
+attribution:
- jQuery Fundamentals
@rmurphey Collaborator

Is this accurate? Seems the jqf content has been largely replaced.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((33 lines not shown))
+```
+
+Since `x` was initialised within `myFunc()`, it is only accessible within `myFunc()`.
+
+__A word of Caution__
+
+If you declare a variable & forget to use the `var` keyword, that variable is automically made global. So this code would work:
+
+```
+function myFunc() {
+ x = 5;
+});
+console.log(x); //5
+```
+
+This is a __very bad idea__. It's considered bad practise to clutter the global scope. You should add as fewer properties as you possibly can to the global object. That's why you'll see libaries such as jQuery often do this:
@rmurphey Collaborator

Why is this a bad idea? It's not just about cluttering the global scope; there's also the issue that other parts of a program can change the value of a global variable, which is generally undesirable because it can lead to unforeseen side effects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((39 lines not shown))
+If you declare a variable & forget to use the `var` keyword, that variable is automically made global. So this code would work:
+
+```
+function myFunc() {
+ x = 5;
+});
+console.log(x); //5
+```
+
+This is a __very bad idea__. It's considered bad practise to clutter the global scope. You should add as fewer properties as you possibly can to the global object. That's why you'll see libaries such as jQuery often do this:
+
+```
+(function() {
+ var jQuery = { /* all my methods go here */ };
+ window.jQuery = jQuery.
+});
@rmurphey Collaborator

jQuery actually does this as an IIFE -- otherwise, the code inside the function won't run, and window.jQuery won't get defined. The code above doesn't include the invocation of the function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((51 lines not shown))
+(function() {
+ var jQuery = { /* all my methods go here */ };
+ window.jQuery = jQuery.
+});
+```
+
+Wrapping everything in a function which is then immediately invoked means all the variables within that function are bound to the _local scope_. At the very end you can then expose all your methods by binding the `jQuery` object to the `window`, the _global object_.
+
+Because local scope works through functions, any functions defined within another have access to variables defined in the outer function:
+
+```
+function outer() {
+ var x = 5;
+ function inner() {
+ console.log(x); //5
+ }
@rmurphey Collaborator

This example makes more sense if the inner() function is called somewhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@jackfranklin

@rmurphey thanks for your feedback, I guess that teaches me for doing the pull request in a bit of a rush! Based on your feedback I have reworded and reworked things.

As for if the attribution is out of date, I am unsure. I presumed the contents of the file before I edited were from jQF, and I've not removed it.

page/javascript-101/scope.md
((15 lines not shown))
When a variable is declared inside of a function using the `var` keyword, it is only available to code inside of that function — code outside of that function cannot access the variable. On the other hand, functions defined inside that function will have access to to the declared variable.
+There are two types of scopes in JavaScript: Global and local. Lets talk about each of them in turn.
+
+The first scope is __Global Scope__. This is very easy to define. If a variable or function is _global_, it can be accessed from anywhere within a program. In a browser, the global scope is the `window` object. A variable that is defined from anywhere but within a function is global.
+
+```
+var x = 9;
+```
+
+Once that variable is set, it exists on the global object. Once that variable had been defined, it could be referenced as `window.x`, but because it exists on the global object we can simply refer to it as `x`.
+
+The only other scope we can have is __Local Scope__. JavaScript scopes at a function level. For example:
@rmurphey Collaborator

Better:

JavaScript also creates a Local Scope inside each function body. For exampmle:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((15 lines not shown))
When a variable is declared inside of a function using the `var` keyword, it is only available to code inside of that function — code outside of that function cannot access the variable. On the other hand, functions defined inside that function will have access to to the declared variable.
+There are two types of scopes in JavaScript: Global and local. Lets talk about each of them in turn.
+
+The first scope is __Global Scope__. This is very easy to define. If a variable or function is _global_, it can be accessed from anywhere within a program. In a browser, the global scope is the `window` object. A variable that is defined from anywhere but within a function is global.
+
+```
+var x = 9;
+```
+
+Once that variable is set, it exists on the global object. Once that variable had been defined, it could be referenced as `window.x`, but because it exists on the global object we can simply refer to it as `x`.
@rmurphey Collaborator

Better:

If this variable declaration occurs outside of a function, then the variable x exists on the global object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((24 lines not shown))
+```
+
+Once that variable is set, it exists on the global object. Once that variable had been defined, it could be referenced as `window.x`, but because it exists on the global object we can simply refer to it as `x`.
+
+The only other scope we can have is __Local Scope__. JavaScript scopes at a function level. For example:
+
+```
+function myFunc() {
+ var x = 5;
+};
+console.log(x); // ReferenceError: x is not defined
+```
+
+Since `x` was initialised within `myFunc`, it is only accessible within `myFunc`, and we get a reference error if we try to access it outside of `myFunc`.
+
+__A word of Caution__
@rmurphey Collaborator

Should this be a header or a note, rather than just an italicized fragment?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@rmurphey
Collaborator

On reading this content in greater depth, I think it would be good to spend some more time integrating it into the existing content -- presently it seems like there's some duplication of content between the old and new content, and it seems like some of the examples at the end of the section are no longer necessary, or should have some prose explanation associated with them. I can try to take a look at this tomorrow, but I'm not sure how best to submit the changes -- as a pull request on @jackfranklin's repo, or as a pull request to this repo that simply builds upon what's here. @ajpiano?

I've added a couple more comments inline. I'd also suggest:

  • ensure consistent use of US English spellings per the style guide
  • avoid using an ampersand; use "and" instead
  • link to Ben Alman's IIFE explanation
  • get the PR into a merge-able state :) seems it can't be merged at the moment but I haven't explored why
@jackfranklin

Thanks for your feedback @rmurphey :) I will have a crack at integrating the two bits more closely, and bring the file up to date with the style guide.

I've not got any immediate idea as to why it's not merge-able, unless the Original MD file has changed since I pulled. I'll have an explore as to why.

@jackfranklin

Just did some more tweaking. I've no idea why Github says this isn't merge-able though!

I made a start on integrating the two "bits" of the article and adding some prose around the larger code examples. Not perfect by any means but a start.

@gnarf
Owner

@jackfranklin Try pulling from upstream master and merging into the branch, or rebasing the branch on the current master. I know I did a lot of changes in the formatting/example code in this article.

@jackfranklin

@gnarf37 thanks, I did a pull from upstream and indeed there was a conflict in scopes.md which I fixed. This does mean that this pull request is now awfully messy though with that latest commit that fixed the conflicts. Would it be best to delete this one, and I'll re-fork, apply my changes and do a new pull request so there's a lot less noise?

page/javascript-101/scope.md
((40 lines not shown))
};
+console.log(x); // ReferenceError: x is not defined
@gnarf Owner
gnarf added a note

console.log( x );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((40 lines not shown))
};
+console.log(x); // ReferenceError: x is not defined
+```
+
+Since `x` was initialised within `myFunc()`, it is only accessible within `myFunc()`, and we get a reference error if we try to access it outside of `myFunc()`.
+
+##A word of Caution
+
+If you declare a variable and forget to use the `var` keyword, that variable is automically made global. So this code would work:
+
+```
+function myFunc() {
+ x = 5;
+});
+console.log(x); // 5
@gnarf Owner
gnarf added a note

Inner spacing: console.log( x );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((61 lines not shown))
+```
+(function() {
+ var jQuery = { /* all my methods go here */ };
+ window.jQuery = jQuery.
+})();
+```
+
+Wrapping everything in a function which is then immediately invoked means all the variables within that function are bound to the _local scope_. At the very end you can then expose all your methods by binding the `jQuery` object to the `window`, the _global object_. To read more about Immediatly-Onvoked Functions, check out Ben Alman's [Immediately-Invoked Function Expression](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) article.
+
+Because local scope works through functions, any functions defined within another have access to variables defined in the outer function:
+
+```
+function outer() {
+ var x = 5;
+ function inner() {
+ console.log(x);
@gnarf Owner
gnarf added a note

Again - console.log( x )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((88 lines not shown))
-sayHello(); // "hello"
-console.log( foo ); // "hello"
+ function inner() {
+ console.log(x);
+ var y = 10;
+ }
+
+ inner(); // 5
+
+ console.log(y); // ReferenceError: y is not defined
@gnarf Owner
gnarf added a note

This and also 6 lines before it, need spacing inside the function args: ( y )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@gnarf
Owner

@jackfranklin the diff doesn't seem that noisy - You could start over if you think that will result in a better pull though, I won't stop you :)

@jackfranklin

If you're happy I'll leave it :-) I will make those adjustments tomorrow.

page/javascript-101/scope.md
((44 lines not shown))
+Since `x` was initialised within `myFunc()`, it is only accessible within `myFunc()`, and we get a reference error if we try to access it outside of `myFunc()`.
+
+##A word of Caution
+
+If you declare a variable and forget to use the `var` keyword, that variable is automically made global. So this code would work:
+
+```
+function myFunc() {
+ x = 5;
+});
+console.log(x); // 5
+```
+
+This is a bad idea. Any variable that is global can have its value changed by any other parts of a program or any other script. This is undesirable, as it could lead to unforseen side effects.
+
+Secondly, it's considered bad practise to clutter the global scope. You should add as fewer properties as you possibly can to the global object, and try to keep your program contained within its own scope. That's why you'll see libaries such as jQuery often do this:
@rmurphey Collaborator

This seems like a restatement of the first reason not to have global variables. I'm hesitant to just say a thing is a bad practice without saying why it's a bad practice, but in fact you've already said why it's a bad practice, so this paragraph seems redundant to me.

I'd simply point out that IIFEs provide a way to avoid polluting the global scope -- ensuring that variables can't be tampered with by other code -- and move on to the example below.

@rmurphey Collaborator

practise -> practice

@rmurphey do you mean to remove the entire jQuery IIFE example, or just reword the line that starts "Secondly..." to mention IIFEs, then show the jQuery example, and then move onto the next example (which starts on line 59) ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((18 lines not shown))
-Furthermore, variables that are declared inside a function without the `var` keyword are not local to the function — JavaScript will traverse the scope chain all the way up to the window scope to find where the variable was previously defined. If the variable wasn't previously defined, it will be defined in the global scope, which can have unexpected consequences.
+## Global Scope
+
+The first scope is __Global Scope__. This is very easy to define. If a variable or function is _global_, it can be accessed from anywhere within a program. In a browser, the global scope is the `window` object. If this variable declaration occurs outside of a function, then the variable x exists on the global object.
@rmurphey Collaborator

This mentions "this variable declaration" but I'm not clear which variable declaration it's referring to?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
page/javascript-101/scope.md
((40 lines not shown))
};
+console.log(x); // ReferenceError: x is not defined
+```
+
+Since `x` was initialised within `myFunc()`, it is only accessible within `myFunc()`, and we get a reference error if we try to access it outside of `myFunc()`.
@rmurphey Collaborator

initialised -> initialized

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@jackfranklin

@rmurphey, with regards to this comment:

This seems like a restatement of the first reason not to have global variables. I'm hesitant to just say a thing is a bad practice without saying why it's a bad practice, but in fact you've already said why it's a bad practice, so this paragraph seems redundant to me.

I'd simply point out that IIFEs provide a way to avoid polluting the global scope -- ensuring that variables can't be tampered with by other code -- and move on to the example below.

Do you mean to remove the entire jQuery IIFE example, or just reword the line that starts "Secondly..." to mention IIFEs, then show the jQuery example, and then move onto the next example (which starts on line 59) ? I agree it could do with reworking a little but not entirely clear on what you mean.

Thanks for all your help so far :)

@addyosmani
Collaborator

cc @rmurphey for some further comments on the above when you get a chance :)

@rmurphey
Collaborator

@jackfranklin I'd change the paragraph that starts with "Secondly" to just explain that IIFEs provide a way to avoid global variables, and then show the example of the jQuery IIFE.

@jackfranklin

@rmurphey sorry for the delay on getting back to this! I've made the edits to shrink that sentence down and make it less repetitive.

@gnarf
Owner

So, this merge went grey somewhere along the way, can you rebase/merge it?

@jackfranklin

@gnarf37 just pulled in from upstream and fixed the conflict - hopefully it's green now?

@gnarf
Owner

It is. I plan on pinging @ajpiano today about this, hopefully we can merge it before it gets stale again :)

@ajpiano ajpiano closed this in 6fc9783
@alimony alimony referenced this pull request from a commit
Commit has since been removed from the repository and is no longer available.
@rmurphey rmurphey referenced this pull request from a commit in rmurphey/learn.jquery.com
@rmurphey rmurphey Merge branch 'master' into fix_method_refs
* master: (21 commits)
  0.2.7
  Remove remaining trailing whitespace from all pages. Fixes #313.
  Style and typography fixes, and code style adherence in the JavaScript 101 section. Fixes #312.
  0.2.6
  Correct comment in :input selector in Selecting Elements article. Fixes #306.
  Expand the JavaScript 101 'Scope' article with more useful information and explanations. Fixes #201.
  Added 0 to the list of falsy values in JavaScript 101 Conditional Code article. Fixes #300. Fixes #271
  Inserted missing word in the JavaScript 101 Arrays article. Fixes #299.
  Fixed inconsistency in showLinkLocation example in Basic Plugin Creation article. Fixes #307.
  Fix example and other style cleanup in Basic Plugin Creation article. Fixes #310. Fixes #311.
  Update list of reserved words in JavaScript. Fixes #301.
  Style and typography fixes and code style adherence in the Events section. Fixes #294.
  Style and typography fixes, and code style adherence in the Effects section. Fixes #290.
  Style and typography fixes, and code style adherence in the Code Organization section. Fixes #287.
  Remove double ampersands in README header. Fixes #284.
  Code and prose style improvements to all articles in Ajax chapter. Fixes #283.
  Style fixes on the About page. Fixes #279.
  Style guide fixes for the index, contributing, and About jQuery articles. Fixes #270
  relabel queue/dequeue content as advanced
  Added a missing 'i' in the for loop. Fixes #280.
  ...

Conflicts:
	page/ajax/ajax-and-forms.md
	page/ajax/jquery-ajax-methods.md
	page/effects/custom-effects.md
	page/effects/intro-to-effects.md
	page/events/event-basics.md
	page/events/event-helpers.md
	page/events/introduction-to-custom-events.md
	page/events/triggering-event-handlers.md
bac5e33
@arthurvr arthurvr referenced this pull request from a commit in arthurvr/learn.jquery.com
@jackfranklin jackfranklin Expand the JavaScript 101 'Scope' article with more useful informatio…
…n and explanations. Fixes #201.
f0d091c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
Showing with 115 additions and 36 deletions.
  1. +115 −36 page/javascript-101/scope.md
View
151 page/javascript-101/scope.md
@@ -1,42 +1,108 @@
---
-title: Scope
-level: beginner
-source: http://jqfundamentals.com/legacy
-attribution:
+title: Scope
+level: beginner
+source: http://jqfundamentals.com/legacy, http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this
+attribution:
- jQuery Fundamentals
@rmurphey Collaborator

Is this accurate? Seems the jqf content has been largely replaced.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
---
-"Scope" refers to the variables that are available to a piece of code at a given time. A lack of understanding of scope can lead to frustrating debugging experiences.
+"Scope" refers to the variables that are available to a piece of code at a given time. A lack of understanding of scope can lead to frustrating debugging experiences. The idea of "scope" is that it's where certain functions or variables are accessible from in our code, and the context in which they exist and are executed in.
-When a variable is declared inside of a function using the `var` keyword, it is only available to code inside of that function — code outside of that function cannot access the variable. On the other hand, functions defined inside that function will have access to the declared variable.
+There are two types of scopes in JavaScript: Global and local. Lets talk about each of them in turn.
-Furthermore, variables that are declared inside a function without the `var` keyword are not local to the function — JavaScript will traverse the scope chain all the way up to the window scope to find where the variable was previously defined. If the variable wasn't previously defined, it will be defined in the global scope, which can have unexpected consequences.
+## Global Scope
+
+The first scope is __Global Scope__. This is very easy to define. If a variable or function is _global_, it can be accessed from anywhere within a program. In a browser, the global scope is the `window` object. If a variable declaration occurs outside of a function, then that variable exists on the global object. For example:
```
-// Functions have access to variables defined in the same scope
-var foo = "hello";
-var sayHello = function() {
- console.log( foo );
+var x = 9;
+```
+
+Once that variable had been defined, it could be referenced as `window.x`, but because it exists on the global object we can simply refer to it as `x`.
+
+## Local Scope
+JavaScript also creates a __Local Scope__ inside each function body. For example:
+
+```
+function myFunc() {
+ var x = 5;
};
+console.log( x ); // ReferenceError: x is not defined
+```
+
+Since `x` was initialized within `myFunc()`, it is only accessible within `myFunc()`, and we get a reference error if we try to access it outside of `myFunc()`.
+
+##A word of Caution
+
+If you declare a variable and forget to use the `var` keyword, that variable is automically made global. So this code would work:
+
+```
+function myFunc() {
+ x = 5;
+});
+console.log( x ); // 5
+```
+
+This is a bad idea. Any variable that is global can have its value changed by any other parts of a program or any other script. This is undesirable, as it could lead to unforseen side effects.
+
+Secondly, Immediately-Invoked Funcion Expressions provide a way to avoid global variables. You'll see many libraries such as jQuery often use these:
+
+```
+(function() {
+ var jQuery = { /* all my methods go here */ };
+ window.jQuery = jQuery.
+})();
+```
+
+Wrapping everything in a function which is then immediately invoked means all the variables within that function are bound to the _local scope_. At the very end you can then expose all your methods by binding the `jQuery` object to the `window`, the _global object_. To read more about Immediatly-Invoked Functions, check out Ben Alman's [Immediately-Invoked Function Expression](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) article.
+
+Because local scope works through functions, any functions defined within another have access to variables defined in the outer function:
+
+```
+function outer() {
+ var x = 5;
+ function inner() {
+ console.log( x );
+ }
+
+ inner(); // 5
+}
+```
+
+But the `outer()` function doesn't have access to any variables declared within `inner()`:
+
+```
+function outer() {
+ var x = 5;
-sayHello(); // "hello"
-console.log( foo ); // "hello"
+ function inner() {
+ console.log( x );
+ var y = 10;
+ }
+
+ inner(); // 5
+
+ console.log( y ); // ReferenceError: y is not defined
+}
```
+Furthermore, variables that are declared inside a function without the `var` keyword are not local to the function — JavaScript will traverse the scope chain all the way up to the window scope to find where the variable was previously defined. If the variable wasn't previously defined, it will be defined in the global scope, which can have unexpected consequences.
+
```
-// Code outside the scope in which a variable was defined does not have access to the variable
+// Functions have access to variables defined in the same scope
+var foo = "hello";
+
var sayHello = function() {
- var foo = "hello";
console.log( foo );
};
-sayHello(); // hello
+sayHello(); // "hello"
-console.log( foo ); // undefined
+console.log( foo ); // "hello"
```
+Variables with the same name can exist in different scopes with different values:
```
-// Variables with the same name can exist in different scopes with different values
var foo = "world";
var sayHello = function() {
@@ -44,12 +110,14 @@ var sayHello = function() {
console.log( foo );
};
-sayHello(); // logs "hello"
-console.log( foo ); // logs "world"
+sayHello(); // "hello"
+
+console.log( foo ); // "world"
```
+When you reference a global variable within a function, that function can see changes to the variable value after the function is defined.
+
```
-// Functions can see changes in variable values after the function is defined
var myFunction = function() {
var foo = "hello";
var myFn = function() {
@@ -63,32 +131,43 @@ var f = myFunction();
f(); // "world"
```
+Here's a more complex example of scopes at play:
+
```
-// Scope insanity
-// a self-executing anonymous function
(function() {
var baz = 1;
+
var bim = function() {
- alert( baz );
+ console.log( baz );
+ };
+
+ bar = function() {
+ console.log( baz );
};
bar = function() {
- alert( baz );
+ console.log( baz );
};
})();
+```
+In this instance, running:
+
+```
+console.log( baz ); // baz is not defined outside of the function
+```
+
+Gives us a `ReferenceError`. `baz` was only defined within the function, and was never exposed to the global scope.
-// baz is not defined outside of the function
-console.log( baz );
+```
+bar(); // 1
+```
-// bar is defined outside of the anonymous function
-// because it wasn't declared with var; furthermore,
-// because it was defined in the same scope as baz,
-// it has access to baz even though other code
-// outside of the function does not
-bar();
+`bar()` may have been defined within the anonymous function, but it was defined without the `var` keyword, which means it wasn't bound to the local scope and was instead created globally. Furthermore, it has access to the `baz` variable because `bar()` was defined within the same scope as `baz`. This means it has access to it, even though other code outside of the function does not.
-// bim is not defined outside of the anonymous function,
-// so this will result in an error
-bim();
+
+```
+bim(); // ReferenceError: bim is not defined
```
+
+`bim()` was only defined within the function, so does not exist on the global object as it was defined locally.
Something went wrong with that request. Please try again.