Skip to content
This repository
Browse code

Merge pull request #45 from gjohnson/js101

Adds type section to JS101
  • Loading branch information...
commit beb3e626bae2adef96e10cedfdeddfa68a1c2bb3 2 parents f24edf9 + 267d07a
Addy Osmani addyosmani authored
9 content/javascript-101/dex.md
Source Rendered
@@ -5,9 +5,6 @@ section : 1
5 5 attribution: jQuery Fundamentals
6 6 ---
7 7
8   -jQuery is built on top of JavaScript, a rich and expressive language in its own
9   -right. This section covers the basic concepts of JavaScript, as well as some
10   -frequent pitfalls for people who have not used JavaScript before. While it will
11   -be of particular value to people with no programming experience, even people
12   -who have used other programming languages may benefit from learning about some
13   -of the peculiarities of JavaScript.
  8 +jQuery is built on top of JavaScript, a rich and expressive language in its own right. This means when using jQuery, we are still writing valid JavaScript; it just serves as a framework to make many aspects of writing JavaScript easier and more reliable in the various browser environments. With that said, a basic knowledge of JavaScript will go a long way in understanding, structuring, and debugging our code; jQuery will just help make that basic knowledge go much, much further.
  9 +
  10 +This section covers the basic concepts of JavaScript, as well as some frequent pitfalls many developers fall into during their first foray into the language. While it will be of particular value to people with little to no programming experience, even people who have used other programming languages may benefit from learning about some of the peculiarities of JavaScript.
81 content/javascript-101/running-code.md
Source Rendered
... ... @@ -0,0 +1,81 @@
  1 +---
  2 +chapter: javascript-101
  3 +section: 1
  4 +title: Running Code
  5 +attribution: jQuery Fundamentals
  6 +github: jquery
  7 +---
  8 +
  9 +### External
  10 +
  11 +The first and recommended option is to write our code in an external file (with a ".js" extension), which can then be included on our web page using a HTML script tag and pointing the "src" attribute to our file's location. Having our JavaScript in it's own file will reduce code duplication if we wish to reuse it on other pages and will allow the browser to cache the file on the remote client's computer, decreasing our page load time.
  12 +
  13 +<javascript caption="Saved in example.js.">
  14 +alert('Hello World!');
  15 +</javascript>
  16 +
  17 +<javascript caption="Code is then included via the script tag src attribute.">
  18 + <script type="text/javascript" src="/path/to/example.js"></script>
  19 +</javascript>
  20 +
  21 +### Inline
  22 +
  23 +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, we place the code 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.
  24 +
  25 +<javascript caption="Embed code directly on a web page using script tags.">
  26 +<script type="text/javascript">
  27 + alert('Hello World!');
  28 +</script>
  29 +</javascript>
  30 +
  31 +### Attributes
  32 +
  33 +The last and strongly discouraged option, is to utilize the event handler attributes of HTML attributes.
  34 +
  35 +<javascript caption="Inline code directly on HTML elements being clicked.">
  36 +<a href="javascript:alert('Hello World!');">Click Me!</a>
  37 +<button onClick="alert('Good Bye World');">Click Me Too!</a>
  38 +</javascript>
  39 +
  40 +### Placement
  41 +
  42 +Placement of the previous two options is important and can vary depending on the situation. If we are including some JavaScript which does not access the elements on the page, we can safely place the script before the closing HTML head tag. However, if the code will interact with the elements on the page, we have to make sure those elements exists at the time of our script's execution. A common pitfall can be seen in the following example where we attempt to find the element with an ID of "hello-world", the problem here is our script will be executed prior to the element being defined within the document.
  43 +
  44 +<javascript caption="Attempting to access an element too early will have unexpected results.">
  45 +<!DOCTYPE html>
  46 +<html>
  47 +<head>
  48 +<script type="text/javascript">
  49 + var title = document.getElementById('hello-world');
  50 + console.log(title);
  51 +</script>
  52 +</head>
  53 +<body>
  54 +<h1 id="hello-world">Hello World</h1>
  55 +</body>
  56 +</html>
  57 +</javascript>
  58 +
  59 +It is a common pattern to just move our scripts to the bottom of the page, prior to the closing HTML body tag. This will guarentee the defination of any element we may need when our script is executed.
  60 +
  61 +<javascript caption="Moving our script to the bottom of the page will make sure the element exists.">
  62 +<!DOCTYPE html>
  63 +<html>
  64 +<head>
  65 +</head>
  66 +<body>
  67 +<h1 id="hello-world">Hello World</h1>
  68 +<script type="text/javascript">
  69 + var title = document.getElementById('hello-world');
  70 + console.log(title);
  71 +</script>
  72 +</body>
  73 +</html>
  74 +</javascript>
  75 +
  76 +
  77 +
  78 +
  79 +
  80 +
  81 +
76 content/javascript-101/syntax-basics.md
Source Rendered
... ... @@ -1,27 +1,77 @@
1 1 ---
2   -chapter: js101
3   -section: 1
  2 +chapter: javascript-101
  3 +section: 2
4 4 title: Syntax Basics
5 5 attribution: jQuery Fundamentals
6 6 github: jquery
7 7 ---
8   -Understanding statements, variable naming, whitespace, and other basic JavaScript syntax.
9 8
10   -<javascript caption="A simple variable declaration">
11   -var foo = 'hello world';
12   -</javascript>
  9 +### Comments
  10 +
  11 +JavaScript has support for single and multi line comments. Comments are ignored by the JavaScript engine, therefore have no side-effects on the outcome of the program. They should be used to document the code for future developers (including yourself!). There are libraries available that can generate project documentation pages based on commenting conventions used, [JSDoc](http://code.google.com/p/jsdoc-toolkit/, "JSDoc Toolkit") is one of the more popular ones.
  12 +
  13 +<javascript caption="Single and multi line comments.">
  14 +// this is an example of a single line comment.
13 15
14   -<javascript caption="Whitespace has no meaning outside of quotation marks">
15   -var foo = 'hello world';
  16 +/*
  17 + * this is an example
  18 + * of a
  19 + * multi line
  20 + * comment.
  21 + */
16 22 </javascript>
17 23
18   -<javascript caption="Parentheses indicate precedence">
19   -2 * 3 + 5; // returns 11; multiplication happens first
20   -2 * (3 + 5); // returns 16; addition happens first
  24 +### Whitespace
  25 +
  26 +Whitespace is also ignored in JavaScript. There are many tools that will actully strip out all the whitespace in a program reducing the overall file size in order to improve network latency. Given the availability of tools like these, whitespace should be leveraged to make the code as readible as possible.
  27 +
  28 +<javascript caption="Whitespace is insignifigant.">
  29 +var hello = "Hello";
  30 +var world = "World!";
21 31 </javascript>
22 32
23   -<javascript caption="Identation enhances readability, but does not have any special meaning">
  33 +<javascript caption="Semantic whitespace promotes readibility.">
  34 +// readible code is good!
24 35 var foo = function() {
25   - console.log('hello');
  36 + for (var i = 0; i < 10; i++) {
  37 + alert(i);
  38 + }
26 39 };
  40 +
  41 +foo();
  42 +
  43 +// not so much!
  44 +var foo=function(){for(var i=0;i<10;++){alert(i);}};foo();
  45 +</javascript>
  46 +
  47 +### Reserved Words
  48 +
  49 +There is a handfull of reserved words that cannot be used when declaring user defined variables and functions. Some of these are currently implemented, some for future use, and others for historical reasons. A list of words and in depth explaination can be found on the [MDN JavaScript Reference](https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words, "MDN Reserved Words.")
  50 +
  51 +### Identifiers
  52 +
  53 +Identifiers are used to name variables and functions with a unique name so they can subsequently be refererred to by that name; variables and functions will be discussed in a later chapter. The name of an identifier must follow a few rules:
  54 +
  55 +* Cannot be a reserved word.
  56 +* Can only be composed of letters, numbers, dollar signs, and underscores.
  57 +* The first character cannot be a number.
  58 +
  59 +It is best practice to name these identifiers to something that will make sense to other developers and to you later on.
  60 +
  61 +<javascript caption="Valid identifier names.">
  62 +var myAwesomeVariable = 'a';
  63 +var myAwesomeVariable2 = 'b';
  64 +var my_awesome_variable = 'c';
  65 +var $my_AwesomeVariable = 'd';
  66 +var _my_awesome_variable_$ = 'e';
27 67 </javascript>
  68 +
  69 +While it is possible to run JavaScript in server-side environments, that is out of the scope for this section.
  70 +
  71 +
  72 +
  73 +
  74 +
  75 +
  76 +
  77 +
171 content/javascript-101/types.md
Source Rendered
... ... @@ -0,0 +1,171 @@
  1 +---
  2 +chapter: javascript-101
  3 +section: 2
  4 +title: Types
  5 +attribution: jQuery Fundamentals
  6 +github: jquery
  7 +---
  8 +
  9 +The types in JavaScript fall into two categories; primitives and objects. The primitive types include:
  10 +
  11 +* string
  12 +* number
  13 +* boolean
  14 +* null
  15 +* undefined
  16 +
  17 +### String
  18 +
  19 +String types are text wrapped in single or double quotation marks, but it is best practice to stick with a consistent variation. There may be times when the string contains quotation marks that collide with the ones used to create the string; in this case we must either escape the characters using a `\` backslash or use different quotes around the string.
  20 +
  21 +<javascript caption="Strings can created with double or single quotes.">
  22 +var a = "I am a string";
  23 +var b = 'So am I!';
  24 +
  25 +alert(a);
  26 +alert(b);
  27 +</javascript>
  28 +
  29 +<javascript caption="Sometimes a string may contain quotation marks.">
  30 +var statement1 = 'He said "JavaScript is awesome!"';
  31 +var statement2 = "He said \"JavaScript is awesome!\"";
  32 +</javascript>
  33 +
  34 +### Number
  35 +
  36 +Number types are just any positive or negative numeric value, there is no distinction between integer and floating point values.
  37 +
  38 +<javascript caption="Numbers are any whole or floating point integer.">
  39 +var num1 = 100;
  40 +var num2 = 100.10;
  41 +var num3 = 0.10;
  42 +</javascript>
  43 +
  44 +### Boolean
  45 +Boolean types are just simply true or false.
  46 +
  47 +<javascript caption="Boolean values.">
  48 +var okay = true;
  49 +var fail = false;
  50 +</javascript>
  51 +
  52 +### Undefined and Null
  53 +
  54 +Undefined and null are special types in JavaScript. Null types are a value that represent the absence of a value, this is similar to many other programming languages. Undefined types represent a state in which no value has been assigned at all, you can achieve this type in two ways; by using the undefined keyword or by just not defining a value at all.
  55 +
  56 +<javascript caption="Two ways to acheive an undefined value.">
  57 +var foo = null;
  58 +
  59 +var bar1 = undefined;
  60 +var bar2;
  61 +</javascript>
  62 +
  63 +### Objects
  64 +
  65 +Everything else is in JavaScript is considered an Object. While there are [numerous built-in objects](https://developer.mozilla.org/en/JavaScript/Reference#Global_Objects, "MDN - Global Object Reference"), the ones we will focus on in this chapter are:
  66 +
  67 +* Object
  68 +* Array
  69 +* Function
  70 +
  71 +The simplist way to create an object is either through the Object constructor or the short hand syntax other wise known as an object literal. These simple objects are unordered key/value pairs; the key is formally known as a property and the value can be any valid JavaScript type, even another object. To create or access a property on an object, we use what is known as "dot notation" or "bracket notation".
  72 +
  73 +<javascript caption="Simple objects using the constructor or the literal syntax.">
  74 +var person1 = new Object;
  75 +
  76 +person1.firstName = "John";
  77 +person1.lastName = "Doe";
  78 +
  79 +alert(person1.firstName + " " + person1.lastName);
  80 +
  81 +var person2 = {
  82 + firstName: "Jane",
  83 + lastName: "Doe"
  84 +};
  85 +
  86 +alert(person2.firstName + " " + person2.lastName);
  87 +</javascript>
  88 +
  89 +<javascript caption="As mentioned, objects can also have objects as a property.">
  90 +var people = {};
  91 +
  92 +people['person1'] = person1;
  93 +people['person2'] = person2;
  94 +
  95 +alert(people['person1'].firstName);
  96 +alert(people['person2'].firstName);
  97 +</javascript>
  98 +
  99 +What happens if a property is accessed which has not been *defined* yet? Well, it will be a type of undefined.
  100 +
  101 +<javascript caption="Properties that have not been created are undefined.">
  102 +var person = { name: "John Doe" };
  103 +alert(person.email); // => undefined
  104 +</javascript>
  105 +
  106 +### Array
  107 +
  108 +Arrays are a type of object which are ordered by the index of each item that it contains; this index starts at zero and extends to however many items have been added, also known as the "length" of the array which happens to be a property as well. Similar to a basic object, an array can be created with the Array Constructor or the short hand syntax known as an array literal.
  109 +
  110 +<javascript caption="Creating an array with initial items">
  111 +var foo = new Array;
  112 +var bar = [];
  113 +</javascript>
  114 +
  115 +There is an important distinction to be made between the two though. An array literal can contain items to be added to the array upon creating it, the same is possisble for the Array Constructor. However, if just a single numeric item is passed in, the Array Constructor will assume its length to be that value.
  116 +
  117 +<javascript caption="">
  118 +var foo = [100];
  119 +alert(foo[0]);
  120 +alert(foo.length);
  121 +
  122 +var bar = new Array(100);
  123 +alert(bar[0]);
  124 +alert(bar.length);
  125 +</javascript>
  126 +
  127 +An array can be manipulated through the methods that are avaiable on the instance and items can be accessed using bracket notation with a given index, the value will be undefined if the index does not exists or contains no value.
  128 +
  129 +<javascript caption="Using the push(), pop(), unshift() and shift() methods.">
  130 +var foo = [];
  131 +
  132 +foo.push('a');
  133 +foo.push('b');
  134 +
  135 +alert(foo[0]);
  136 +alert(foo[1]);
  137 +
  138 +alert(foo.length);
  139 +
  140 +foo.pop();
  141 +
  142 +alert(foo[0]);
  143 +alert(foo[1]);
  144 +
  145 +alert(foo.length);
  146 +
  147 +foo.unshift('z');
  148 +
  149 +alert(foo[0]);
  150 +alert(foo[1]);
  151 +
  152 +alert(foo.length);
  153 +
  154 +foo.shift();
  155 +
  156 +alert(foo[0]);
  157 +alert(foo[1]);
  158 +
  159 +alert(foo.length);
  160 +</javascript>
  161 +
  162 +There are many more methods for manipulating arrays, details can be found on the [MDN Document](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array "MDN - Array Reference")
  163 +
  164 +
  165 +
  166 +
  167 +
  168 +
  169 +
  170 +
  171 +

0 comments on commit beb3e62

Please sign in to comment.
Something went wrong with that request. Please try again.