This notebook covers the following material about the JavaScript langauge using examples from the Mozilla website.
Value Properties
Infinity
NaN
undefined
null
Function Properties
eval()
uneval()
isFinite()
isNaN()
parseFloat()
parseInt()
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
unescape()
Fundamental Objects
Object
Function
Boolean
Symbol
Error
EvalError
InternalError
RangeError
ReferenceError
SyntaxError
TypeError
URIError
Numbers and Dates
Number
Math
Date
Text Processing
String
RegExp
Indexed Collections
Array
Int8Array
Uint8Array
Keyed Collections
Map
Set
WeakMap
WeakSet
Vector Collections
SIMD
, ...Structured Data
ArrayBuffer
JSON
Control Abstraction Objects
Promise
Generator
GeneratorFunction
Reflection
Reflect
Proxy
Internationalization
Itl
Non-standard Objects
Iterator
ParallelArray
StopIteration
Control Flow
{}
break
continue
Empty
if...else
switch
throw
try...catch
Declarations
var
let
const
Functions and Classes
function
function*
return
class
Iterations
do...while
for
for each...in
for...in
for...of
while
Others
debugger
export
import
label
Primary Expression
this
: refers to function's execution contextfunction
: defines function expressionclass
: defines a class expressionfunction*
yield
yield*
[]
: array initializer{}
: object initializer/ab+c/i
()
: grouping operatorLeft-hand-side Expressions
object.property
and object["property"]
)new
new.target
super
Increment and Decrement
A++
A--
++A
--A
Unary Operators
delete
void
typeof
+
, -
, ~
, !
Arithmetic Operators
+
, -
, /
, *
, %
, **
Relational Operators
in
instanceof
<
>
<=
>=
Equality Operators
==
: equality!=
===
: identity!==
Bitwise Shift Operators
<<
: left shift>>
: right shift>>>
: bitwise unsigned right shiftBinary Bitwise Operators
&
, |
, ^
Binary Logic Operators
&&
, ||
Conditional (ternary) Operators
(condition ? ifTrue : ifFalse)
Assignment Operators
=
*=
/=
%=
+=
-=
<<=
>>=
>>>=
&=
^=
|=
[a, b] = [1, 2]
{a, b} = {a:1, b:2}
Comma Operator
,
: allows multiple expressions to be evaluated in a single statement and returns the result of the last expressionNon-standard Features
[for (x of y) x]
: array comprehensions[for (x of y) y]
: generator comprehensions/*
This is a multiline comment.
*/
// This is an inline comment.
// Grammar and Types
var var_1 = 'a'; // a declared variable initialized with a value
{let var_2 = 'b';} // a block scope local variable, optionally initializing it to a value
const var_3 = 'c'; // declares a read-only named constant
// variables can start with a letter, underscore, or dollar sign.
var _var_4 = 'd';
var $var_5 = 'e';
// the + operator concantenates strings and Numbers, but other operators do the reverse
console.log("a string and the number " + 9);
console.log("9" - 9 === 0);
a string and the number 9 true
// empty array cells are filled with 'null'
var sunset_colors = ["blue", , "purple"]
console.log(sky[1] == null)
true
// JSON objects are dictionary-like structures that contain data and functions
car = {
make: 'honda',
model: 'odyssey',
}
console.log(car.make === 'honda')
console.log("make" in car)
delete car.make
console.log("make" in car)
true true false
// Getters and Setters
var o = {
a: 7,
get b() {
return this.a + 1;
},
set b(x) {
this.a = x / 2
}
};
console.log(o.b)
o.b = 10
console.log(o.a)
8 5
// strings
var s = 'this is a string'
var m = 'this \
is \
a \
string'
console.log(s === m)
false
// a while-loop
x = 0;
while (x < 3){
console.log(x);
x++
}
0 1 2
2
// a for-loop
for(var i=0; i<3; i++){
console.log(i)
}
0 1 2
// for ... in
a = [1,2,3]
for (i in a){
console.log(i)
}
0 1 2
// for ... of
b = [1,2,3]
for (i of a){
console.log(i)
}
1 2 3
// if-else statement
if (true){
var x = 1;
} else if (true) {
var x = 2;
} else {
var x = 3;
}
console.log(x === 1)
true
// a switch statement
switch(1) {
case 1:
console.log(1);
case 2:
console.log(2);
break;
default:
console.log(3)
}
1 2
// a throw statement
function UserException(message) {
this.message = message;
this.name = "UserException";
}
UserException.prototype.toString = function() {
return this.name + ': "' + this.message + '"';
}
// try-except
function afunc() {
throw new UserException("a user error has occurred!");
}
try {
afunc();
} catch (e) {
console.log(e);
} finally {
console.log("do this regardless of what happens");
}
[UserException] {"message":"a user error has occurred!","name":"UserException"} do this regardless of what happens
try {
throw (new Error("the message"));
} catch (e) {
console.log(e.name);
console.log(e.message);
}
Error the message
// function
function afunc(param1, param2) {
console.log(param1);
return param2;
}
var b = afunc('a', 'b')
console.log(b)
c = function(param1) {
console.log(param1)
}
c("c")
a b c
// lambda functions
f = (param1) => {console.log(param1)}
f('a')
a
// class
class Rectangle{
constructor (height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
}
var a = new Rectangle(2, 3)
console.log(a.height === 2)
true
// this: refers to function's execution context
var o = {
data: 1234,
f: function(){
console.log(this.data)
}
}
o.f()
// another way
var o = {data: 1234};
function afunc(){console.log(this.data)};
o.f = afunc;
o.f()
1234 1234
// call + apply: bind function context to object
o = {a: 1, b: 2};
function add(c, d){
return this.a + this.b + c + d;
}
var ans1 = add.call(o,3,4);
var ans2 = add.apply(o,[3,4]);
console.log(ans1 == ans2)
true
// bind: creates new function with new data bound to it
function f(){
return this.a
}
o = {a: 'azkaban'}
var g = f.bind(o)
console.log(g())
azkaban
// function*: a generator function
function* foo(){
var index = 0;
while (index <= 2)
yield index++;
}
iter = foo()
console.log(iter.next())
console.log(iter.next())
console.log(iter.next())
console.log(iter.next())
{"value":0,"done":false} {"value":1,"done":false} {"value":2,"done":false} {"done":true}
// yield*
function* g1() {
yield 2;
yield 3;
}
function* g2() {
yield 1;
yield* g1();
yield 4;
}
var iterator = g2();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
{"value":1,"done":false} {"value":2,"done":false} {"value":3,"done":false} {"value":4,"done":false} {"done":true}
// new
class Car {
constructor(make){
this.make = make
}
}
var c = new Car('honda')
console.log(c.make)
honda
// super
class Honda extends Car {
constructor(model){
super("honda")
this.model = model
}
}
var h = new Honda('crv')
console.log(h.make + ' ' + h.model)
honda crv
// ...obj: only applies to iterables
function aFunc(p1,p2,p3) {
console.log(p1);
console.log(p2);
console.log(p3);
}
aFunc(...[1,2,3])
1 2 3
// ternary operator
var age = 11;
var status = (age >= 18) ? "adult" : "minor";
console.log(status === 'minor')
true
// comma operator
for (var i=1, j=5; i <= j; i++, j--){
console.log(i + ' ' + j)
}
1 5 2 4 3 3
// typeof
typeof 42 === 'number';
typeof "s" === 'string';
typeof true === 'boolean';
typeof null === 'object';
true
// instanceof
d = {a: 1, b: 2}
d instanceof Object
true
// [for (x of y) x] : doesn't work here
[for (i of [ 1, 2, 3 ]) i*i ];
SyntaxError: Unexpected token for
// Numbers
var a = 0o10;
var b = 0x10
console.log(a)
console.log(b)
console.log(Number.MAX_VALUE)
console.log(Number.MIN_VALUE)
console.log(Number.NaN)
console.log(Number.prototype.toExponential(9))
console.log(Number.prototype.toString(9))
console.log(Number.prototype.toFixed(9))
console.log(Number.prototype.toPrecision(9))
8 16 1.7976931348623157e+308 5e-324 null 0.000000000e+0 0 0.000000000 0.00000000
// Math
console.log(String(Math.PI).substring(0, 4) === '3.14')
console.log(Math.sin(Math.PI/2) == 1)
true true
// Date
var d = new Date(2000, 1, 1, 12, 30, 5)
console.log(d)
var today = new Date()
console.log(today)
[Date] "2000-02-01T20:30:05.000Z" [Date] "2016-05-17T20:23:18.111Z"
// Strings
console.log('\xA9')
console.log('Foo!')
console.log(eval("2 + 2"))
console.log('Foo!'.indexOf('!'))
console.log('Foo!'.startsWith('F'))
console.log('Foo!'.charAt(1) === 'o')
var re = /\s*o\s*/;
console.log('Foo!'.split(re))
console.log('Foo!'.toLowerCase())
console.log('Foo!'.toUpperCase())
console.log('Foo!'.startsWith('F'))
console.log('Foo!'.endsWith('!'))
console.log('Foo!'.match(/[A-Z][a-z]+/))
© Foo! 4 3 true true [Array] ["F","","!"] foo! FOO! true true [Array] ["Foo"]
// Map
var names = new Map();
names.set("first", "billy");
names.set("second", "timmy");
names.set("third", "tommy");
console.log(names.get("third"))
for (let i of names){
console.log(i)
}
tommy [Array] ["first","billy"] [Array] ["second","timmy"] [Array] ["third","tommy"]
// Set
var names = new Set();
names.add("billy");
names.add("timmy");
names.add("tommy");
for (let i of names) console.log(i)
names.delete("billy")
console.log(names.size)
billy timmy tommy 2
a = [1,2,3]
b = a.map(function(x){return x+1})
c = a.filter(function(x){return x === 1})
d = a.reduce(function(x,y){return x + y})
a.reverse()
a.sort()
a.slice(0, 2)
e = a.splice(0, 2)
a = e.concat(a)
[Array] [1,2,3]
a = []
for (var i=0; i < 10; i++){
a[i] = i;
}
[Array] [0,1,2,3,4,5,6,7,8,9]