Douglas Crockford - The JavaScript Programming Language

Douglas Crockford - The JavaScript Programming Language

Numbers Strings
Booleans Objects
null undefined


• Only one number type
○ No integers
• 64-bit floating point
• IEEE-754 aka “Double”
• Does not map well to common understanding of arithmetic:
• 0.1 + 0.2 = 0.30000000000000004


Numbers type
• Special number: Not a Number
• Result of undefined or erroneous operations
• Toxic: any arithmetic operation with NaN as an input will have NaN as a result
• NaN is not equal to anything, including NaN.

Number function

• Converts the value into a number.
• It produces NaN if it has a problem.
• Similar to + prefix operator.

parseInt function

parseInt(value, 10)

· Converts the value into a number.

· It stops at the first non-digit character.

· The radix(10) should be required.


· Math object is modelled on Java’s Math class.
· It contains
abs absolute value
floor Integer
Math.floor(number) - gets the integer part.

log        logarithm
max        maximum
pow        raise to a power
random        random number
round      nearest integer
sin        sine
sqrt       square root


• Sequence of 0 or more 16-bit characters
○ UCS-2, not quite UTF-16
○ No awareness of surrogate pairs
• No separate character type
○ Characters are represented as strings with a length of 1
• Strings are immutable
cant be modify after created.

• Similar strings are equal (==)
• String literals can use single or double quotes

String length

• `string.length`

• The `length` property determines the number of 16-bit characters in a string.

String function


• Converts value to a string

String Methods

• chatAt
• concat
• indexOf
• lastIndexOf
• matchreplacesearch
• slice
• split
• substring
• toLowerCase
• toUpperCase



Boolean function


• Returns true if value is truthy
• Returns false if value is falsy
• Similar to !! Prefix operator


• A value that isn't anything


A value that isn't even that.
• The default value for variables and parameters
• The value of missing members in objects

Falsy values

false null
undefined “”
0 NaN

All other values (including all objects) are truthy.

e.g. “0” “False”

Everything Else Is Objects

JavaScript is all about objects!

Dynamic Objects

• Unification of Object and Hashtable

• new Object() produces an empty container of name/value pairs

• A name can be any string, a value can be any value except undefined

• members can be accessed with dot notation or subscript notation


• No hash nature is visible (no hash codes or rehash methods)

Loosely Typed

• Any of these types can be stored in an variable, or passed as a parameter to any function.

• The language is not "untyped"


• JavaScript is syntactically a C family language

• It differs from C mainly in its type system, which allows functions to be values.


• Starts with a letter or _ or $

• Followed by zero or more letters, digits, _ or $

• By convention, all variables, parameters, members, and function names start with lower case

• Except for **constructors which start with upper case**

• Initial _ should be reserved for implementations

• $ should be reserved for machines. (microprocessors & program generators)

Reserved Words

boolean break byte
case catch char class const continue
debugger default delete do double
else enum export extends
false final finally float for function
if implements import in instanceof int
native new null
package private protected public
short static super switch synchronized
this throw throws transient true try typeof
var volatile void
while with


// slashslash line comment



• Arithmetic

+ - * / %

• Comparison

==  != < > <= >=

• Logical

&& || !

• Bitwise

& | ^ >> >>> <<

• Ternary


• Addiction and concatenation
• If both operands are number,
    add them
    convert them both to strings
    concatenate them 
        '$' + 3 + 4 = '$34'

• Unary operator can convert strings to numbers
+"42" = 42

• Also 
Number("42") = 42

• Also 
parseInt("42", 10) = 42

**+"3" + (+"4") = 7**


Division of two integers can produce a non-integer result
10 / 3 = 3.333333333333333

== !=

Equal and not equal

• These operators can do type coercion

• It is better to use === and !==, 
which do not do type coercion.


• The guard operator, aka logical andIf first operand is truthy
    **Then result is second operand**
    **Else result is first operand**

• It can be used to avoid null references


• can be written as 


The default operator, aka logical orIf first operand is truthy
    *Then result is first operand
    *Else result is second operand
• It can be used to fill in default values.

• If input is truthy, then last is input, otherwise set last to nr_items.


Prefix logical not operator.
• If the operand is truthy, the result is false. Otherwise, the result is true.
• !! Produces booleans.

& | ^ >> >>> <<
The bitwise operators convert the operand to a 32-bit signed integer, and turn the result back into 64-bit floating point.


expression if
switch while
do for
break continue
return try/throw

Break statement

• Statements can have labels.

• Break statements can refer to those labels.

loop: for (;;) {
If (…) {
break loop;


For statement

Iterate through all of the elements of an array;

For (var I = 0;I < array.length; I += 1) {
// within the loop,
// I is the index of the current member
// array[i] is the current element

Iterate through all of the members of an object:

for (var name in object) {
If (object.hasOwnPropert(name)) {

// within the loop,
// name is the key of current member
// object[name] is the current value


Switch statement

*Multiway branch

*The switch value does not need to be a number. It can be a string.

*The case values can be expressions.

Switch statement

swith (expression) {
case ';':
case ',':
case '.':

Throw statement

throw new Error(reason);

throw {
name: exceptionName,
message: reason

Try statement

try {
} catch (e) {
switch ( {
case 'Error':
throw e;

Try Statement

  • The JavaScript implementation can produce these exception names:

With statement

  • Intended as a short-hand

  • Ambiguous

  • Error-prone

  • Don’t use it

with (o) {
foo = null;
} = null;

foo = null;

Function statement

function name(parmeters) {

Var statement

  • Defines variables within a function.
  • Types are not specified.
  • Initial values are optional.
var name;
var nrErrors = 0;
var a, b, c;


  • In JavaScript, {block} do not have scope.
  • Only functions have scope.
  • Vars defined in a function are not visible outside of the function.

Declare variable any place inside of a function, it’s visible anywhere inside of the function.

Declare variable twice inside of a function, it only gets created once!

Global Variables

JavaScript has implied Globals.

If you create a variable and forget to declare it, JavaScript assumes you might the variable to be global variable.

For example if you forget to define i, you create a global variable called i.

If you make the same mistake in two places, there is a good chance your program is going to be failed.

Return statement

return expression;



In JavaScript, every function will return a result, no void type in js.

  • If there is no expression, then the return value is undefined.
  • Except for constructors, whose default return value is this. It returns the new object.


  • Everything else is objects.
  • Objects can contain data and methods.
  • Objects can inherit from other objects.

Objects are collections


*An object is an unordered collection of name/value pairs

*Names are strings

*Values are any type, including other objects

*Good for representing records and trees.

*Every object is a little database.

Object Literals

  • Object literals are wrapped in { }
  • Names can be names or strings
  • Values can be expressions
  • : separates names and values
  • , separates pairs
  • Object literals can be used anywhere a value can appear.
var myObject = {
name: "Jack B. Nimble",
'goto': 'Jail',
grade: 'A',
level: 3

var theName =;
var destination = myObject['goto'];

Maker function

function maker(name, where, grade, level) {
var it = {}; = name;
it['goto'] = where;
it.grade = grade;
it.level = level;
return it;

myObject = maker("Jack B. Nimble", 'Jail', 'A', 3);

Object Literals

var myObject = {
name: "Jack B. Nimble",
'goto': 'Jail',
grade: 'A',
format: {
type: 'rect',
width: 1920,
height: 1080,
interlace: false,
framerate: 24

Object Literals

type: 'rect',
width: 1920,
height: 1080
throw {
name: 'error',
message: 'out of bounds'

Object Literals

function SuperDiv(width, height, left, top, zIndex, position, color, 
visibility, html, cssClass)

var spec = {

width: 1,
height: 1,
left: 1,
top: 1,
zIndex: 1,
position: 1,
color: 1,
visibility: 1,
html: 1,
cssClass: 1

function SuperDiv(spec)

Object Augmentation (n. 扩大; 增大; 增加物; <音>主题延长)

  • New members can be added to any object by simple assignment

  • There is no need to define a new class

var myObject = {
name: "Jack B. Nimble",
'goto': 'Jail',
grade: 'A',
format: {
type: 'rect',
width: 1920,
height: 1080,
interlace: false,
framerate: 24

myObject.format.colorModel = 'YCgCb';

myObject[name] = value;


  • Objects can be created with a secret link to another object. (Inheritance)

    Objects are able to be inheritanced from other objects.

  • If an attempt to access a member from an object which fails, the secret linked object will be used.

  • The secret link is not used when storing. New members are only added to the primary object.

  • The object(o) function makes a new empty object with a linkage to object o.


var myOldObject = {
name: "Jack B. Nimble",
'goto': 'Jail',
grade: 'A',
level: 3

var myNewObject = Object(myOldObject);

keywords = "Tom Piperson";
myNewObject.level += 1;
myNewObject.crime = 'pignapping';

// A


  • Linkage provides simple Inheritance.
  • An object can inherit from an old object.

Prototypal Inheritance

  • Some languages have classes, methods, constructors, and modules.
    JavaScript’s functions do the work of all of those.

  • Instead of Classical Inheritance,
    JavaScript has Prototypal Inheritance.

  • It accomplishes the same things, but differently.

  • It offers greater expressive power.

  • But it’s different.

Prototypal Inheritance

  • Instead of organizing objects into rigid classes, new objects can be made that are similar to existing objects, and then customized.

  • Object customization is a lot less work than making a class, and less overhead, too.

  • One of the keys is the object(o) function.

  • The other key is functions.

myOldObject.grade = "B";

// B

delete myOldObject['grade'];

// undefined

delete myNewObject['level'];

// 3 or undefined


Single Inheritance (long linkage)

Garbage Collection


What happened to the new objects if the old object set to undefined?

Object Methods

  • All objects are linked directly or indirectly to Object.prototype.
    Object.prototype provides system built-in methods for you.
  • All objects inherit some basic methods.

  • None of them are very userful.

  • hasOwnProperty(name)
    Is the name a true member of this object?

  • No copy method.

  • No equals methos.
    Can use equal operator to check two references to the same object, but it doesnt tell you two object contains the same staff.

Object Construction

  • Make a new empty object

  • Three ways to make new empty object!
    All three of these expressions have exactly the same result:

new Object()


  • {} is the preferred form.


  • Objects can be passed as arguments to functions, and can be returned by functions
    Objects are passed by reference.
    Objects are not passed by value.

  • The === operator compares object references, not values
    true only if both operands are the same object.


  • Members can be removed from an object with the delete operator.
    delete myObject[name];

change the value to undefined.


  • Array inherits from Object.

  • Indexes are converted to strings and used as names from retrieving values.

  • Very efficient for sparse arrays. (创建稀疏矩阵)

  • Not very efficient in most other cases.

  • One advantage: No need to provide a length or type when creating an array.


  • Arrays, unliket objects, have a special length member.

  • It is always 1 larger than the highest integer subscript.

  • It allows use of the traditaional for statement.

    for (i = 0; i< a.length; i+= 1) {
  • Do not use for .. in with arrays.

Array Literals

  • An array literal uses []

  • It can contain any number of expressions, separated by commas
    myList = ['oats', 'peas', 'beans'];

  • New items can be appended
    myList[myList.length] = 'barley';

  • The dot notation should not be used with arrays.

  • [] is preferred to new Array().

Array Methods

  • concat
  • join
  • pop
  • push
  • slice
  • sort
  • splice

Deleting Elements

delete array[number]

  • Removes the element, but leaves a hole in the numbering.
array.splice(number, 1);
  • Removes the element and renumbers all the following elements.

Deleting Elements

myArray = ['a', 'b', 'c', 'd'];

delete myArray[1];

// ['a', undefined, 'c', 'd']

myArray.splice(1, 1);

// ['a', 'c', 'd']

Arrays v Objects

  • Use objects when the names are arbitrary strings.

  • Use arrays when the names are sequential integers.

  • Don’t get confused by the term Associative Array.

Distinguishing Arrays

value.constructor === Array

value instanceof Array

Neither of these work when the value comes from a different frame. (talk later!)

We cant inherited from an array effectivly. We cant use array as a prototype.

Arrays and Inheritance

  • Don’t use arrays as prototypes.
    var array = [1];
    var notArray = Object(array);

The thing got produced by Object(array) is an object instead of an array.

The object produced this way does not have array nature. It will inherit the array’s values and methods. but not its length.

  • You can augment an individual array.

By assigning methods to it since it is underneath an object it’s able to receive any kind of value including functions in any kind of key not just numbers.

This works because arrays are objects.

Since it’s underneath an object, it’s able to receive any kind of values including functions and any kind of keys not just numbers.

  • You can augment all arrays.
    Assign methods to Array.prototype.


  • Functions are first class objects.
  1. Functions can be passed, returned, and stored just like any other value.

  2. Functions inherit from Object and can store name/value pairs.

Function operator

  • The function operator takes an optional name, a parameter list, and a block of statements, and returns a function object.
function name(parameters) {
  • A function can appear anywhere that an expression can appear.


  • What JavaScript calls function, other languages call lambda.

  • It is a source of enormous expressive power.

  • Unlike most power-constructs, it is secure.

Function statement

The function statement is just a short-hand for a var statement with a function value.

function foo() {}

expands to 

var foo = function foo() {};

There is one namespace for both of those things.

Inner functions

  • Functions do not all have to be defined at the top level (or left edge).

  • Functions can be defined inside of other functions.


  • An inner function has access to the variables and parameters of functions that it is contained within.

  • This is known as Static Scoping or Lexical Scoping.


  • The scope that an inner function enjoys continues even after the parent functions have returned.

  • This is called closure.

function fade(id) {
var dom = document.getElementById(id),
level = 1;

function step() {
var h = level.toString(16); =
'#FFFF' + h + h;

if (level < 15) {
level += 1;
setTimeout(step, 100);

setTimeout(step, 100);

Function Objects

  • Functions are objects, so they can contain name/value pairs.

  • This can serve the same purpose as static members in other languages.


  • Since functions are values, functions can be stored in objects.

  • A function in an object is called a method.

var foo = function () {};


  • If a function is called with too many arguments, the extra arguments are ignored.

  • If a function is called with too few arguments, the missing values will be undefined.

  • There is no implicit type checking on the arguments.


  • There are four ways to call a function:

Method form

Function form

Constructor form
new functionObject(arguments)

Apply form
functionObject.apply(thisObject, [arguments])

Method form


  • When a function is called in this form, In additional its regular parameters, it gets a special extra parameter called ‘this’.
    And ‘this’ will be bind to ‘thisObject’.
    So it gives that function access to the object that it was invoked in.

When a function is called in the method form, this is set to thisObject, the object containing the function.

  • This allows methods to have a reference to the object of interest.

Function form


When a function is called in the function form, this is set to the global object.
That is not very useful.
Mistake or not? It makes it harder to write helper functions within a method because the helper function does not get access to the outer this.
var that = this;

Constructor form

new functionObject(arguments)

  • When a function is called with the new operator, a new object is created and assigned to this.

  • If there is not an explicit return value, then this will be returned.


  • this is an extra parameter. Its value depends on the calling form.

  • this gives methods access to their objects.

  • this is bound at invocation time.

Invocation form this
function the global object
method the object
constructor the new object


  • When a function is invoked, in addition to its parameters, it also gets a special parameter called arguments.

  • It contains all of the arguments from the invocation.

  • It is an array-like object.

  • arguments.length is the number of arguments passed.


function sum() {
var i,
n = arguments.length,
total = 0;

for (i = 0; i < n; i += 1) {
total += arguments[i];

return total;

Augmenting Build-in Types

  • Object.prototype
  • Array.prototype
  • Function.prototype
  • Number.prototype
  • String.prototype
  • Boolean.prototype


String.prototype.trim = function () {
return this.replace(
/^\s*(\S*(\s+\S+)*)\s*$/, "$1");


var template = '<table border="{border}">' + 
'<tr><th>Last</th><td>{last}</td></tr>' +
'<tr><th>First</th><td>{first}</td></tr>' +

var data = {
first: "Carl",
last: "Hollywood",
border: 2

mydiv.innerHTML = template.supplant(data);

String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' ? r : a;


The typeof prefix operator returns a string identifying the type of a value.

type typeof
object ‘object’
function ‘function’
array ‘object’
number ‘number’
string ‘string’
boolean ‘boolean’
null ‘object’
undefined ‘undefined’



  • calling compiler to do something

  • The eval function compiles and executes a string (in the context of the function that is calling eval ) and returns the result.

  • It is what the browser uses to convert strings into actions.

  • It is the most misused feature of the language.

Recommend that not use it ever!

  1. Waste lot of time. Often you calling the compiler to do something which can be done much easier on that.
  2. People dont know how to use subscript notation. They will concated dot notation then eval them. The slowest way to doing this.
  3. For certain of checking done in running time it could’ve been done to compile time. Delays error detection, makes it easier to ship bugs.
  4. Security problem.

Using eval on Json is the only time when its correct to use eval.

Use parseJson method!

new Function function

new Function(parameters, body)

when a script tag or an eventhandler on the page,
brower call ‘eval’ to do with it.

  • eval calls the new Function(parameters, body).
    The Function constructor takes zero or more parameter name strings, and a body string, and uses the JavaScript compiler to produce a function object.

  • It should only be used to compile fresh source from a server.

  • It it closely related to eval.

Build-int Type Wrappers

  • Java has both int and Integer type, one is an simple value and the other is an object which wraps the simple value.
    Two incompatible types which can both carry the same value with differing levels of efficiency and convenience.

  • JavaScript copied this pattern to no advantage. Avoid it.

  • Avoid new Boolean()
  • Avoid new String()
  • Avoid new Number()


function object(o) {
function F() {}

F.prototype = o;

return new F();


*We can directly modify individual objects to give them just the characteristics we want.

*We can do this without having to create classes.

*We can then use our new object as the prototype for lots of new objects,
each of which can also be augmented.

Working with the Grain

  • Classical patterns are less effective than prototypal patterns or parasitic patterns(talk in the advanced classes) .

  • Formal classes are not needed for reuse or extension.

(global) Object

  • The object that dares not speak its name.

  • It is the container for all global variables and all built-in objects.

  • Sometimes this points to it.

    var global = this;
  • On browsers, window is the global object.

  • On nodejs, global is the global object.

They assigned to the global object a window member whose value is global object.

global.window = global;

window.something -> global object -> window

Instead of a linker, everything has been reslove in a global namespace
that namespace is the global object, and it is implemented as a JavaScript object.

Global variables are evil

  • Functions within an application can clobber each other.

  • Cooperating applications can clobber each other.

  • Use of the global namespace must be minimized.

Implied Global

  • Any var which is not properly declared is assumed to be global by default.

  • This makes it easy for people who do not know or care about encapsulation to be productive, but it makes applications less reliable.

  • JSLint is a tool which helps identify implied globals and other weaknesses.


Every object is (on its own namespace) a separate namespace.

Use an object to organize your variables and functions.

The YAHOO Object.




  • Function scope can create an encapsulation

  • Use an anonymous function to wrap your application.(talk about in advanced classes)


YAHOO.Trivia = function () {
// define your common vars here
// define your common functions here
return {
getNextPoser: function (cat, diff) {
showPoser: function () {

Thinking about type

  • Trading type-safety for dynamism(n.(人的)活力; 精力,魄力; 劲头;).

  • JavaScript has no cast operator.

  • Reflection is really easy, and usually unnecessary.

  • Why inheritance?
    Automatic casting
    Code reuse

  • Trading brittleness (n.脆性,脆度,脆弱性) for flexibility


The Date function is based on Java’s Date class.

It was not Y2K ready.


  • Regular expression pattern matcher
  • Patterns are enclosed in slashes
  • Example: a pattern that matches regular expressions


  • Bizarre notation, difficult to read


  • The language definition is neutral on threads.

  • Some language processors (like SpiderMonkey) provide thread support

  • Most application environments (like browsers) do not provide it

  • Threads are evil


  • Browsers

  • Windows Script Host and Dashboard

  • Yahoo!Widgets

  • DreamWeaver and Photoshop

  • Embedded


  • Empty strings are truthy
  • keywords are case insensitive
  • No Unicode support
  • No RegExp
  • No try
  • No statement labels
  • || and && return booleans
  • separate operators for strings and numbers


  • Extensions to ECMAScript for XML
  • Proposed by BEA
  • Allows literals
  • Not compatible with ECMAScript Third Edition
  • Not widly accepted yet
  • Not in IE7


  • Progamming style isnt about personal taste.
  • It is about rigor in expression.
  • It is about clearness in presentation.
  • It is about product adaptability and longevity.
  • Good rules help us to keep the quality of our programs high.

Style and JavaScript

  • Style is critically important for JavaScript.

  • The dynamic nature of the language is considered by some to be “too soft”.
    Discipline is necessary for balance.

  • Most of the world’s body of JavaScript programs is crap.

Code Conventions for the JavaScript Programming Language

Semicolon insertion

  • When the compiler sees an error, it attempts to replace an nearby linefeed(n.换行) with a semicolon and try again.
  • This should alarm you.
  • It can mask errors.
  • Always use the full, correct forms, including semicolons.

Line Ending

Break a line after a punctuator:
,.;:{} ([=<>?!+-/%~^|&==!=<=>+=-==/=%=^=|=&=<<>>||&&===!==<<= >>= >>> >>>=

Do not break after a name, string, number, or ) ] ++ —

Defense against copy/paste errors.


  • Avoid tricky expressions using the comma operators.tags: JavaScript

  • Do not use extra commas in array literals.

  • Good: [1, 2, 3]

  • Bad: [1, 2, 3,]

Required Blocks

  • Good:
    if (a) {

  • Bad:
    if (a) b();

Forbidden Blocks
Blocks do not have scope in JavaScript

Blocks should only be used with structured statements



  • Define all variables at the beginning of the function.

  • JavaScript does not have block scope, so their is no advantage in declaring variables at the place of their first use.

Expression Statements

Any expression can be used as a statement. That can mask errors.

Only assignement expressions and invocation expressions should be used as statements.

foo && foo();

switch Statement
Avoid using fallthrough.

Each clause should explicitly break or return or throw.

Assignment Expressions

Do not use assignment expressions in the condition parts of if, while, or for.

It is more likely that

if (a = b) { ... }

was intended to be

if (a == b) { ... }

Avoid tricky expressions.

== and !=
Be aware that == and != do type coercion.


if (a == null) { ... }


if (a === null) { ... }
if (!a) { ... }

Use labels only on these statements:


  • Never use JavaScript: as a label.


Eloquent JavaScript(The Annotated Version) - Chapter 1 - Values, Types, and Operators

JavaScript Value Types

  • Numbers
  • Strings
  • Booleans
  • Undefined
  • Null

  • Objects

  • Functions
  • Arrays


  • 64-bit floating point
  • IEEE-754(aka “Double”)

  • 264 different numbers which is about 18 quintillion (an 18 with 18 zeros after it).

    The actual maximum whole number that can be stored is more in the range of 9 quadrillion (15 zeros), which is still pleasantly huge.

    Not all whole numbers below 18 quintillion fit in a JavaScript number, though.

    Those bits also store negative numbers, so one bit indicates the sign of the number.

    To do this, some of the bits are used to store the position of the decimal point.

  • The % symbol is used to represent the “Remainder“ operation, not “modulo“.
Special numbers
  • Infinity - positive infinity
  • -Infinity - negative infinity
  • NaN - “not a number” which is a value of the number type.
    1. Result of undefined or erroneous operations
    2. Toxic: any arithmetic operation with NaN as an input will have NaN as a result.
    3. Nan is not equal to anything, including NaN
      console.log(NaN == NaN)
      // → false

NaN is supposed to denote the result of a nonsensical computation, and as such, it isn’t equal to the result of any other nonsensical computations.

Strings - anything in ‘’ or “”

Backslash () - “escaping“ the character.

\”, \n, \t means a tab character.

Unary operators

Not all operators are symbols. Some are written as words.

the typeof operator (produces a string value naming the type of the value)

console.log(typeof 4.5)
// → number
console.log(typeof "x")
// → string
  • Sequence of 0 or more 16-bit characters
    • UCS-2, not quite UTF-16
    • No awareness of surrogate pairs
  • No separate character type
    • Characters are represented as strings with a length of 1
  • Strings are immutable
  • Similar strings are equal (==)
  • String literals can use single or double quotes

Boolean - true or false


String comparison is based on the Unicode standard.
This standard assigns a number to virtually every character you would ever need.
When comparing strings, JavaScript goes over them from left to right, comparing the numeric codes of the characters one by one.

Logical operators
  • The && operator represents logical and. It is a binary operator, and its result is true only if both the values given to it are true.

  • The || operator denotes logical or. It produces true if either of the values given to it is true.

  • Not is written as an exclamation mark (!).

  • || has the lowest precedence, then comes &&, then the comparison operators (>, ==, and so on), and then the rest.

  • Ternary operator, operating on three values. It is written with a question mark and a colon, like this:

console.log(true ? 1 : 2);
// → 1
console.log(false ? 1 : 2);
// → 2

The value on the left of the question mark “picks” which of the other two values will come out.

When it is true, the middle value is chosen, and when it is false, the value on the right comes out.

Undefined values

  • Null and Undefined, that are used to denote the absence of a meaningful value.

  • Many operations in the language that don’t produce a meaningful value yield undefined simply because they have to yield some value.

  • Treating Undefined and Null as interchangeable.

Automatic type conversion

console.log(8 * null)
// → 0
console.log("5" - 1)
// → 4
console.log("5" + 1)
// → 51
console.log("five" * 2)
// → NaN
console.log(false == 0)
// → true

When an operator is applied to the “wrong” type of value, JavaScript will quietly convert that value to the type it wants, using a set of rules that often aren’t what you want or expect. This is called type coercion.

  1. Null on either side of Arithmetic will convert to be 0 if numeric on the other side.
  2. String can be convert to be number alongside of “-“ convert to be number.
  3. if Strings on either side of “+”, numeric values will be convert to be string and concatenated.
  4. (Strings that can’t be convert to numeric , false, null, undefined) “*” numeric will be return “NaN”.

False, 0, the empty string (“”), undefined, null are all falsy values.

The rules for converting strings and numbers to Boolean values state that 0, NaN, and the empty string (“”) count as false, while all the other values count as true.

For cases like this, where you do not want any automatic type conversions to happen, there are two extra operators: === and !==.

Recommend using the three-character comparison operators defensively to prevent unexpected type conversions.

When something that doesn’t map to a number in an obvious way (such as “five” or undefined) is converted to a number, the value NaN is produced.

Further arithmetic operations on NaN keep producing NaN, so if you find yourself getting one of those in an unexpected place, look for accidental type conversions.

When comparing values of the same type using ==, the outcome is easy to predict: you should get true when both values are the same, except in the case of NaN.

But when the types differ, JavaScript uses a complicated and confusing set of rules to determine what to do. In most cases, it just tries to convert one of the values to the other value’s type.

However, when null or undefined occurs on either side of the operator, it produces true only if both sides are one of null or undefined.

console.log(null == undefined);
// → true
console.log(null == 0);
// → false

When you want to test whether a value has a real value instead of null or undefined, you can simply compare it to null with the == (or !=) operator.

Short-circuiting of logical operators

The logical operators && and || handle values of different types in a peculiar way.

They will convert the value on their left side to Boolean type in order to decide what to do, but depending on the operator and the result of that conversion, they return either the original left-hand value or the right-hand value.

The || operator, for example, will return the value to its left when that can be converted to true and will return the value on its right otherwise. This conversion works as you’d expect for Boolean values and should do something analogous for values of other types.

console.log(null || "user")
// → user
console.log("Karl" || "user")
// → Karl

This functionality allows the || operator to be used as a way to fall back on a default value. If you give it an expression that might produce an empty value on the left, the value on the right will be used as a replacement in that case.

The && operator works similarly, but the other way around. When the value to its left is something that converts to false, it returns that value, and otherwise it returns the value on its right.

Another important property of these two operators is that the expression to their right is evaluated only when necessary. In the case of true || X, no matter what X is—even if it’s an expression that does something terrible—the result will be true, and X is never evaluated. The same goes for false && X, which is false and will ignore X. This is called short-circuit evaluation.

The conditional operator works in a similar way. The first expression is always evaluated, but the second or third value, the one that is not picked, is not.

Due to the restrict access to the internet in my working place,

I am eager to have everything of my personal project on the internet which is not that hard to find a solution.

Let me introduce you Cloud9 IDE + Github + Travis CI!


Online Git Repo dont think I need to talk about it more.

Cloud9 IDE

Can link C9 with your github repo, so you can clone to C9 and start working.

Most awesomeness about C9 is that its not only a online IDE, but also a RHEL virtual enivorement has node and bower installed, which means u can ‘npm install’ and ‘bower install’ whatever u want!


├── azure-cli@0.8.2
├── bower@1.3.12
├── grunt@0.4.4
├── grunt-cli@0.1.13
├── hexo-cli@0.1.7
├── hexo-deployer-git@0.0.4
├── jitsu@0.13.15
└── npm@1.4.28

maybe not that awesome since the free version only serves 512mb memory which causes ‘Thread being killed’ most of time if u do a ‘bower install’.


Travis CI

Why Travis CI is awesome? cos Travis CI also will do npm install and bower install for you when it cis ur project!!

  1. npm install is defaultly in Travis CI.

  2. Add a simple file to ask Travis CI do “bower install”

    Create a file called .travis.yml in the repo.

    Put following in there.

    language: node_js
      - 0.12
      - npm install -g bower
      - bower install


  • Part of a larger, more complex execution platform called the Common Language Infrastructure (CLI), C# is a programming language for building software components and applications.

C# is a case-sensitive language:
Incorrect case prevents the code from compiling successfully.
  • The C# compiler allows any file extension for files containing C# source code, but .cs is typically used. After saving the source code to a file, developers must compile it.
Set up CSC to compile C# source code.

Set PATH=%PATH%;%Windir%\Microsoft.NET\Framework\v4.0.30319
  • The program created by the C# compiler, HelloWorld.exe, is an assembly.

    Instead of creating an entire program that can be executed independently, developers can create a library of code that can be referenced by another, larger program.

    Libraries (or class libraries) use the filename extension .dll, which stands for Dynamic Link Library (DLL).

    A library is also an assembly. In other words, the output from a successful C# compile is an assembly regardless of whether it is a program or a library.

  • Keywords


After C# 1.0, no new reserved keywords were introduced to C#. However, some constructs in later versions use contextual keywords, which are significant only in specific locations. Outside these designated locations, contextual keywords have no special significance

  • Rules for naming identifiers

    Ultimately, select clear, possibly even verbose names—especially when working on a team or when developing a library against which others will program.

    Two basic casing formats for an identifier:

    • Pascal case (henceforth PascalCase)

      capitalizes the first letter of each word in an identifier name

    • Camel case (henceforth camelCase)

      capitalizes the first letter of each word in an identifier name, except that the first letter is lowercase


      1. DO favor clarity over brevity when naming identifiers.

      2. DO NOT use abbreviations or contractions within identifier names.

      3. DO NOT use any acronyms unless they are widely accepted,
        and even then, only when necessary.

1. DO capitalize both characters in two-character acronyms, 
except for the first word of a camelCased identifier.

2. DO capitalize only the first character in acronyms with three or more characters, 
except for the first word of a camelCased identifier.

3. DO NOT capitalize any of the characters in acronyms 
at the beginning of a camelCased identifier.

4. DO NOT use Hungarian notation 
(that is, do not encode the type of a variable in its name).

Although it is rare, keywords may be used as identifiers if they include “@” as a prefix. e.g.”name a local variable @return”, “name a method @throw()”.

  • Type Definition

    All executable code in C# appears within a type definition, and the most common type definition begins with the keyword class. A class definition is the section of code that generally begins with class identifier { … }

class HelloWorld

Class name can be vary, but must be PascalCase.


1. DO name classes with nouns or noun phrases.

2. DO use PascalCasing for all class names.

Generally, programs contain multiple types, each containing multiple methods.

  • Method

    A method in C# is

    A named block of code introduced by a method declaration and (usually) followed by zero or more statements within curly braces.

    1. Perform computations and/or actions.

    2. Provide a means of structuring and organizing code so that it is more readable.

    3. More importantly, can be reused and called from multiple places, and so avoid the need to duplicate code.

    4. The method declaration introduces the method and defines the method name along with the data passed to and from the method.

  • Main Method

    1. The location where C# programs begin execution is the Main method, which begins with static void Main().

    2. Although the Main method declaration can vary to some degree, static and the method name, Main, are always required for a program.

    3. C# requires that the Main method return either void or int, and that it take either no parameters, or a single array of strings.

    4. The args parameter is an array of strings corresponding to the command-line arguments. However, the first element of the array is not the program name but the first command-line parameter to appear after the executable name.

    5. The int returned from Main is the status code and it indicates the success of the program’s execution. A return of a nonzero value generally indicates an error.

static int Main(string[] args)

  • Statements and Statement Delimiters

    System.Console.WriteLine(), which is used to write a line of text to the console.
    C# generally uses a semicolon to indicate the end of a statement, where a statement comprises one or more actions that the code will perform.

    • Statements without Semicolons
    1. One example that does not include the semicolon is a switch statement.
      Because curly braces are always included in a switch statement, C# does not require a semicolon following the statement.

    2. In fact, code blocks themselves are considered statements (they are also composed of statements) and they don’t require closure using a semicolon.

    3. Similarly, there are cases, such as the using declarative, in which a semicolon occurs at the end but it is not a statement.

  • Place multiple statements on the same line

    Since creation of a newline does not separate statements, you can place multiple statements on the same line and the C# compiler will interpret the line to have multiple instructions.
static int Main(string[] args)

  • Splitting of a statement across multiple lines

C# also allows the splitting of a statement across multiple lines. Again, the C# compiler looks for a semicolon to indicate the end of a statement

static int Main(string[] args)

"Hello. My name is Inigo Montoya.");
Beginner Topic: What Is Whitespace?

Whitespace is the combination of one or more consecutive formatting characters such as tab, space, and newline characters.
Eliminating all whitespace between words is obviously significant, as is whitespace within a quoted string.

The semicolon makes it possible for the C# compiler to ignore whitespace in code.
Apart from a few exceptions, C# allows developers to insert whitespace throughout the code without altering its semantic meaning.

  • Working with Variables


Beginner Topic: Local Variables

A variable refers to a storage location by a name that the program can later assign and modify.Local indicates that the programmer declared the variable within a method.

To declare a variable is to define it, which you do by

  1. Specifying the type of data which the variable will contain
  2. Assigning it an identifier (name)
  • Data Types

Beginner Topic: What Is a Data Type?

The type of data that a variable declaration specifies is called a data type (or object type). A data type, or simply type, is a classification of things that share similar characteristics and behavior.

Similarly, in programming languages, a type is a definition for several items endowed with similar qualities.

  • Declaring a Variable

It is possible to declare multiple variables within the same statement by specifying the data type once and separating each identifier with a comma.

string message1, message2;

  • In C#, the name of the variable may begin with any letter or an underscore (_), followed by any number of letters, numbers, and/or underscores.

  • By convention, however, local variable names are camelCased (the first letter in each word is capitalized, except for the first word) and do not include underscores.

  DO use camelCasing for local variables.
  • Assigning a Variable

After declaring a local variable, you must assign it a value before reading from it. One way to do this is to use the = operator, also known as the simple assignment operator.

Operators are symbols used to identify the function the code is to perform.

class MiracleMax
static void Main()

// declaring 'valerie'
string valerie;

// declaring and assigning a variable to 'max'
string max = "Have fun storming the castle!";

// assigning a variable to 'valerie'
valerie = "Think it will work?";

max = "It would take a miracle.";

  • Assign a variable as part of the variable declaration (as it was for max),
  • Assign a variable afterward in a separate statement (as with the variable valerie)
  • The value assigned must always be on the right side.

C# requires that local variables be determined by the compiler to be “definitely assigned” before they are read.

Additionally, an assignment returns a value. Therefore, C# allows two assignments within the same statement,

class MiracleMax
static void Main()

// ...
string requirements, max;
requirements = max = "It would take a miracle.";
// ...
  • Using a Variable

The result of the assignment, is that you can then refer to the value using the variable identifier.

Advanced Topic: Strings Are Immutable

All data of type string, whether string literals or otherwise, is immutable (or unmodifiable). For example, it is not possible to change the string “Come As You Are” to “Come As You Age.” A change such as this requires that you reassign the variable to point to a new location in memory, instead of modifying the data to which the variable originally referred.
  • Console Input and Output

Advanced Topic: System.Console.Read()

In addition to the System.Console.ReadLine() method, there is also a System.Console.Read() method.

However, the data type returned by the System.Console.Read() method is an integer corresponding to the character value read, or –1 if no more characters are available.

To retrieve the actual character, it is necessary to first cast the integer to a character.

int readValue;
char character;
readValue = System.Console.Read();
character = (char) readValue;
  • The System.Console.Read() method does not return the input until the user presses the Enter key

  • no processing of characters will begin, even if the user types multiple characters before pressing the Enter key.

In C# 2.0, there appears a new method called System.Console.ReadKey() which, in contrast to System.Console.Read(), returns the input after a single keystroke.
It allows the developer to intercept the keystroke and perform actions such as key validation, restricting the characters to numerics.

"Your full name is {0} {1}.", firstName, lastName);

writes out the entire output using composite formatting. With composite formatting, the code first supplies a format string to define the output format. It identifies two indexed placeholders for data insertion in the string.

  • Comments