Javascript for Beginners
Part 1: The Basics
By Dallin Osmun
@dallinosmun
Before we get started, here's what you should know:
  • You can try out Javascript code in Chrome by pressing F12.
  • You can try out Javascript code in Firefox by pressing Shift-F4.
  • I recommend using Chrome as your browser and Sublime Text 2 as your editor.
  • Use console.log(myVar); to display your variable in the console.
  • It can even work for objects: console.log(JSON.stringify(myObject));
Comments
Variables
Operators
Conditionals
Loops
Objects
Functions
Common Globals
Comments
Comments are vital. Although your code should be self-explanatory, it doesn't hurt to add comments, explaining your thought process and what each function or code block does.
In Javascript you have single line comments
// here is a single line comment
and block comments
/*Here is a comment that
  can wrap multiple lines.
 */
Variables
Variables let you store data for later use. Javascript has loosely-typed variables, meaning you store whatever you want and your browser will figure out what type your variable is.
To declare a variable in Javascript you write:
var myVariableName = 'myValue';
  • Booleans
  • Numbers
  • Strings
  • Functions
  • Objects
  • Arrays
  • undefined
  • null
Booleans
Booleans are either true or false. Example:
var likesCake = true;
Numbers
Javascript can handle both whole and decimal numbers.
var age = 22;
var PI = 3.14159;
( Note: There are no constants in Javascript. A variable defined in all caps is an implied constant. )
Strings
Strings are lines of text. They can be declared with either single or double quotes:
var name = 'Sam';
var job = "Developer";
Functions
A function is a group of executable code. We'll talk a lot more about them soon. Example:
var add = function (a, b) {
    return a * b;
};
Objects
An Object can contain any of these variable types inside it, including other objects. We'll talk more about them as well. Example:
var person = {
    name: "Josh",
    age: 19,
    isAwesome: true
};
Arrays
Arrays are a lot like Objects. They can contain a variety of values. Arrays have bulit in properties and methods like .length and .push(val). Example:
var myValues = [45, 'foo', true];
myValues.length; // returns 3
myValues.push('bar'); // adds bar to the array
myValues[1]; // returns 'foo'
undefined
Every variable you define automatically is assigned this value. Example:
var importantThing;
console.log(importantThing);
// returns undefined
null
null is a falsy value like undefined but it's one that has been intentionally set. Example:
var moreData = null;
A valid variable name starts with $, _, or a letter and can contain letters, certain characters, and numbers.
0 (zero), '' (empty string), undefined, null, and false are all considered Falsy Values. Everything else (including [] and {}) is considered Truthy. These will come into play when we talk about if statements.
Operators
Equals
age === 10
Not Equal To
age !== 10
Less
age < 10
Less or Equal
age <= 10
Greater
age > 10
Greater or Equal
age >= 10
Not
!foo
And
foo && bar
Or
foo || age < 10
Time for a Demo!
Conditionals
You can choose to branch your code by placing conditionals. The most common is the if statement. It looks like this:
if (value) {
    // to do if value is true
} else {
    // to do if value is false
}
Any Truthy Value will cause the if block to run. Any Falsy Value will cause the else block to run.
Another way to branch out is using as switch statement. A specific code path will run based on the value you pass in. Here it is:
switch (state) {
    case "Utah":
        // do stuff
        break;
    case "California":
        // do stuff
        break;
    default:
        // do stuff
}
A switch statement can be used with a string, number, or boolean.
Loops
Another useful control structure is loops. Javascript has 3 types of loops. The first, and most useful, is the for loop. The syntax looks like this:
for (var i = 0; i < 5; i++) {
    console.log(i);
} // prints out 01234
First you initialize your variable, then you put in a condition, then you increment.
The second style of loop is called the while loop. Here's what it looks like:
var i = 0;
while (i < 5) {
    console.log(i);
    i++;
} // prints out 01234
While the condition in the loop is true, the loop will continue. Make sure not to make an infinite loop!!
The last type of loop is the do while The syntax looks like this.
var i = 0;
do {
    console.log(i);
    i++;
} while (i < 5);
// prints out 01234
The difference between this and the while loop is that the code in the loop block here is guaranteed to run at least once whereas in the while loop, the condition might always be false.
All of these loops have two keywords that can be used inside.
break; // exits out of the loop
continue; // skips to the next loop iteration
Objects
An object is a set of key-value pairs. It can have as many properties as you want. Keys must be valid variable names, otherwise they must be surrounded in quotation marks. You can access object properties through the . operator or [] like arrays. If a function is assigned to an object, it is called a method.
Example of an object:
var dog = {
    name: 'spot',
    age: 4,
    bark: function () {
        console.log('arf!');
    },
    children: ['scout', 'fido'],
    "favorite-things": {
        toy: 'bone',
        food: 'ravioli'
    }
};
Using our last object, we can do this:
var dog = { ... };

dog.name // returns 'spot'
dog.age // returns 4
dog['age'] // returns 4
dog.bark() // runs that function
dog.children[0] // returns 'scout'
dog['favorite-things'].person = 'dallin'
// adds a new property to the object
*If a property name is not a valid identifier, you will need to use [] notation to access that property.
Let's code up a little example.
Functions
We'll talk more about functions in part 2, but they're quite important. In Javascript, functions are first class. There are two ways to define a function:
function add(a, b) {
    return a + b;
}
var add = function (a, b) {
    return a + b;
};
We'll talk about the differences later. The more accepted, javascript approach, would be to use the second.
You don't have to be very picky with your parameters or return statement. Everything in Javascript defaults to undefined. Any parameters not passed in will be undefined. If you don't return anything, the default value is undefined.
var myFunc = function (a) {
    if (a) {
        console.log('parameter passed');
    } else {
        console.log('parameter not found');
    }
}
console.log(myFunc());
// displays 'parameter not found'
// displays 'undefined'
Anonymous Functions are those that don't have names. They can be assigned to variables like you see here. Or they can be used in another way...
var doSomething = function () {
    // do something awesome
    return a;
}
The function is anonymous and has no name, but is assigned to a variable with the name of doSomething.
...as Immediate Functions! These are functions that are run immediately after they are created. This comes in very useful for scoping which will be covered in part 2. There are two ways to write immediate functions.
(function (a) {
    console.log(a);
}('hey there'));
// displays 'hey there'
(function (a) {
    console.log(a);
})("what's up");
// displays "what's up"
Let's create a memoized fibonacci function
Common Globals
The window and document objects are always available to you. They have some nice methods that you can use:
document.getElementById(id);
// grabs an element from the DOM
instanceof
age instanceof Number; // returns true;
// determines if a variable is an instance of a certain type.
typeof
typeof age; // returns Number
// determines what type a variable is
parseInt(val)
parseInt("34"); // returns 34
// converts a string into a number

Thanks for watching!