$ node
> 1 + 1;
2
> var greeting = "Hello World";
undefined
> greeting;
'Hello World'
$ echo 'process.stdout.write("Hello World");' >> helloworld.js
$ node helloworld.js
Hello World
a REPL in the current page
OSX : cmd + option + j
Win / Linux : ctrl + shift + j
using the <script> tag
<script src="helloworld.js"></script>
http://repl.it/languages/JavaScript
http://jsbin.com
http://jsfiddle.net
A statement performs an action
An expression may also be used wherever JavaScript expects a statement (called an "expression statement")
Statements end with a semicolon
var foo; // variable statement
{ // block statement
foo = "bar"; // assignment statement
}
for (var i = 0; i < 10; i++) { // for statement
// execute more statements
}
return true; // return statement
produce a value and can be written wherever a value is expected.
// expressions produce a value
true // true
2 + 3 // 5
5 < 10 // true
add( 2, 3 ); // 5
function( base, increment ){} // [Function]
// can be used as an argument in a function call
add( 2, 4*2 ); // 10
// or in an if statement
if( add( 2, 4*2 ) === 10 ){
// true
}
+ Addition
or concatenate
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
= Assignment
+= Increment and Assign
or concatenate
-= Decrement and Assign
*= Multiply and Assign
/= Divide and Assign
%= Modulo and Assign
== equality
=== strict equality
!= inequality
!== strict inequality
&& logical AND
|| logical OR
> greater than
< less than
>= greater than or equal to
<= less than or equal to
are reserved words
built-in objects, properties, and methods
Your code editor will highlight (most) keywords
highlighted as blue
Never use reserved words as variable or function names
var var = function;
function var() {
var true = false;
var = true;
var return = var;
if( var === true ){
return return;
}
}
use the keyword var
// define
var my_awesome_variable_name;
// access to change value
my_awesome_variable_name = "A literal value of type String";
// access to read value
console.log( my_awesome_variable_name );
// define and set value in one line
var some_numbers = [0,1,2,3,4,5];
Multiple Word Variable Names
use camelCase to seperate words
var userName;
var firstName;
var lastName;
Syntax for Strings
// Strings are wrapped between double quotes
"Hello World"
// or single quotes
'Hello Solar System'
// wrap literal single quotes in double quotes
"Hello Local Interstellar Cloud, i'm fine"
// wrap literal double quotes in single quotes
'Hello "Local Bubble", how are you?'
// or escape double quotes with a backslash \
"Hello Orion's \"Arm\""
// or escape single quotes with a backslash \
'Hello Virgo\'s Supercluster'
// concatenate strings
"Observble" + "universe"
// concatenate with a space
"Observble" + " " + "universe"
Syntax for Number
// Integer
42
// Floating Point Value
0.5432
41.9999998
8.2e+2 // 820
8.2e-4 // 0.00082
// Octal (not in strict mode)
010 // 8
012 // 10
0755 // 493
// Hexadecimal
0xf // 15
0x10 // 16
0xDEADBEEF // 3735928559
// Not a Number
NaN
// Infinites
Infinity
-Infinity
Syntax for Boolean
// literals
true
false
// falsy
false
0
""
null
undefined
NaN
// truthy, any other value not in the falsy list
true
1
"true"
"false"
function(){}
[]
{}
More Truthy Falsy expressions
// falsy, expressions that evaluate to false
!true
0 === 1
undefined || 5 < "potato"
// truthy, expressions that evaluate to true
true
!false
0 !== 1
1 && 1 < 3
has only one value, null
and it's type is Object
// literal
null
// set a previous value to no value
var empty = "mind";
empty = null;
empty === null // evaluates to true
when a variable doesn't exist, or hasn't been set
// literal
undefined
// create a variable with no value
var zed;
zed == undefined // true
typeof(zed) === "undefined" // true
collection of key value pairs
well, almost everything
aka, Anonymous object
aka, Hash Table
aka, Associative Array
aka, Dictionary
// wrapped in open and closing curly braces
var basic_syntax = {};
// keys seperates value pairs separated by colons
var user = { name : "Jon" };
// keys can have special characters
var student = { "first & last name" : "Finn Human" };
// key value pairs are separated by commas
var color = {
red : 0,
green : 0x33,
blue : 0xFF,
getRGB : function(){
return (this.red << 16) + (this.green << 8) + this.blue
}
};
// access the "green" property of the "color" object
// using dot notation
color.green // 51
// as an associative array using array accessor square brackets
color["green"] // 51
var propertyName = "green";
color[propertyName] // 51
// invoking the "getRGB" method of the "color" object
color.getRGB(); // 13311
color["getRGB"](); // 13311
// changing the "blue" property of the "color" object
color.blue = 0xFC;
function doesNothing(){ }
doesNothing();
// function declaration
function greeting(){
console.log("Hello World");
}
// function expression
function(){
console.log("Hello World");
}
// assigning function expression to a variable
var greeting = function(){
console.log("Hello World");
}
// named function expressions
var greeting = function greeting(){
console.log("Hello World");
}
// immediately invoked function expression
(function(){
console.log("Hello World");
})();
parameters are defined in order
only live within the scope of the function
must be a valid variable name
// declaring a function with two parameters
function add( a, b ){
return a + b;
}
// invoking the add function with two arguments
add( 1, 2 ); // 3
// assigning the return value of the function to a value
var sum = add( 1, 2 );
// not all functions return a value
function greeting(){
console.log("Hello World");
}
// functions can only return one time
// then "exits" the function
function createGreeting( name ){
return "Hello " + name;
return "Goodbye"; // function already returned, exited
console.log("I will never execute"); // this is true
}
// the comma operator separates expressions
// evaluates each one, then returns the last
function createNonsense( name, age ){
return name, age; // only age is returned
}
createNonsense( "Jon", 31 ); // 31
// conditional return
function createGreeting( name, age ){
if( age < 32 ){
return "Hello " + name;
}else{
return "Hello Mr. " + name;
}
}
declarations are "hoisted" to the top of the current scope
// a variable declaration
var one;
// a variable assignment
one = "ūnus":
// variable declaration and assignment
var one = "ūnus";
// when this is written
one = "ūnus"; // variable assignment
var one; // variable declaration
// JavaScript interprets it in this order
var one; // hoisted to the top
one = "ūnus";
// only the declaration is hoisted
// not the assignment
console.log( two ); // undefined
var two = "duo";
// JavaScript hoists the declaration
var two;
console.log( two ); // undefined
two = "duo"; // assigned
applies to source files
function declaration vs. function expressions
// function declared after it's invoked
three();
function three(){
return "trēs";
}
// JavaScript interprets in this order
// declaration gets hoisted to the top of the scope
function three(){
return "trēs";
}
three(); // "trēs"
// assign anonymous function expression to variable four
four(); // "quattuor"
var four = function(){
return "quattuor";
}
// JavaScript interprets in this order
// variable declaration gets hoisted to the top of the scope
// assignment does not get hoisted
var four;
four(); // Error! four is not a function
four = function(){
return "quattuor";
}
can cause confusion, understand how JavaScript interprets
// declaration and expression
var five = function(){
return 5;
}
function five(){
return "quīnque";
}
five(); // ??
What is the result of invoking five() ?
can cause confusion, understand how JavaScript interprets
// declaration and expression
var five = function(){
return 5;
}
function five(){
return "quīnque";
}
five(); // ??
// JavaScript hoists only declarations
function five(){ // functions are hoisted first
return "quīnque";
}
var five; // hoisted to top of scope
five = function(){ // assignment in original position
return 5;
}
five(); // 5
the order that JavaScript interprets your code
// normal control flow
var foo = 1;
var bar = 2;
console.log( foo ); // 1
console.log( bar ); // 2
console.log( 3 ); // 3
console.log( 4 ); // 4
the flow of control can be manipulated
// drop in to function execution
function thief(){
console.log( bar ); // 2
console.log( 3 ); // 3
}
var foo = 1;
var bar = 2;
console.log( foo ); // 1
thief(); // takes control
// resume control
console.log( 4 ); // 4
the flow of control can be conditional
// block statement
{
console.log( "group of statements" );
console.log( "that run in containing scope" );
var foo = 1;
}
var bar = 2;
console.log( foo ); // 1
if( foo > 100 ){ // block statement does not run
console.log( bar );
console.log( 3 );
}
console.log( 4 ); // 4
the flow of control can be repeated
// for loop
for( var i=0; i<3; i++ ){
console.log( "statement "+i+" repeats 3 times" );
}
// while loop
var i = 0;
while( i < 3 ){
console.log( "statement "+i+" repeats 3 times" );
i++;
}
// do while loop
var k = 3;
do{
console.log( "statement "+k+" runs once" );
k++;
}while( k < 3 );
normal flow is disrupted by an error
// try will run execute the block statement
// and exit as soon as an exception is thrown
var humans = { pewDiePie : "PewDiePie" };
try{
console.log("Attack pewDiePie");
delete humans.pewDiePie;
console.log("woot!");
}catch(error){
console.log("You cannot kill "+humans.pewDiePie);
}
// catch will execute the block statement
// if try throws an exception
var chuckNorris = "Chuck Norris";
try{
console.log("Attack chuckNorris");
chuckNorris.kill();
console.log("woot!");
}catch(error){ // handle the exception
console.log("You cannot kill "+chuckNorris);
}
var humans = { pewDiePie : "PewDiePie" };
// throw your own exceptions
function kill( humanName ){
if( humanName === "Chuck Norris" ){
throw (new Error("You cannot kill "+humanName));
// exits function block statement
}
delete humans[humanName];
console.log("killed "+humanName);
}
try{
kill("pewDiePie");
kill("Chuck Norris");
console.log("woot!");
}catch(error){
console.log(error.message);
// do something more useful, like run away!
}
// applies strict mode to the current and child scopes
function(){
"use strict"; // invokes strict mode
console.log( "in strict mode" );
function(){
console.log( "also in strict mode" );
}
}
// out of scope
console.log( "NOT in strict mode" );
Invoking Strict Mode
// accidentally defining a variable in the global scope
foo = "bad"; // forgot to use the var keyword
// no errors are thrown
global.foo; // bad
"use strict";
// accidentally defining a variable in the global scope
foo = "bad"; // forgot to use the var keyword
// throws ReferenceError: foo is not defined
"use strict";
var foo = "good";
var foo = 1;
fuu = 2; // typo
foo; // 1, oops!
global.fuu; // 2, pollution!
"use strict";
var foo = 1;
fuu = 2; // typo
// throws ReferenceError: fuu is not defined
ECMAScript6 keywords are now reserved words
prohibits function statements not at the top level of a script or function
"use strict";
if (true){
function foo() { }
// SyntaxError: In strict mode code, functions can only be declared
// at top level or immediately within another function.
foo(); // program exited
}
for (var i = 0; i < 5; i++){
function bar() { }
// SyntaxError: In strict mode code, functions can only be declared
// at top level or immediately within another function.
bar(); // program exited
}
function baz(){ // ok
function qux() { } // ok
function norf() { } // ok
}