Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Style and typography fixes, and code style adherence in the JavaScript 101 section. #312

Closed
wants to merge 3 commits into from

3 participants

@alimony

See commit messages for details.

@alimony

Sigh, that was a mess of commits, I will have to clean it up.

@alimony

Hmm, can't really get this to work, are all the previous commits' branches properly merged? Or am I just doing something wrong when rebasing my branch over master?

alimony added some commits
@alimony alimony Remove trailing whitespace. 0382302
@alimony alimony Code style adherence.
* Spaces to tabs.
* Whitespace inside parentheses etc.
* Insertion and removal of empty lines for spacing.
* Comment reflow.
* Remove a few redundant code blocks.
249f92b
@alimony alimony Style, wording, and typography fixes.
* Dot and parentheses on function names.
* Better header style when only function names.
* Inline code markup on more words.
* Always link internal links with trailing slash.
* Various small style adherence fixes.
6680691
@alimony

@rdworth Yes, I read it, but it seems like no matter how much I try to keep a straight brain when doing git stuff, it most often ends up messy :(

Now, git reset --hard upstream/master and then rebasing branch over master did it this time, this pull request looks better now.

Sorry for the trouble.

@ajpiano ajpiano closed this in 6e0db70
@ajpiano
Collaborator

Thanks @alimony. What happened here is definitely a good example of why it it's a good to make sure to stash and pull before committing :)

@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
@alimony alimony Style and typography fixes, and code style adherence in the JavaScrip…
…t 101 section. Fixes #312.
e981287
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Mar 14, 2013
  1. @alimony

    Remove trailing whitespace.

    alimony authored
  2. @alimony

    Code style adherence.

    alimony authored
    * Spaces to tabs.
    * Whitespace inside parentheses etc.
    * Insertion and removal of empty lines for spacing.
    * Comment reflow.
    * Remove a few redundant code blocks.
  3. @alimony

    Style, wording, and typography fixes.

    alimony authored
    * Dot and parentheses on function names.
    * Better header style when only function names.
    * Inline code markup on more words.
    * Always link internal links with trailing slash.
    * Various small style adherence fixes.
This page is out of date. Refresh to see the latest.
View
5 page/javascript-101.md
@@ -2,7 +2,7 @@
title : JavaScript 101
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
customFields:
-
@@ -10,7 +10,8 @@ customFields:
value: "pencil"
---
-##Introduction
+## Introduction
+
So you want to unlock the power of jQuery to make the web a better place? Awesome, but there are a few things you should know about JavaScript first.
Introduced at the dawn of the web, [JavaScript](http://en.wikipedia.org/wiki/JavaScript) is a powerful and expressive language that runs inside the browser in conjunction with HTML and CSS. Based on an open standard called [ECMAScript](http://en.wikipedia.org/wiki/ECMAScript), JavaScript has quickly become the "programming language of the web". All the power of jQuery is accessed via JavaScript, so needless to say, it's an important language to learn. Having a basic knowledge of JavaScript will go a long way in understanding, structuring and debugging your code.
View
69 page/javascript-101/arrays.md
@@ -2,7 +2,7 @@
title: Arrays
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
Arrays are zero-indexed, ordered lists of values. They are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays.
@@ -10,31 +10,31 @@ Arrays are zero-indexed, ordered lists of values. They are a handy way to store
To create an array, either use the object constructor or the literal declaration, by assigning the variable a list of values after the declaration.
```
-// A simple array with constructor
-var myArray1 = new Array( "hello", "world" );
-// literal declaration, the preferred way
-var myArray2 = [ "hello", "world" ];
+// A simple array with constructor.
+var myArray1 = new Array( "hello", "world" );
+// Literal declaration, the preferred way.
+var myArray2 = [ "hello", "world" ];
```
The literal declaration is generally preferred. See the [Google Coding Guidelines](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Array_and_Object_literals) for more information.
-If the values are unknown, it is also possible to declare an empty Array, and add elements either through functions or through accessing by index:
+If the values are unknown, it is also possible to declare an empty array, and add elements either through functions or through accessing by index:
```
// Creating empty arrays and adding values
var myArray = [];
// adds "hello" on index 0
-myArray.push("hello");
+myArray.push( "hello" );
// adds "world" on index 1
-myArray.push("world");
+myArray.push( "world" );
// adds "!" on index 2
myArray[ 2 ] = "!";
```
-'push' is a function that adds an element on the end of the array and expands the array respectively. You also can directly add items by index. Missing indices will be filled with 'undefined'.
+`.push()` is a function that adds an element on the end of the array and expands the array respectively. You also can directly add items by index. Missing indices will be filled with `undefined`.
```
// Leaving indices
@@ -47,7 +47,7 @@ myArray[ 3 ] = "!";
console.log( myArray ); // [ "hello", "world", undefined, "!" ];
```
-If the size of the array is unknown, 'push' is far more safe. You can both access and assign values to array items with the index.
+If the size of the array is unknown, `.push()` is far more safe. You can both access and assign values to array items with the index.
```
// Accessing array items by index
@@ -58,7 +58,7 @@ console.log( myArray[2] ); // "!"
## Array Methods and Properties
-### `.length`
+### .length
The `.length` property is used to determine the amount of items in an array.
@@ -76,7 +76,7 @@ You will need the `.length` property for looping through an array:
var myArray = [ "hello", "world", "!" ];
for ( var i = 0; i < myArray.length; i = i + 1 ) {
- console.log( myArray[i] );
+ console.log( myArray[i] );
}
```
@@ -87,13 +87,13 @@ Except when using `for`/`in` loops:
var myArray = [ "hello", "world", "!" ];
for ( var i in myArray ) {
- console.log( myArray[ i ] );
+ console.log( myArray[ i ] );
}
```
-### `.concat`
+### .concat()
-Concatenate two or more arrays with `.concat`:
+Concatenate two or more arrays with `.concat()`:
```
// Concatenating Arrays
@@ -104,9 +104,9 @@ var myOtherArray = [ 5, 6, 7 ];
var wholeArray = myArray.concat( myOtherArray );
```
-### `.join`
+### .join()
-`.join` creates a string representation of an array by joining all of its elements using a separator string. If no separator is supplied (e.g. `.join` is called without arguments) the array will be joined using a comma:
+`.join()` creates a string representation of an array by joining all of its elements using a separator string. If no separator is supplied (e.g. `.join()` is called without arguments) the array will be joined using a comma:
```
// Joining elements
@@ -124,9 +124,9 @@ console.log( myArray.join("") ); // "helloworld!"
```
-### `.pop`
+### .pop()
-`.pop` removes the last element of an array. It is the opposite method of `.push`:
+`.pop()` removes the last element of an array. It is the opposite method of `.push()`:
```
// pushing and popping
@@ -138,7 +138,7 @@ myArray.push( 7 ); // [ 0 , 2 , 7 ]
myArray.pop(); // [ 0 , 2 ]
```
-### `.reverse`
+### .reverse()
As the name suggests, the elements of the array are in reverse order after calling this method:
@@ -150,9 +150,9 @@ var myArray = [ "world" , "hello" ];
myArray.reverse();
```
-### `.shift`
+### .shift()
-Removes the first element of an array. With `.push` and `.shift`, you can recreate the method of a [queue](http://en.wikipedia.org/wiki/Queue_(data_structure)):
+Removes the first element of an array. With `.push()` and `.shift()`, you can recreate the method of a [queue](http://en.wikipedia.org/wiki/Queue_(data_structure)):
```
// queue with shift() and push()
@@ -164,7 +164,7 @@ myArray.push( 7 ); // [ 0 , 2 , 7 ]
myArray.shift(); // [ 2 , 7 ]
```
-### `.slice`
+### .slice()
Extracts a part of the array and returns that part in a new array. This method takes one parameter, which is the starting index:
@@ -177,9 +177,9 @@ console.log( myArray ); // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
console.log( newArray ); // [ 4, 5, 6, 7, 8 ]
```
-### `.splice`
+### .splice()
-Removes a certain amount of elements and adds new ones at the given index. It takes at least 3 parameters:
+Removes a certain amount of elements and adds new ones at the given index. It takes at least three parameters:
```
// splice method
@@ -200,7 +200,7 @@ myArray.splice( 1, 2, 1, 2, 3, 4 );
console.log( myArray ); // [ 0, 1, 2, 3, 4, 5 ]
```
-### `.sort`
+### .sort()
Sorts an array. It takes one parameter, which is a comparing function. If this function is not given, the array is sorted ascending:
@@ -214,7 +214,7 @@ myArray.sort(); // 1, 3, 4, 6
```
// sorting with comparing function
function descending( a, b ) {
- return b - a;
+ return b - a;
}
var myArray = [ 3, 4, 6, 1 ];
@@ -224,7 +224,7 @@ myArray.sort( descending ); // [ 6, 4, 3, 1 ]
The return value of descending (for this example) is important. If the return value is less than zero, the index of a is before b, and if it is greater than zero it's vice-versa. If the return value is zero, the elements index is equal.
-### `.unshift`
+### .unshift()
Inserts an element at the first position of the array:
@@ -237,29 +237,30 @@ myArray.unshift( 2 ); // [ 2 , 0 ]
myArray.unshift( 7 ); // [ 7 , 2 , 0 ]
```
-### `.forEach`
+### .forEach()
-In modern browsers it is possible to traverse through arrays with a `.forEach` method, where you pass a function that is called for each element in the array.
+In modern browsers it is possible to traverse through arrays with a `.forEach()` method, where you pass a function that is called for each element in the array.
The function takes up to three arguments:
+
* *Element* - The element itself.
* *Index* - The index of this element in the array.
* *Array* - The array itself.
-All of these are optional, but you will need at least the 'element' parameter in most cases.
+All of these are optional, but you will need at least the "Element" parameter in most cases.
```
// native forEach
function printElement( elem ) {
- console.log( elem );
+ console.log( elem );
}
function printElementAndIndex( elem, index ) {
- console.log( "Index " + index + ": " + elem );
+ console.log( "Index " + index + ": " + elem );
}
function negateElement( elem, index, array ) {
- array[ index ] = -elem;
+ array[ index ] = -elem;
}
myArray = [ 1, 2, 3, 4, 5 ];
View
142 page/javascript-101/closures.md
@@ -2,143 +2,119 @@
title: Closures
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
Closures are an extension of the concept of scope. With closures, functions have access to variables that were available in the scope where the function was created. If that seems confusing, don’t worry: closures are generally best understood by example.
-As shown in the [Functions](/functions) section, functions have access to changing variable values. The same sort of behavior exists with functions defined within loops &#8212; the function "sees" the change in the variable's value even after the function is defined, resulting in each function referencing the last value stored in the variable.
+As shown in the [Functions](/functions/) section, functions have access to changing variable values. The same sort of behavior exists with functions defined within loops the function "sees" the change in the variable's value even after the function is defined, resulting in each function referencing the last value stored in the variable.
```
-// Each function executed within the loop will reference
+// Each function executed within the loop will reference
// the last value stored in i (5).
-// this won't behave as we want it to -
-// every 100 milliseconds, 5 will alert
+// This won't behave as we want it to - every 100 milliseconds, 5 will alert
for ( var i = 0; i < 5; i++ ) {
-
- setTimeout(function() {
-
- alert( i );
-
- }, i * 100 );
-
+ setTimeout(function() {
+ alert( i );
+ }, i * 100 );
}
```
-Closures can be used to prevent this by creating a unique scope for each iteration &#8212; storing each unique value of the variable within its scope.
+Closures can be used to prevent this by creating a unique scope for each iteration storing each unique value of the variable within its scope.
```
// Using a closure to create a new private scope
// fix: “close” the value of i inside createFunction, so it won't change
var createFunction = function( i ) {
-
- return function() {
-
- alert( i );
-
- };
-
+ return function() {
+ alert( i );
+ };
};
for ( var i = 0; i < 5; i++ ) {
-
- setTimeout( createFunction( i ), i * 100 );
-
+ setTimeout( createFunction( i ), i * 100 );
}
```
Closures can also be used to resolve issues with the `this` keyword, which is unique to each scope:
```
-//Using a closure to access inner and outer object instances simultaneously
+// Using a closure to access inner and outer object instances simultaneously.
var outerObj = {
- myName : "outer",
- outerFunction : function() {
-
- // provide a reference to outerObj through innerFunction"s closure
- var self = this;
-
- var innerObj = {
- myName : "inner",
- innerFunction : function() {
-
- console.log( self.myName, this.myName ); // "outer inner"
-
- }
- };
-
- innerObj.innerFunction();
-
- console.log( this.myName ); // "outer"
- }
+ myName: "outer",
+ outerFunction: function() {
+ // provide a reference to outerObj through innerFunction"s closure
+ var self = this;
+ var innerObj = {
+ myName: "inner",
+ innerFunction: function() {
+ console.log( self.myName, this.myName ); // "outer inner"
+ }
+ };
+
+ innerObj.innerFunction();
+
+ console.log( this.myName ); // "outer"
+ }
};
outerObj.outerFunction();
```
-## `Function.bind`
-Closures can be particularly useful when dealing with callbacks. However, it is often better to use `Function.bind`, which will avoid any overhead associated with scope traversal.
+## Function.bind
+
+Closures can be particularly useful when dealing with callbacks. However, it is often better to use `Function.bind`, which will avoid any overhead associated with scope traversal.
`Function.bind` is used to create a new function. When called, the new function then calls itself in the context of the supplied `this` value, using a given set of arguments that will precede any arguments provided when the new function was initially called.
-As `bind` is a recent addition to ECMAScript 5, it may not be present in all browsers, which is something to be wary of when deciding whether to use it. However, it's possible to work around support by using [this shim](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind) from MDN:
+As `.bind()` is a recent addition to ECMAScript 5, it may not be present in all browsers, which is something to be wary of when deciding whether to use it. However, it's possible to work around support by using [this shim](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind) from MDN:
```
// Shim from MDN
if (!Function.prototype.bind) {
- Function.prototype.bind = function( oThis ) {
-
- if (typeof this !== "function") {
-
- // closest thing possible to the ECMAScript 5 internal
- // IsCallable function
- throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
-
- }
-
- var fSlice = Array.prototype.slice,
- aArgs = fSlice.call( arguments, 1 ),
- fToBind = this,
- fNOP = function() {},
- fBound = function() {
+ Function.prototype.bind = function( oThis ) {
- return fToBind.apply( this instanceof fNOP
- ? this
- : oThis || window,
- aArgs.concat( fSlice.call( arguments ) ) );
+ if (typeof this !== "function") {
+ // closest thing possible to the ECMAScript 5 internal
+ // IsCallable function
+ throw new TypeError( "Function.prototype.bind - what is trying to be bound is not callable" );
+ }
- };
+ var fSlice = Array.prototype.slice,
+ aArgs = fSlice.call( arguments, 1 ),
+ fToBind = this,
+ fNOP = function() {},
+ fBound = function() {
+ return fToBind.apply( this instanceof fNOP
+ ? this
+ : oThis || window,
+ aArgs.concat( fSlice.call( arguments ) ) );
+ };
- fNOP.prototype = this.prototype;
- fBound.prototype = new fNOP();
+ fNOP.prototype = this.prototype;
- return fBound;
-
- };
+ fBound.prototype = new fNOP();
+ return fBound;
+ };
}
```
-One of the simplest uses of `bind` is making a function that is called with a particular value for `this`, regardless of how it's called. A common mistake developers make is attempting to extract a method from an object, then later calling that method and expecting it to the use the origin object as its `this`. However, this can be solved by creating a bound function using the original object as demonstrated below:
+One of the simplest uses of `.bind()` is making a function that is called with a particular value for `this`, regardless of how it's called. A common mistake developers make is attempting to extract a method from an object, then later calling that method and expecting it to the use the origin object as its `this`. However, this can be solved by creating a bound function using the original object as demonstrated below:
```
-//let's manipulate "this" with a basic example
+// Let's manipulate "this" with a basic example.
var user = "johnsmith";
var module = {
-
- getUser: function() {
-
- return this.user;
-
- },
-
- user: "janedoe"
-
+ getUser: function() {
+ return this.user;
+ },
+ user: "janedoe"
};
-// module.getUser() is called where "module" is "this"
+// module.getUser() is called where "module" is "this"
// and "module.user" is returned.
// janedoe
View
85 page/javascript-101/conditional-code.md
@@ -2,10 +2,10 @@
title: Conditional Code
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
-Sometimes a block of code should only be run under certain conditions. Flow control &#8212; via `if` and `else` blocks &#8212; lets you run code if certain conditions have been met.
+Sometimes a block of code should only be run under certain conditions. Flow control via `if` and `else` blocks lets you run code if certain conditions have been met.
```
// Flow control
@@ -13,32 +13,32 @@ var foo = true;
var bar = false;
if ( bar ) {
- // this code will never run
- console.log("hello!");
+ // this code will never run
+ console.log( "hello!" );
}
if ( bar ) {
- // this code won't run
+ // this code won't run
} else {
- if ( foo ) {
+ if ( foo ) {
- // this code will run
+ // this code will run
- } else {
+ } else {
- // this code would run if foo and bar were both false
+ // this code would run if foo and bar were both false
- }
+ }
}
```
While curly braces aren't strictly required around single-line `if` statements, using them consistently, even when they aren't strictly required, makes for vastly more readable code.
-Be mindful not to define functions with the same name multiple times within separate if/else blocks, as doing so may not have the expected result.
+Be mindful not to define functions with the same name multiple times within separate `if`/`else` blocks, as doing so may not have the expected result.
## Truthy and Falsy Things
@@ -48,9 +48,9 @@ In order to use flow control successfully, it's important to understand which ki
// Values that evaluate to true
"0";
"any string";
-[]; // an empty array
-{}; // an empty object
-1; // any non-zero number
+[]; // an empty array
+{}; // an empty object
+1; // any non-zero number
```
```
@@ -58,8 +58,8 @@ In order to use flow control successfully, it's important to understand which ki
""; // an empty string
NaN; // JavaScript's "not-a-number" variable
null;
-undefined; // be careful -- undefined can be redefined!
-0; // the number zero
+undefined; // be careful -- undefined can be redefined!
+0; // the number zero
```
## Conditional Variable Assignment with the Ternary Operator
@@ -77,27 +77,22 @@ While the ternary operator can be used without assigning the return value to a v
## Switch Statements
-Rather than using a series of `if`/`else` blocks, sometimes it can be useful to use a `switch` statement instead. `Switch` statements look at the value of a variable or expression, and run different blocks of code depending on the value.
+Rather than using a series of `if`/`else` blocks, sometimes it can be useful to use a `switch` statement instead. `switch` statements look at the value of a variable or expression, and run different blocks of code depending on the value.
```
// A switch statement
switch ( foo ) {
- case "bar":
+ case "bar":
+ alert( "the value was bar -- yay!" );
+ break;
- alert("the value was bar -- yay!");
+ case "baz":
+ alert( "boo baz :(" );
+ break;
- break;
-
- case "baz":
-
- alert("boo baz :(");
-
- break;
-
- default:
-
- alert("everything else is just ok");
+ default:
+ alert( "everything else is just ok" );
}
```
@@ -107,35 +102,29 @@ Switch statements have somewhat fallen out of favor in JavaScript, because often
```
var stuffToDo = {
- "bar" : function() {
-
- alert("the value was bar -- yay!");
-
- },
-
- "baz" : function() {
-
- alert("boo baz :(");
-
- },
-
- "default" : function() {
+ "bar": function() {
+ alert( "the value was bar -- yay!" );
+ },
- alert("everything else is just ok");
+ "baz": function() {
+ alert( "boo baz :(" );
+ },
- }
+ "default": function() {
+ alert( "everything else is just ok" );
+ }
};
if ( stuffToDo[ foo ] ) {
- stuffToDo[ foo ]();
+ stuffToDo[ foo ]();
} else {
- stuffToDo["default"]();
+ stuffToDo["default"]();
}
```
-Objects are covered further in the [Types](/types) and [Objects](/objects) sections.
+Objects are covered further in the [Types](/types/) and [Objects](/objects/) sections.
View
72 page/javascript-101/functions.md
@@ -2,7 +2,7 @@
title: Functions
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
@@ -11,59 +11,51 @@ Functions contain blocks of code that need to be executed repeatedly. Functions
Functions can be created in a variety of ways, two of which are shown below:
```
-// Function Declaration
+// Function declaration.
function foo() {
-
- /* do something */
-
+ /* do something */
}
```
```
-// Named Function Expression
+// Named function expression.
var foo = function() {
-
- /* do something */
-
+ /* do something */
}
```
## Using Functions
```
-// A simple function
-var greet = function( person, greeting ) {
-
- var text = greeting + ", " + person;
-
- console.log( text );
+// A simple function.
+var greet = function( person, greeting ) {
+ var text = greeting + ", " + person;
+ console.log( text );
};
greet( "Rebecca", "Hello" );
```
```
-// A function that returns a value
-var greet = function( person, greeting ) {
-
- var text = greeting + ", " + person;
-
- return text;
+// A function that returns a value.
+var greet = function( person, greeting ) {
+ var text = greeting + ", " + person;
+ return text;
};
console.log( greet( "Rebecca", "hello" ) ); // "hello, Rebecca"
```
```
-// A function that returns another function
-var greet = function( person, greeting ) {
- var text = greeting + ", " + person;
+// A function that returns another function.
- return function() {
- console.log( text );
- };
+var greet = function( person, greeting ) {
+ var text = greeting + ", " + person;
+ return function() {
+ console.log( text );
+ };
};
var greeting = greet( "Rebecca", "Hello" );
@@ -73,14 +65,13 @@ greeting();
## Immediately-Invoked Function Expression (IIFE)
-A common pattern in JavaScript is the immediately-invoked function expression. This pattern creates a function expression and then immediately executes the function. This pattern is extremely useful for cases where you want to avoid polluting the global namespace with code &#8212; no variables declared inside of the function are visible outside of it.
+A common pattern in JavaScript is the immediately-invoked function expression. This pattern creates a function expression and then immediately executes the function. This pattern is extremely useful for cases where you want to avoid polluting the global namespace with code no variables declared inside of the function are visible outside of it.
```
-// An immediately-invoked function expression
-(function() {
-
- var foo = "Hello world";
+// An immediately-invoked function expression.
+(function() {
+ var foo = "Hello world";
})();
console.log( foo ); // undefined!
@@ -88,18 +79,19 @@ console.log( foo ); // undefined!
## Functions as Arguments
-In JavaScript, functions are "first-class citizens" &#8212; they can be assigned to variables or passed to other functions as arguments. Passing functions as arguments is an extremely common idiom in jQuery.
+In JavaScript, functions are "first-class citizens" they can be assigned to variables or passed to other functions as arguments. Passing functions as arguments is an extremely common idiom in jQuery.
```
-// Passing an anonymous function as an argument
+// Passing an anonymous function as an argument.
+
var myFn = function( fn ) {
- var result = fn();
- console.log( result );
+ var result = fn();
+ console.log( result );
};
// logs "hello world"
myFn( function() {
- return "hello world";
+ return "hello world";
});
```
@@ -107,12 +99,12 @@ myFn( function() {
// Passing a named function as an argument
var myFn = function( fn ) {
- var result = fn();
- console.log( result );
+ var result = fn();
+ console.log( result );
};
var myOtherFn = function() {
- return "hello world";
+ return "hello world";
};
myFn( myOtherFn ); // "hello world"
View
71 page/javascript-101/getting-started.md
@@ -2,70 +2,75 @@
title: Getting Started
level: Beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
-##Anatomy of a Web Page
+## Anatomy of a Web Page
+
Before diving into JavaScript, it helps to understand how it aligns with the other web technologies.
-###HTML is for Content
-HTML is a markup language used to define and describe content. Whether it be a blog post, a search engine result or an e-commerce site, the core content of a web page is written in HTML. A semantic markup, HTML is used to describe content in universal terms (headers, paragraphs, images, etc.).
+### HTML is for Content
+
+HTML is a markup language used to define and describe content. Whether it be a blog post, a search engine result or an e-commerce site, the core content of a web page is written in HTML. A semantic markup, HTML is used to describe content in universal terms (headers, paragraphs, images, etc.)
###CSS is for Presentation
-CSS is a supplemental language that applies style to HTML documents. CSS is all about making content look better by defining fonts, colors and other visual aesthetics. The power of CSS comes from the fact that styling is not intermingled with content. This means you can apply different styles to the same piece of content, which is critical when building responsive websites that look good across a range of devices.
+
+CSS is a supplemental language that applies style to HTML documents. CSS is all about making content look better by defining fonts, colors, and other visual aesthetics. The power of CSS comes from the fact that styling is not intermingled with content. This means you can apply different styles to the same piece of content, which is critical when building responsive websites that look good across a range of devices.
###JavaScript is for Interactivity
+
In the browser, JavaScript adds interactivity and behavior to HTML content. Without JavaScript, web pages would be static and boring. JavaScript helps bring a web page to life.
Look at this simple HTML page that includes CSS and JavaScript to see how it all fits together:
```
-<!DOCTYPE HTML>
-<html lang="en-US">
+<!doctype html>
+<html lang="en">
<head>
- <meta charset="UTF-8">
- <title>Hello World</title>
- <!-- CSS for presentation -->
- <style type="text/css">
- h1 { font-size: 14px; color: hotpink; }
- button { color: red; }
- </style>
+ <meta charset="utf-8">
+ <title>Hello World</title>
+ <!-- CSS for presentation -->
+ <style>
+ h1 { font-size: 14px; color: hotpink; }
+ button { color: red; }
+ </style>
</head>
<body>
- <h1>Hello World</h1>
- <button>Click Me!</button>
-
- <!-- JavaScript for interactivity -->
- <script>
- // get a handle on the first button element
- // in the document.
- var button = document.querySelector('button');
- // if a user clicks on it, say hello!
- button.addEventListener('click', function(ev) {
- alert('Hello');
- }, false);
- </script>
+ <h1>Hello World</h1>
+ <button>Click Me!</button>
+ <!-- JavaScript for interactivity -->
+ <script>
+ // Get a handle on the first button element in the document.
+ var button = document.querySelector( "button" );
+ // If a user clicks on it, say hello!
+ button.addEventListener( "click", function( ev ) {
+ alert( "Hello" );
+ }, false);
+ </script>
</body>
</html>
```
In the example above, HTML is used to describe the content. The "Hello World" text is described as a heading with the `<h1>` tag and "Click Me!" is described as a button with the `<button>` tag. The `<style>` block contains CSS that changes the font-size and color of the header text. The `<script>` block contains JavaScript that adds interactivity to the button. When a user clicks on the button, an alert message will appear that says "Hello!".
-##A Scripting Language for the Web
-JavaScript was originally designed to add interactivity to web pages, not to be a general programming language, which makes it a scripting language. [Scripting languages](http://en.wikipedia.org/wiki/Scripting_language) are regarded to be more productive than general languages because they are optimized for their specific domain (in this case, the web browser). However, recent advancements have brought JavaScript to the server-side (via [Node.js](http://nodejs.org/)) so it can now be used in place of languages like PHP, Ruby or ASP. This guide will focus exclusively on JavaScript running in the browser with jQuery.
+## A Scripting Language for the Web
-The name "JavaScript" is a bit misleading. Despite the similarity in name, JavaScript has no relationship with [Java](http://en.wikipedia.org/wiki/Java_\(programming_language\)), a general purpose language. JavaScript is based on an Open Web standard called [ECMAScript](http://en.wikipedia.org/wiki/ECMAScript). Standards-based languages are not controlled by any one entity or corporation - instead, developers work together to define the language, which is why JavaScript will run in *every* web browser regardless of the operating system or device.
+JavaScript was originally designed to add interactivity to web pages, not to be a general programming language, which makes it a scripting language. [Scripting languages](http://en.wikipedia.org/wiki/Scripting_language) are regarded to be more productive than general languages because they are optimized for their specific domain (in this case, the web browser). However, recent advancements have brought JavaScript to the server-side (via [Node.js](http://nodejs.org/)) so it can now be used in place of languages like PHP, Ruby, or ASP. This guide will focus exclusively on JavaScript running in the browser with jQuery.
+
+The name "JavaScript" is a bit misleading. Despite the similarity in name, JavaScript has no relationship with [Java](http://en.wikipedia.org/wiki/Java_\(programming_language\)), a general purpose language. JavaScript is based on an Open Web standard called [ECMAScript](http://en.wikipedia.org/wiki/ECMAScript). Standards-based languages are not controlled by any one entity or corporation – instead, developers work together to define the language, which is why JavaScript will run in *every* web browser regardless of the operating system or device.
+
+## What You Need to Get Started with JavaScript and jQuery
-##What You Need to Get Started with JavaScript and jQuery
1. Web Browser
2. Text Editor
3. Developer Tools (optional)
One of JavaScript's greatest strengths is its simplicity. It can be written and run on any operating system, and the only requirements are a web browser and a text editor. There are also numerous tools that can make JavaScript development more productive, but they are completely optional.
-###Developer Tools
-Commonly referred to as "developer tools," many browsers ship with built-in features that provide better insight into JavaScript and jQuery while they run in the browser. Although they aren't required, you may find developer tools helpful when it comes to debugging errors in your code. Check out these browsers' developer tools:
+### Developer Tools
+
+Commonly referred to as "developer tools," many browsers ship with built-in features that provide better insight into JavaScript and jQuery while they run in the browser. Although they aren't required, you may find developer tools helpful when it comes to debugging errors in your code. Check out these browsers' developer tools:
- [Apple Safari](https://developer.apple.com/technologies/safari/developer-tools.html)
- [Google Chrome Developer Tools](https://developers.google.com/chrome-developer-tools/)
View
78 page/javascript-101/loops.md
@@ -2,7 +2,7 @@
title: Loops
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
Loops let a block of code run a certain number of times:
@@ -12,12 +12,12 @@ Loops let a block of code run a certain number of times:
// logs "try 0", "try 1", ..., "try 4"
for ( var i = 0; i < 5; i++ ) {
- console.log( "try " + i );
+ console.log( "try " + i );
}
```
-Note that in loops, the variable i is not "scoped" to the loop block even though the keyword `var` is used before the variable name. Scope is covered in more depth in the [Scope](/scope) section.
+Note that in loops, the variable i is not "scoped" to the loop block even though the keyword `var` is used before the variable name. Scope is covered in more depth in the [Scope](/scope/) section.
## The `for` loop
@@ -26,7 +26,7 @@ A `for` loop is made up of four statements and has the following structure:
```
for ( [initialisation]; [conditional]; [iteration] ) {
- [ loopBody ]
+ [ loopBody ]
}
```
@@ -37,20 +37,16 @@ The _conditional_ statement is executed before each iteration, and its return va
The _iteration_ statement is executed at the end of each iteration and gives you an opportunity to change the state of important variables. Typically, this will involve incrementing or decrementing a counter and thus bringing the loop closer to its end.
-The _loopBody_ statement is what runs on every iteration. It can contain anything. Typically, there will be multiple statements that need to be executed, and should be wrapped in a block ( {...}).
+The _loopBody_ statement is what runs on every iteration. It can contain anything. Typically, there will be multiple statements that need to be executed, and should be wrapped in a block ( {...} ).
Here's a typical `for` loop:
```
// A typical for loop
for (var i = 0, limit = 100; i < limit; i++) {
-
- // This block will be executed 100 times
-
- console.log( 'Currently at ' + i );
-
- // Note: the last log will be "Currently at 99"
-
+ // This block will be executed 100 times
+ console.log( 'Currently at ' + i );
+ // Note: the last log will be "Currently at 99"
}
```
@@ -61,7 +57,7 @@ A while loop is similar to an `if` statement, except that its body will keep exe
```
while ( [conditional] ) {
- [loopBody]
+ [loopBody]
}
```
@@ -71,15 +67,12 @@ Here's a typical `while` loop:
```
// A typical while loop
var i = 0;
-
while ( i < 100 ) {
+ // This block will be executed 100 times
+ console.log( "Currently at " + i );
- // This block will be executed 100 times
- console.log( "Currently at " + i );
-
- // increment i
- i++;
-
+ // increment i
+ i++;
}
```
@@ -88,12 +81,9 @@ Notice that the counter is incrementing within the loop's body. It's possible to
```
// A while loop with a combined conditional and incrementer
var i = -1;
-
while ( ++i < 100 ) {
-
- // This block will be executed 100 times
- console.log( "Currently at " + i );
-
+ // This block will be executed 100 times
+ console.log( "Currently at " + i );
}
```
@@ -106,7 +96,7 @@ This is almost exactly the same as the `while` loop, except for the fact that th
```
do {
- [ loopBody ]
+ [ loopBody ]
} while ( [conditional] )
```
@@ -115,10 +105,9 @@ Here's a `do-while` loop:
```
// A do-while loop
do {
-
- // Even though the condition evaluates to false
- // this loop's body will still execute once.
- alert("Hi there!");
+ // Even though the condition evaluates to false
+ // this loop's body will still execute once.
+ alert( "Hi there!" );
} while ( false );
```
@@ -127,36 +116,29 @@ These types of loops are quite rare since only few situations require a loop tha
## Breaking and continuing
-Usually, a loop's termination will result from the conditional statement not evaluating to true, but it is possible to stop a loop in its tracks from within the loop's body with the break statement.
+Usually, a loop's termination will result from the conditional statement not evaluating to true, but it is possible to stop a loop in its tracks from within the loop's body with the `break` statement.
```
// Stopping a loop
for ( var i = 0; i < 10; i++ ) {
-
- if ( something ) {
-
- break;
-
- }
-
+ if ( something ) {
+ break;
+ }
}
```
-You may also want to continue the loop without executing more of the loop's body. This is done using the continue statement.
+You may also want to continue the loop without executing more of the loop's body. This is done using the `continue` statement.
```
// Skipping to the next iteration of a loop
for ( var i = 0; i < 10; i++ ) {
+ if ( something ) {
+ continue;
+ }
- if ( something ) {
-
- continue;
-
- }
-
- // The following statement will only be executed
- // if the conditional 'something' has not been met
- console.log("I have been reached");
+ // The following statement will only be executed
+ // if the conditional 'something' has not been met
+ console.log( "I have been reached" );
}
```
View
22 page/javascript-101/objects.md
@@ -2,20 +2,21 @@
title: Objects
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
Objects contain one or more key-value pairs. The key portion can be any string. The value portion can be any type of value: a number, a string, an array, a function, or even another object. When one of these values is a function, it’s called a method of the object. Otherwise, they are called properties.
-As it turns out, nearly everything in JavaScript is an object &#8212; arrays, functions, numbers, even strings &#8212; and they all have properties and methods.
+As it turns out, nearly everything in JavaScript is an object arrays, functions, numbers, even strings and they all have properties and methods.
```
-// Creating an object literal
+// Creating an object literal.
+
var myObject = {
- sayHello : function() {
- console.log("hello");
- },
- myName : "Rebecca"
+ sayHello: function() {
+ console.log( "hello" );
+ },
+ myName: "Rebecca"
};
myObject.sayHello(); // "hello"
@@ -26,10 +27,9 @@ console.log( myObject.myName ); // "Rebecca"
When creating object literals, note that the key portion of each key-value pair can be written as any valid JavaScript identifier, a string (wrapped in quotes), or a number:
```
-// test
var myObject = {
- validIdentifier: 123,
- "some string": 456,
- 99999: 789
+ validIdentifier: 123,
+ "some string": 456,
+ 99999: 789
};
```
View
27 page/javascript-101/operators.md
@@ -2,7 +2,7 @@
title: Operators
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
Basic operators allow you to manipulate values.
@@ -24,17 +24,13 @@ console.log( foo + " " + bar ); // "hello world"
```
// Incrementing and decrementing
// The pre-increment operator increments the operand before any further processing.
-// pre-increment:
var i = 1;
-
-console.log( ++i ); // 2
+console.log( ++i ); // 2 - because i was incremented before evaluation
console.log( i ); // 2
// The post-increment operator increments the operand after processing it.
-// post-increment:
var i = 1;
-
-console.log( i++ ); // 1 - because i was 1
+console.log( i++ ); // 1 - because i was evaluated to 1 and _then_ incremented
console.log( i ); // 2 - incremented after using it
```
@@ -100,12 +96,11 @@ You'll sometimes see developers use these logical operators for flow control ins
foo && doSomething( foo );
// set bar to baz if baz is truthy;
-// otherwise, set it to the return
-// value of createBar()
+// otherwise, set it to the return value of createBar()
var bar = baz || createBar();
```
-This style is quite elegant and pleasantly terse; that said, it can be really hard to read or use, especially for beginners. See the section on truthy and falsy things in the [Conditional Code](/conditional-code) article for more about evaluating truthiness.
+This style is quite elegant and pleasantly terse; that said, it can be really hard to read or use, especially for beginners. See the section on truthy and falsy things in the [Conditional Code](/conditional-code/) article for more about evaluating truthiness.
## Comparison Operators
@@ -118,16 +113,16 @@ var bar = 0;
var baz = "1";
var bim = 2;
-foo == bar; // false
-foo != bar; // true
-foo == baz; // true; but note that the types are different
+foo == bar; // false
+foo != bar; // true
+foo == baz; // true; but note that the types are different
foo === baz; // false
foo !== baz; // true
foo === parseInt( baz ); // true
-foo > bim; // false
-bim > baz; // true
-foo <= baz; // true
+foo > bim; // false
+bim > baz; // true
+foo <= baz; // true
```
For more information about comparison operators, visit the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators "MDN - Comparison Operators").
View
52 page/javascript-101/running-code.md
@@ -2,16 +2,16 @@
title: Running Code
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
### External
-The first and recommended option is to write code in an external file (with a ".js" extension), which can then be included on our web page using an HTML `<script>` tag and pointing the `src` attribute to the file's location. Having JavaScript in a separate file will reduce code duplication if you want to reuse it on other pages. It will also allow the browser to cache the file on the remote client's computer, decreasing page load time.
+The first and recommended option is to write code in an external file (with a `.js` extension), which can then be included on our web page using an HTML `<script>` tag and pointing the `src` attribute to the file's location. Having JavaScript in a separate file will reduce code duplication if you want to reuse it on other pages. It will also allow the browser to cache the file on the remote client's computer, decreasing page load time.
```
-<!--Code is written in a .js file, then included via the script tag src attribute.-->
+<!-- Code is written in a .js file, then included via the script tag src attribute. -->
<script src="/path/to/example.js"></script>
```
### Inline
@@ -19,9 +19,9 @@ The first and recommended option is to write code in an external file (with a ".
The second option is to inline the code directly on the web page. This is also achieved using HTML `<script>` tags, but instead of pointing the `src` attribute to a file, the code is placed between the tags. While there are use cases for this option, the majority of the time it is best to keep our code in an external file as described above.
```
-<!--Embed code directly on a web page using script tags.-->
-<script type="text/javascript">
- alert("Hello World!");
+<!-- Embed code directly on a web page using script tags. -->
+<script>
+ alert( "Hello World!" );
</script>
```
@@ -30,7 +30,7 @@ The second option is to inline the code directly on the web page. This is also a
The last option is to use the event handler attributes of HTML elements. This method is strongly discouraged:
```
-<!--Inline code directly on HTML elements being clicked.-->
+<!-- Inline code directly on HTML elements being clicked. -->
<a href="javascript:alert(&#34;Hello World!&#34;);">Click Me!</a>
<button onClick="alert(&#34;Good Bye World&#34;);">Click Me Too!</a>
```
@@ -40,19 +40,17 @@ The last option is to use the event handler attributes of HTML elements. This me
Placement of the previous two options is important and can vary depending on the situation. If you are including JavaScript that doesn't access the elements on the page, you can safely place the script before the closing HTML `<head>` tag. However, if the code will interact with the elements on the page, you have to make sure those elements exist at the time the script is executed. This common pitfall can be seen in the example below. The script for finding the element with the ID "hello-world" will be executed before the element is defined in the document.
```
-<!--Attempting to access an element too early will have unexpected results.-->
+<!-- Attempting to access an element too early will have unexpected results. -->
<!doctype html>
<html>
<head>
-<script type="text/javascript">
-
- var title = document.getElementById("hello-world");
- console.log( title );
-
-</script>
+ <script>
+ var title = document.getElementById( "hello-world" );
+ console.log( title );
+ </script>
</head>
<body>
- <h1 id="hello-world">Hello World</h1>
+ <h1 id="hello-world">Hello World</h1>
</body>
</html>
```
@@ -60,26 +58,18 @@ Placement of the previous two options is important and can vary depending on the
It is a common pattern to move scripts to the bottom of the page, prior to the closing HTML `<body>` tag. This will guarantee that elements are defined when the script is executed.
```
-<!--Moving the script to the bottom of the page will make sure the element exists.-->
+<!-- Moving the script to the bottom of the page will -->
+<!-- make sure the element exists. -->
<!doctype html>
<html>
<head>
</head>
<body>
- <h1 id="hello-world">Hello World</h1>
- <script type="text/javascript">
-
- var title = document.getElementById("hello-world");
- console.log( title );
-
- </script>
+ <h1 id="hello-world">Hello World</h1>
+ <script>
+ var title = document.getElementById( "hello-world" );
+ console.log( title );
+ </script>
</body>
</html>
-```
-
-
-
-
-
-
-
+```
View
102 page/javascript-101/scope.md
@@ -8,7 +8,7 @@ attribution:
"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.
-There are two types of scopes in JavaScript: Global and local. Lets talk about each of them in turn.
+There are two types of scopes in JavaScript: global and local. Let's talk about each of them in turn.
## Global Scope
@@ -21,24 +21,25 @@ 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;
+ 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()`.
+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
+## 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;
+ x = 5;
});
console.log( x ); // 5
```
@@ -49,8 +50,8 @@ Secondly, Immediately-Invoked Funcion Expressions provide a way to avoid global
```
(function() {
- var jQuery = { /* all my methods go here */ };
- window.jQuery = jQuery.
+ var jQuery = { /* all my methods go here */ };
+ window.jQuery = jQuery.
})();
```
@@ -60,74 +61,78 @@ Because local scope works through functions, any functions defined within anothe
```
function outer() {
- var x = 5;
- function inner() {
- console.log( x );
- }
+ var x = 5;
+
+ function inner() {
+ console.log( x );
+ }
- inner(); // 5
+ inner(); // 5
}
```
-But the `outer()` function doesn't have access to any variables declared within `inner()`:
+But the `.outer()` function doesn't have access to any variables declared within `.inner()`:
```
function outer() {
- var x = 5;
+ var x = 5;
- function inner() {
- console.log( x );
- var y = 10;
- }
+ function inner() {
+ console.log( x );
+ var y = 10;
+ }
- inner(); // 5
+ inner(); // 5
- console.log( y ); // ReferenceError: y is not defined
+ 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 &#8212; 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.
+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.
```
-// Functions have access to variables defined in the same scope
+// Functions have access to variables defined in the same scope.
+
var foo = "hello";
var sayHello = function() {
- console.log( foo );
+ console.log( foo );
};
-sayHello(); // "hello"
+sayHello(); // "hello"
-console.log( foo ); // "hello"
+console.log( foo ); // "hello"
```
Variables with the same name can exist in different scopes with different values:
+
```
var foo = "world";
var sayHello = function() {
- var foo = "hello";
- console.log( foo );
+ var foo = "hello";
+ console.log( foo );
};
-sayHello(); // "hello"
+sayHello(); // "hello"
-console.log( foo ); // "world"
+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.
```
var myFunction = function() {
- var foo = "hello";
- var myFn = function() {
- console.log( foo );
- };
- foo = "world";
- return myFn;
+ var foo = "hello";
+ var myFn = function() {
+ console.log( foo );
+ };
+ foo = "world";
+ return myFn;
};
var f = myFunction();
+
f(); // "world"
```
@@ -135,39 +140,36 @@ Here's a more complex example of scopes at play:
```
(function() {
- var baz = 1;
- var bim = function() {
- console.log( baz );
- };
+ var baz = 1;
- bar = function() {
- console.log( baz );
- };
+ var bim = function() {
+ console.log( baz );
+ };
- bar = function() {
- console.log( baz );
- };
+ bar = function() {
+ console.log( baz );
+ };
})();
```
In this instance, running:
```
-console.log( baz ); // baz is not defined outside of the function
+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.
```
-bar(); // 1
+bar(); // 1
```
-`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.
+`.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(); // ReferenceError: bim is not defined
+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.
+`.bim()` was only defined within the function, so does not exist on the global object as it was defined locally.
View
18 page/javascript-101/syntax-basics.md
@@ -8,11 +8,12 @@ attribution:
### Comments
-JavaScript has support for single and multi-line comments. Comments are ignored by the JavaScript engine and therefore have no side-effects on the outcome of the program. Use comments to document the code for other developers. Libraries like [JSDoc](http://code.google.com/p/jsdoc-toolkit/, "JSDoc Toolkit") are available to help generate project documentation pages based on commenting conventions.
+JavaScript has support for single- and multi-line comments. Comments are ignored by the JavaScript engine and therefore have no side-effects on the outcome of the program. Use comments to document the code for other developers. Libraries like [JSDoc](http://code.google.com/p/jsdoc-toolkit/, "JSDoc Toolkit") are available to help generate project documentation pages based on commenting conventions.
```
// Single and multi line comments.
-// this is an example of a single line comment.
+
+// This is an example of a single line comment.
/*
* this is an example
@@ -29,7 +30,6 @@ Whitespace is also ignored in JavaScript. There are many tools that will strip o
```
// Whitespace is insignificant.
var hello = "Hello";
-
var world = "World!";
```
@@ -54,7 +54,7 @@ var foo=function() {for(var i=0;i<10;i++){alert(i);}};foo();
### Reserved Words
-There are a handful of reserved words that can't be used when declaring user-defined variables and functions. Some of these reserved words are currently implemented, some are saved for future use, and others are reserved for historical reasons. A list of words and in-depth explanations for each can be found on the [MDN JavaScript Reference](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Reserved_Words "MDN Reserved Words.") site.
+There are a handful of reserved words that can't be used when declaring user-defined variables and functions. Some of these reserved words are currently implemented, some are saved for future use, and others are reserved for historical reasons. A list of reserved words can be found [here](/javascript-101/reserved-words/), and in-depth explanations for each can be found on the [MDN JavaScript Reference](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Reserved_Words "MDN Reserved Words.") site.
### Identifiers
@@ -77,8 +77,7 @@ var _my_awesome_variable_$ = "e";
### Variable definition
-Variables can be defined using multiple `var` statements, or in a single
-combined var statement.
+Variables can be defined using multiple `var` statements, or in a single combined var statement.
```
// this works
@@ -88,12 +87,11 @@ var test3 = test2( test );
// and so does this
var test4 = 1,
- test5 = function() { ... },
- test6 = test2( test );
+ test5 = function() { ... },
+ test6 = test2( test );
```
-Variables can be declared without assigning them a value. The value of a
-variable declared without a value is `undefined`.
+Variables can be declared without assigning them a value. The value of a variable declared without a value is `undefined`.
```
var x;
View
20 page/javascript-101/testing-type.md
@@ -2,21 +2,21 @@
title: Testing Type
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
-JavaScript offers a way to test the type of a variable. However, the result can be confusing &#8212; for example, the type of an array is "Object."
+JavaScript offers a way to test the type of a variable. However, the result can be confusing for example, the type of an array is "Object."
It's common practice to use the `typeof` operator when trying to determining the type of a specific value.
```
-// Testing the type of various variables
+// Testing the type of various variables.
var myFunction = function() {
- console.log("hello");
+ console.log( "hello" );
};
var myObject = {
- foo : "bar"
+ foo: "bar"
};
var myArray = [ "a", "b", "c" ];
var myString = "hello";
@@ -30,15 +30,13 @@ typeof myNumber; // "number"
typeof null; // "object" -- Careful!
if ( myArray.push && myArray.slice && myArray.join ) {
-
- // probably an array (this is called "duck typing")
+ // probably an array (this is called "duck typing")
}
if ( Object.prototype.toString.call( myArray ) === "[object Array]" ) {
-
- // Definitely an array!
- // This is widely considered as the most robust way
- // to determine if a specific value is an Array.
+ // Definitely an array!
+ // This is widely considered as the most robust way
+ // to determine if a specific value is an Array.
}
```
View
54 page/javascript-101/this-keyword.md
@@ -2,28 +2,28 @@
title: The "this" Keyword
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
In JavaScript, as in most object-oriented programming languages, `this` is a special keyword that is used in methods to refer to the object on which a method is being invoked. The value of `this` is determined using a simple series of steps:
-- If the function is invoked using `Function.call` or `Function.apply`, this will be set to the first argument passed to `call`/`apply`. If the first argument passed to `call`/`apply` is null or undefined, `this` will refer to the global object (which is the `window` object in web browsers).
-- If the function being invoked was created using `Function.bind`, `this` will be the first argument that was passed to `bind` at the time the function was created.
+- If the function is invoked using `Function.call` or `Function.apply`, this will be set to the first argument passed to `.call()`/`.apply()`. If the first argument passed to `.call()`/`.apply()` is `null` or `undefined`, `this` will refer to the global object (which is the `window` object in web browsers).
+- If the function being invoked was created using `Function.bind`, `this` will be the first argument that was passed to `.bind()` at the time the function was created.
- If the function is being invoked as a method of an object, `this` will refer to that object.
- Otherwise, the function is being invoked as a standalone function not attached to any object, and `this` will refer to the global object.
```
// A function invoked using Function.call
var myObject = {
- sayHello: function() {
- console.log( "Hi! My name is " + this.myName );
- },
- myName: "Rebecca"
+ sayHello: function() {
+ console.log( "Hi! My name is " + this.myName );
+ },
+ myName: "Rebecca"
};
var secondObject = {
- myName: "Colin"
+ myName: "Colin"
};
myObject.sayHello(); // "Hi! My name is Rebecca"
@@ -34,10 +34,10 @@ myObject.sayHello.call( secondObject ); // "Hi! My name is Colin"
// A function created using Function.bind
var myName = "the global object";
var sayHello = function() {
- console.log( "Hi! My name is " + this.myName );
+ console.log( "Hi! My name is " + this.myName );
};
var myObject = {
- myName: "Rebecca"
+ myName: "Rebecca"
};
var myObjectHello = sayHello.bind( myObject );
@@ -46,16 +46,16 @@ myObjectHello(); // "Hi! My name is Rebecca"
```
```
-// A function being attached to an object at runtime
+// A function being attached to an object at runtime.
var myName = "the global object";
var sayHello = function() {
- console.log( "Hi! My name is " + this.myName );
- };
+ console.log( "Hi! My name is " + this.myName );
+};
var myObject = {
- myName: "Rebecca"
+ myName: "Rebecca"
};
var secondObject = {
- myName: "Colin"
+ myName: "Colin"
};
myObject.sayHello = sayHello;
@@ -70,12 +70,12 @@ When invoking a function deep within a long namespace, it is often tempting to r
```
var myNamespace = {
- myObject: {
- sayHello: function() {
- console.log( "Hi! My name is " + this.myName );
- },
- myName: "Rebecca"
- }
+ myObject: {
+ sayHello: function() {
+ console.log( "Hi! My name is " + this.myName );
+ },
+ myName: "Rebecca"
+ }
};
var hello = myNamespace.myObject.sayHello;
@@ -87,12 +87,12 @@ You can, however, safely reduce everything up to the object on which the method
```
var myNamespace = {
- myObject: {
- sayHello: function() {
- console.log( "Hi! My name is " + this.myName );
- },
- myName: "Rebecca"
- }
+ myObject: {
+ sayHello: function() {
+ console.log( "Hi! My name is " + this.myName );
+ },
+ myName: "Rebecca"
+ }
};
var obj = myNamespace.myObject;
View
91 page/javascript-101/types.md
@@ -2,7 +2,7 @@
title: Types
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
@@ -11,27 +11,24 @@ Types in JavaScript fall into two categories: primitives or objects. Primitive t
* String
* Number
* Boolean
-* Null
-* Undefined
+* null
+* undefined
### String
Strings are text wrapped in single or double quotation marks. It is best practice to consistently use one or the other. There may be times when the string contains quotation marks that collide with the ones used to create the string. In this case, either escape the characters using a `\` backslash or use different quotes around the string.
```
-// Strings can created with double or single quotes.
+// Strings can be created with double or single quotes.
var a = "I am a string";
var b = 'So am I!';
-
alert( a );
-
alert( b );
```
```
// Sometimes a string may contain quotation marks.
var statement1 = 'He said "JavaScript is awesome!"';
-
var statement2 = "He said \"JavaScript is awesome!\"";
```
@@ -47,7 +44,7 @@ var num3 = 0.10;
```
### Boolean
-Boolean types are either true or false.
+Boolean types are either `true` or `false`.
```
// Boolean values.
@@ -55,14 +52,15 @@ var okay = true;
var fail = false;
```
-### Null and Undefined
+### null and undefined
-Null and undefined are special types in JavaScript. Null types are a value that represent the absence of a value, similar to many other programming languages. Undefined types represent a state in which no value has been assigned at all. This type is created in two ways: by using the undefined keyword or by not defining a value at all.
+`null` and `undefined` are special types in JavaScript. Null types are values that represent the absence of a value, similar to many other programming languages. Undefined types represent a state in which no value has been assigned at all. This type is created in two ways: by using the `undefined` keyword or by not defining a value at all.
```
-// Two ways to achieve an undefined value.
+// Define a null value.
var foo = null;
+// Two ways to achieve an undefined value.
var bar1 = undefined;
var bar2;
```
@@ -88,8 +86,8 @@ alert( person1.firstName + " " + person1.lastName );
// Creating an object with the object literal syntax:
var person2 = {
- firstName: "Jane",
- lastName: "Doe"
+ firstName: "Jane",
+ lastName: "Doe"
};
alert( person2.firstName + " " + person2.lastName );
@@ -99,27 +97,26 @@ alert( person2.firstName + " " + person2.lastName );
// As mentioned, objects can also have objects as a property.
var people = {};
-people["person1"] = person1;
-people["person2"] = person2;
+people[ "person1" ] = person1;
+people[ "person2" ] = person2;
-alert( people["person1"].firstName );
-alert( people["person2"].firstName );
+alert( people[ "person1" ].firstName );
+alert( people[ "person2" ].firstName );
```
-If a property is accessed that has not been defined, it will return a type of undefined.
+If a property is accessed that has not been defined, it will return a type of `undefined`.
```
// Properties that have not been created are undefined.
var person = { name: "John Doe" };
-
alert( person.email ); // => undefined
```
-Objects are covered further in the [Objects](/objects) section.
+Objects are covered further in the [Objects](/objects/) section.
### Array
-Arrays are a type of object that are ordered by the index of each item it contains. The index starts at zero and extends to however many items have been added, which is a property of the array known as the "length" of the array. Similar to a basic object, an array can be created with the array constructor or the shorthand syntax known as array literal.
+Arrays are a type of object that are ordered by the index of each item it contains. The index starts at zero and extends to however many items have been added, which is a property of the array known as the `length` of the array. Similar to a basic object, an array can be created with the array constructor or the shorthand syntax known as array literal.
```
// Creating an array with the constructor:
@@ -132,23 +129,18 @@ var bar = [];
There is an important distinction to be made between the two. Both an array constructor and an array literal can contain items to be added to the array upon creating it. However, if just a single numeric item is passed in, the array constructor will assume its length to be that value.
```
-// The array literal returns a bar.length value of 1:
+// The array literal returns a foo.length value of 1:
var foo = [ 100 ];
-
-// => 100
-alert( foo[0] );
-// => 1
-alert( foo.length );
+alert( foo[0] ); // => 100
+alert( foo.length ); // => 1
// The array constructor returns a bar.length value of 100:
var bar = new Array( 100 );
-// => undefined
-alert( bar[0] );
-// => 100
-alert( bar.length );
+alert( bar[0] ); // => undefined
+alert( bar.length ); // => 100
```
-An array can be manipulated through methods that are available on the instance of the array. Items in the array can be accessed using bracket notation with a given index. If the index does not exist or contains no value, the return type will be undefined.
+An array can be manipulated through methods that are available on the instance of the array. Items in the array can be accessed using bracket notation with a given index. If the index does not exist or contains no value, the return type will be `undefined`.
A few common array methods are shown below:
@@ -156,8 +148,8 @@ A few common array methods are shown below:
// Using the push(), pop(), unshift() and shift() methods on an array
var foo = [];
-foo.push("a");
-foo.push("b");
+foo.push( "a" );
+foo.push( "b" );
alert( foo[ 0 ] ); // => a
alert( foo[ 1 ] ); // => b
@@ -171,7 +163,7 @@ alert( foo[ 1 ] ); // => undefined
alert( foo.length ); // => 1
-foo.unshift("z");
+foo.unshift( "z" );
alert( foo[ 0 ] ); => z
alert( foo[ 1 ] ); => a
@@ -186,11 +178,11 @@ alert( foo[ 1 ] ); // => undefined
alert( foo.length ); // => 1
```
-There are many more methods for manipulating arrays, some of which are covered further in the [Arrays](/arrays) section. Details can be found on the [Mozilla Developer Network](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array "MDN - Array Reference").
+There are many more methods for manipulating arrays, some of which are covered further in the [Arrays](/arrays/) section. Details can be found on the [Mozilla Developer Network](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array "MDN - Array Reference").
## Type Checking with jQuery
-jQuery offers a few basic utility methods for determining the type of a specific value. Type checking is covered further in the [Testing Type](/testing-type) section, but here are some examples:
+jQuery offers a few basic utility methods for determining the type of a specific value. Type checking is covered further in the [Testing Type](/testing-type/) section, but here are some examples:
```
// Checking the type of an arbitrary value
@@ -198,25 +190,18 @@ var myValue = [ 1, 2, 3 ];
// Using JavaScript's typeof operator to test for primitive types:
-// false
-typeof myValue === "string";
-// false
-typeof myValue === "number";
-// false
-typeof myValue === "undefined";
-// false
-typeof myValue === "boolean";
+typeof myValue === "string"; // false
+typeof myValue === "number"; // false
+typeof myValue === "undefined"; // false
+typeof myValue === "boolean"; // false
// Using strict equality operator to check for null
-// false
-myValue === null;
+
+myValue === null; // false
// Using jQuery's methods to check for non-primitive types
-// false
-jQuery.isFunction( myValue );
-// false
-jQuery.isPlainObject( myValue );
-// true
-jQuery.isArray( myValue );
+jQuery.isFunction( myValue ); // false
+jQuery.isPlainObject( myValue ); // false
+jQuery.isArray( myValue ); // true
```
Something went wrong with that request. Please try again.