Skip to content

Cheatsheet

Javascript is an object oriented scripting language. It can be used in browsers but also as a base language for phone development (cordova) and as a commandline scripting language (nodejs).

Documentation

By ... Far ... the best documentation is the Mozilla documentation. It is superb : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction

java comparison

Javascript is definitely not a script version of java.

JavaScript follows most Java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from LiveScript to JavaScript.

Javascript has prototype based inheritance. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.

JavaScript Java
Object-oriented. No distinction between types of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically. Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically.
Variable data types are not declared (dynamic typing) Variable data types must be declared (static typing)
Cannot automatically write to hard disk Can automatically write to hard disk

ECMA Script

  • Javascript is standardized by an organization previously known as the (European Computer Manufacturers Cooperation).
  • JavaScript supports all functionality outlined in the ECMAScript specification
  • The ECMAScript standard is documented in the ECMA-262 which is approved by the international standardization organization as ISO-16262.
  • Don't use the ECMA script specification unless you are creating a new javascript implementation ;)

Platforms

Support for javascript is in all modern browsers, and you can use nodejs as well to execute javascript from the command line. Some platforms will be highlighted here. Especially firefox.

firefox

You don't have to create html pages just to try javascript in firefox. You just hit shift-F4 and a js scratch-pad opens up.

If you type some javascript code, like alert("hi") and run it it will appear in the firefox window.

nodejs

Of course even better is the commandline, and nodejs is perfect for that. Install from aptitude/yum and run it a script like :

!/usr/bin/env node console.log ("Yep");

Introduction

Some facts:

  • Javascript is case sensitive and uses Unicode characters
  • Always use var
  • Just use semicolons, they won't hurt.

declarations

Though the specification mentions let and const as declaration keywords, they are experimental and the only keyword used is var.

var x =11;

This means you define it locally, so in the outer scope it may be global.

outer scope
x=11;

Is always global. So it is best to just always use var.

Variables declared but not initialized are 'undefined'

initialization
var x;
var y=10;
var z=null;
console.log(x)
# undefined
console.log(y)
# 10
console.log(z)
# null
console.log(nonexistent)
# TypeError
  • undefined evaluates to false if use in boolean expressions : if (x) -> false
  • undefined becomes NaN in numerical context : (x + 2) -> NaN
  • null evaluates to false in boolean context : if (z) -> false
  • null becomes 0 in numerical context (z * 2) -> 0

scope

Javascript has no block-scope, a variable declared outside any function has global scope , and a variable declared inside a bock has local scope in the function the block belongs to.

Having blocks, but no block-scope means :

no block scope
1
2
3
4
5
6
var x=1;
{ 
    var x = 2;
} 
console.log(x);
# 2

Global variables are actually members of the enclosing global object of the program, which is the window object in a browser. So you could also reference globals as :

window is global object in a browser
window.myvariable=222;

declaration hoisting

Hoisting declaration means, bring to the top as in 'jolly roger'. It means a variable may be used if declared lower/after then the statement.

type error
console.log (x) // gives TypError

but adding the var gives undefined

ok but prints undefined
console.log(x) // gives undefined (NOT 9)
var x=9

constants

constants
1
2
3
const c=222;
c = 333; # error
console.log(c);

data structures and types

There are 7 primitive types :

  • boolean : true or false
  • null (lowercase) a special type denoting null
  • undefined, a top-level property whose value is undefined
  • Number
  • String
  • Symbol (ECMAscript)
  • Object

=== compares both value and type

=== operator
5 === 5 -> false

== compare value only

== operator
5 == 5 -> true

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=.

The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:
'' == '0' // false
0 == '' // true
0 == '0' // true

false == 'false' // false
false == '0' // true

false == undefined // false
false == null // false
null == undefined // true

' trn ' == 0 // true

The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.

Javascript converts types where needed and applicable. + can be used for concatenation, it means that :

unexpected ?
1
2
3
// beware !!
37 - 7 // 30
37 + 7 // “337”

To force the other behavior explicitly use parseInt/parseFloat :

do it like this
parseInt(37) + 7 // 44

Also + can be used to force strings into a number format, so these two statements differ:

add an extra +
nn = 1.1 + 1.1 // 1.11.1
nn = +1.1 + +1.1 // 2.2

literals

There are 7 types :

  • array literals
  • boolean literals
  • floating point
  • integers
  • object literals
  • regexp literals
  • string literals

array literals

Arrays are initialized in the expected way, each member is evaluated left to right. Mixed type members are allowed and extra comma's generate extra members, except for the last one !

array literals
1
2
3
var c=1
function x() { return y; }
var arr[c++,c++,,c++,string,x(),];

This will give :

output
[ 1, 2, , 3, 'string', ‘y’ ]

Note also that console.log prefers single quotes ... i don't .....

boolean literals

true or false. But beware !!

There is also a Boolean object !!, and that leads to : .. code-block:

var b = new Boolean(false);
if (b) // this condition evaluates to true
if (b == true) // this condition evaluates to false

Explanation:

  • if (b) evaluates if b is an existing object !!, and it is : true.
  • (b == true) evaluates the content to be true, and it is not : false

While we are at it, note that this will become a true boolean :

becomes true ! not false
var b = new Boolean(false);

Since the string 'false' evaluates to true like any string !!

Floating point literals

Exactly like c : the exact syntax is

float format
[(+|-)][digits][.digits][(E|e)[(+|-)]digits]

Integer literals

Very like c literals but with the additional prefix of 0b for binary :

  • 0, 117 and -345 (decimal, base 10)
  • 015, 0001 and -0o77 (octal, base 8)
  • 0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)
  • 0b11, 0b0011 and -0b11 (binary, base 2)
  • 1.11.5 Object literals

Call it : json... ?

You can also use functions and expression here like in the array example above. And you can use arrays as members, and objects as array members so i can't really see a difference between object and array literals ?!?

You can even use an array index as a member name : Example using function x() from above :

initialize
function x() { return “y”; }

var o = {
    dinges: x(),
    die: {
        sub: 33,
        twee: "hallo"
    },
    7: 888,
};
console.log(o);
# { 7: “zeven”, dinges: 'y', die: { sub: 33, twee: 'hallo' } }
console.log(o[7])
# zeven
console.log(o.7) // ERROR
console.log(o.die.sub)
# 33

Notice the order of the members when printing the object, 7 is printed first. Also you can only use o[7] and o['7'] , not o.7 or o."7" or something. members must be strings to use the . dot notation. Note also that this can even be an empty string :

weird
1
2
3
4
5
6
7
8
var weird = {
    “”: “Empty string”,
“[“: “Any string”,
};
console.log(weird[“”]) 
# Empty string
console/log.”[“;
# error… only the [] notation !!

Regexp literals

These are expressions enclosed in slashes, like :

regexp
var re = /ab+c/ ;

String literals

These can be double or single quotes but of course they have to match :

  • "This" == 'This' => true;
  • "That" === 'That' => true;

Line breaks can be included :

string literals
1
2
3
4
var s = Een regel\nEn nog een
console.log(s);
# Een regel
# En nog een

You can actually call all methods and properties you could use on a string object on a string literal as well because js converts it to an Object temporarily :

string length
console.log(Een string.length);
# 10

Control flow

These are the default control flow constructs like if, while, etc.

if statement

if
1
2
3
if ( x == 1) { 
} else { 
} 

The following values become false in if statements :

  • false
  • undefined
  • null
  • 0
  • NaN
  • the empty string ("")

All other values, including all objects will become true. So .. remember the "var v = new Boolean(false)" ? It will test true because its an object.

switch statement

Much as expected. You can use strings as case values, break is optional and the default does not have to be the last one in the list !

An example :

switch
switch ('mis') {
    case 'nix':
        console.log('nix');
    break;
    default:
        console.log('default');
    case 'yup':
        console.log('yup');
    break;
}
#default
#yup

functions and =>

How do i 'read' : const foo = (property) => { return property + 'bar' }

Define a constant foo that equals a function which takes an argument, property, and returns property + bar.

In general, (...) => { ... } is mostly equivalent to function(...) {...}

Of course there are again some exceptions, since you can omit the braces :

arrow notation
const foo = (property) => property + 'bar' 

If the => isn't followed by a { then it defines a function that returns a javascript expression. So, without the {

(...) => ... Is mostly equivalent to function(...) {return ...}

this is not finished, just as far as i got