Friday, December 25, 2015

JavaScript Basics

Development Setup

  • Start "Console" in browser. For example, press F12 in Chrome.
  • Type in and evaluate javascript code
  • Press F5 (refresh) to clear all previous js variables
  • Press Shift-Enter to enter multiple statements before executing
  • Node.js can be be used to run js from command-line
  • 'use strict' at the top of the script to require variable declaration before use.

Common Statements

console.log("Write hello to console");

var age = prompt("What is our age?", "18");

alert("Hello");  // only available in browser, not when run on command-line

Data Types

In Javascript variables do not have a type; however, the value assigned to a variable has a type.

String

"same" as 'same'

var a = 100;
a = String(a);   // coerce value to string

Number

Integers and floating numbers
var b = "100";
b = Number(b);  // coerce value to number

amount.toFixed(2);  // string formatted and rounded to 2 places

if (isNan(b))
  ...

null resolves to 0
undefined resolves to NaN

Boolean

Two valid values: true, false

Composite Data Types

  • Object - var anObj = new Object();
  • Array - var array = new Array(5);

Internally, arrays are objects as well (keys are index values, 0,1, ...).
Special Data Types

  • Null - no value, use to clear value
  • Undefined - does not exist, not defined

JSON

http://sal-razzaq.blogspot.com/2014/04/json-javascript-object-notation.html
// Convert JSON string to Javascript object
var obj = JSON.parse(text);

Falsy Values

0 -0 NaN "" false null undefined

Object-Oriented Programming

OO Programming with JavaScript

JavaScript on Web Page

Include JavaScript on Web Page

jQuery

Using jQuery JavaScript library

JavaScript Promise

A promise represents the eventual result of an asynchronous operation. It is a placeholder into which the successful result value or reason for failure will materialize.A  Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason.

A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa. If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier.