Mastery
JavaScript » Syntax

Literals

Object literals define an object:

{ firstName:"Remus", lastName:"Lupin", species:"Werewolf", eyeColor:"Green" }

Function literals define a function:

function myFunction (a, b) {
    return a * b;
}

Variables

It’s good programming practice to declare all variables at the beginning of a script. As with algebra, you can do arithmetic with JavaScript variables. You can also add strings, but strings will be concatenated (added end-to-end).

var birthplace = "Godric's Hollow";
var lastName = "Potter", age = 30, job = "Auror"; // Can declare many variables in one statement

Dynamic Types

JavaScript has dynamic types. This means that the same variable can be used as different types:

var x;               // Now x is undefined
var x = 5;           // Now x is a Number
var x = "John";      // Now x is a String

Typeof Operator

You can use the JavaScript typeof operator to find the type of a variable.

typeof "John"                  // Returns string
typeof 3.14                    // Returns number
typeof false                   // Returns boolean
typeof [1, 2, 3, 4]            // Returns object
typeof {name:'John', age:34}   // Returns object 

Case Sensitive

All identifiers are case sensitive. The variables lastName and lastname are two different variables. The functions myFunction and myfunction are two different functions. JavaScript does not interpret Var; as var.