Skip to content

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 :)

@rmurphey rmurphey commented on an outdated diff Nov 24, 2012
page/javascript-101/scope.md
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
rmurphey added a note Nov 24, 2012

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
@rmurphey rmurphey commented on an outdated diff Nov 24, 2012
page/javascript-101/scope.md
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
rmurphey added a note Nov 24, 2012

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
@rmurphey rmurphey commented on an outdated diff Nov 24, 2012
page/javascript-101/scope.md
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
rmurphey added a note Nov 24, 2012

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 Nov 24, 2012
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
rmurphey added a note Nov 24, 2012

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
@rmurphey rmurphey commented on an outdated diff Nov 24, 2012
page/javascript-101/scope.md
+```
+
+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
rmurphey added a note Nov 24, 2012

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
@rmurphey rmurphey commented on an outdated diff Nov 24, 2012
page/javascript-101/scope.md
+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
rmurphey added a note Nov 24, 2012

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
@rmurphey rmurphey commented on an outdated diff Nov 24, 2012
page/javascript-101/scope.md
+(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
rmurphey added a note Nov 24, 2012

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.

@rmurphey rmurphey commented on an outdated diff Nov 25, 2012
page/javascript-101/scope.md
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
rmurphey added a note Nov 25, 2012

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
@rmurphey rmurphey commented on an outdated diff Nov 25, 2012
page/javascript-101/scope.md
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
rmurphey added a note Nov 25, 2012

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
@rmurphey rmurphey commented on an outdated diff Nov 25, 2012
page/javascript-101/scope.md
+```
+
+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
rmurphey added a note Nov 25, 2012

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

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
jQuery Foundation member
gnarf commented Nov 25, 2012

@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?

@gnarf gnarf commented on an outdated diff Nov 25, 2012
page/javascript-101/scope.md
};
+console.log(x); // ReferenceError: x is not defined
@gnarf
jQuery Foundation member
gnarf added a note Nov 25, 2012

console.log( x );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@gnarf gnarf commented on an outdated diff Nov 25, 2012
page/javascript-101/scope.md
};
+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
jQuery Foundation member
gnarf added a note Nov 25, 2012

Inner spacing: console.log( x );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@gnarf gnarf commented on an outdated diff Nov 25, 2012
page/javascript-101/scope.md
+```
+(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
jQuery Foundation member
gnarf added a note Nov 25, 2012

Again - console.log( x )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@gnarf gnarf commented on an outdated diff Nov 25, 2012
page/javascript-101/scope.md
-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
jQuery Foundation member
gnarf added a note Nov 25, 2012

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
jQuery Foundation member
gnarf commented Nov 25, 2012

@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.

@rmurphey rmurphey and 1 other commented on an outdated diff Nov 26, 2012
page/javascript-101/scope.md
+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
rmurphey added a note Nov 26, 2012

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
rmurphey added a note Nov 26, 2012

practise -> practice

@jackfranklin
jackfranklin added a note Nov 26, 2012

@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
@rmurphey rmurphey commented on an outdated diff Nov 26, 2012
page/javascript-101/scope.md
-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
rmurphey added a note Nov 26, 2012

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
@rmurphey rmurphey commented on an outdated diff Nov 26, 2012
page/javascript-101/scope.md
};
+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
rmurphey added a note Nov 26, 2012

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
jQuery Foundation member

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

@rmurphey

@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
jQuery Foundation member
gnarf commented Feb 27, 2013

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
jQuery Foundation member
gnarf commented Feb 27, 2013

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

@ajpiano ajpiano added a commit that closed this pull request Mar 14, 2013
@jackfranklin jackfranklin Expand the JavaScript 101 'Scope' article with more useful informatio…
…n and explanations. Fixes #201.
6fc9783
@ajpiano ajpiano closed this in 6fc9783 Mar 14, 2013
@rmurphey rmurphey added a commit to rmurphey/learn.jquery.com that referenced this pull request Mar 17, 2013
@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 pushed a commit to arthurvr/learn.jquery.com that referenced this pull request Jan 4, 2015
@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
Something went wrong with that request. Please try again.