Skip to content

Commit

Permalink
Merge pull request #45 from gjohnson/js101
Browse files Browse the repository at this point in the history
Adds type section to JS101
  • Loading branch information
addyosmani committed Feb 7, 2012
2 parents f24edf9 + 267d07a commit beb3e62
Show file tree
Hide file tree
Showing 4 changed files with 318 additions and 19 deletions.
9 changes: 3 additions & 6 deletions content/javascript-101/dex.md
Expand Up @@ -5,9 +5,6 @@ section : 1
attribution: jQuery Fundamentals
---

jQuery is built on top of JavaScript, a rich and expressive language in its own
right. This section covers the basic concepts of JavaScript, as well as some
frequent pitfalls for people who have not used JavaScript before. While it will
be of particular value to people with no programming experience, even people
who have used other programming languages may benefit from learning about some
of the peculiarities of JavaScript.
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.

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 changes: 81 additions & 0 deletions content/javascript-101/running-code.md
@@ -0,0 +1,81 @@
---
chapter: javascript-101
section: 1
title: Running Code
attribution: jQuery Fundamentals
github: jquery
---

### External

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.

<javascript caption="Saved in example.js.">
alert('Hello World!');
</javascript>

<javascript caption="Code is then included via the script tag src attribute.">
<script type="text/javascript" src="/path/to/example.js"></script>
</javascript>

### Inline

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.

<javascript caption="Embed code directly on a web page using script tags.">
<script type="text/javascript">
alert('Hello World!');
</script>
</javascript>

### Attributes

The last and strongly discouraged option, is to utilize the event handler attributes of HTML attributes.

<javascript caption="Inline code directly on HTML elements being clicked.">
<a href="javascript:alert('Hello World!');">Click Me!</a>
<button onClick="alert('Good Bye World');">Click Me Too!</a>
</javascript>

### Placement

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.

<javascript caption="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>
</head>
<body>
<h1 id="hello-world">Hello World</h1>
</body>
</html>
</javascript>

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.

<javascript caption="Moving our 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>
</body>
</html>
</javascript>







76 changes: 63 additions & 13 deletions content/javascript-101/syntax-basics.md
@@ -1,27 +1,77 @@
---
chapter: js101
section: 1
chapter: javascript-101
section: 2
title: Syntax Basics
attribution: jQuery Fundamentals
github: jquery
---
Understanding statements, variable naming, whitespace, and other basic JavaScript syntax.

<javascript caption="A simple variable declaration">
var foo = 'hello world';
</javascript>
### Comments

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.

<javascript caption="Single and multi line comments.">
// this is an example of a single line comment.

<javascript caption="Whitespace has no meaning outside of quotation marks">
var foo = 'hello world';
/*
* this is an example
* of a
* multi line
* comment.
*/
</javascript>

<javascript caption="Parentheses indicate precedence">
2 * 3 + 5; // returns 11; multiplication happens first
2 * (3 + 5); // returns 16; addition happens first
### Whitespace

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.

<javascript caption="Whitespace is insignifigant.">
var hello = "Hello";
var world = "World!";
</javascript>

<javascript caption="Identation enhances readability, but does not have any special meaning">
<javascript caption="Semantic whitespace promotes readibility.">
// readible code is good!
var foo = function() {
console.log('hello');
for (var i = 0; i < 10; i++) {
alert(i);
}
};

foo();

// not so much!
var foo=function(){for(var i=0;i<10;++){alert(i);}};foo();
</javascript>

### Reserved Words

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.")

### Identifiers

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:

* Cannot be a reserved word.
* Can only be composed of letters, numbers, dollar signs, and underscores.
* The first character cannot be a number.

It is best practice to name these identifiers to something that will make sense to other developers and to you later on.

<javascript caption="Valid identifier names.">
var myAwesomeVariable = 'a';
var myAwesomeVariable2 = 'b';
var my_awesome_variable = 'c';
var $my_AwesomeVariable = 'd';
var _my_awesome_variable_$ = 'e';
</javascript>

While it is possible to run JavaScript in server-side environments, that is out of the scope for this section.








171 changes: 171 additions & 0 deletions content/javascript-101/types.md
@@ -0,0 +1,171 @@
---
chapter: javascript-101
section: 2
title: Types
attribution: jQuery Fundamentals
github: jquery
---

The types in JavaScript fall into two categories; primitives and objects. The primitive types include:

* string
* number
* boolean
* null
* undefined

### String

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.

<javascript caption="Strings can created with double or single quotes.">
var a = "I am a string";
var b = 'So am I!';

alert(a);
alert(b);
</javascript>

<javascript caption="Sometimes a string may contain quotation marks.">
var statement1 = 'He said "JavaScript is awesome!"';
var statement2 = "He said \"JavaScript is awesome!\"";
</javascript>

### Number

Number types are just any positive or negative numeric value, there is no distinction between integer and floating point values.

<javascript caption="Numbers are any whole or floating point integer.">
var num1 = 100;
var num2 = 100.10;
var num3 = 0.10;
</javascript>

### Boolean
Boolean types are just simply true or false.

<javascript caption="Boolean values.">
var okay = true;
var fail = false;
</javascript>

### Undefined and Null

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.

<javascript caption="Two ways to acheive an undefined value.">
var foo = null;

var bar1 = undefined;
var bar2;
</javascript>

### Objects

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:

* Object
* Array
* Function

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

<javascript caption="Simple objects using the constructor or the literal syntax.">
var person1 = new Object;

person1.firstName = "John";
person1.lastName = "Doe";

alert(person1.firstName + " " + person1.lastName);

var person2 = {
firstName: "Jane",
lastName: "Doe"
};

alert(person2.firstName + " " + person2.lastName);
</javascript>

<javascript caption="As mentioned, objects can also have objects as a property.">
var people = {};

people['person1'] = person1;
people['person2'] = person2;

alert(people['person1'].firstName);
alert(people['person2'].firstName);
</javascript>

What happens if a property is accessed which has not been *defined* yet? Well, it will be a type of undefined.

<javascript caption="Properties that have not been created are undefined.">
var person = { name: "John Doe" };
alert(person.email); // => undefined
</javascript>

### Array

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.

<javascript caption="Creating an array with initial items">
var foo = new Array;
var bar = [];
</javascript>

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.

<javascript caption="">
var foo = [100];
alert(foo[0]);
alert(foo.length);

var bar = new Array(100);
alert(bar[0]);
alert(bar.length);
</javascript>

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.

<javascript caption="Using the push(), pop(), unshift() and shift() methods.">
var foo = [];

foo.push('a');
foo.push('b');

alert(foo[0]);
alert(foo[1]);

alert(foo.length);

foo.pop();

alert(foo[0]);
alert(foo[1]);

alert(foo.length);

foo.unshift('z');

alert(foo[0]);
alert(foo[1]);

alert(foo.length);

foo.shift();

alert(foo[0]);
alert(foo[1]);

alert(foo.length);
</javascript>

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









0 comments on commit beb3e62

Please sign in to comment.