diff --git a/page/javascript-101.md b/page/javascript-101.md index a74874b7..66abdea7 100644 --- a/page/javascript-101.md +++ b/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. diff --git a/page/javascript-101/arrays.md b/page/javascript-101/arrays.md index 507c62cb..ac2dffe5 100644 --- a/page/javascript-101/arrays.md +++ b/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 ]; diff --git a/page/javascript-101/closures.md b/page/javascript-101/closures.md index 00891849..8945fc20 100644 --- a/page/javascript-101/closures.md +++ b/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 — 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 — 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 diff --git a/page/javascript-101/conditional-code.md b/page/javascript-101/conditional-code.md index bc336843..cc54b58e 100644 --- a/page/javascript-101/conditional-code.md +++ b/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 — via `if` and `else` blocks — 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. diff --git a/page/javascript-101/functions.md b/page/javascript-101/functions.md index 96d75b6b..5559108d 100644 --- a/page/javascript-101/functions.md +++ b/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 — 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" — 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" diff --git a/page/javascript-101/getting-started.md b/page/javascript-101/getting-started.md index b760799a..0c38d9dd 100644 --- a/page/javascript-101/getting-started.md +++ b/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: ``` - - + +
- -