Basics
Console I/O
console.log("Hello World!");
prompt("What is your name?");
Comments
// This is a single line comment.
/* This is a really long comment
that extends multiple lines */
Variables
var a = 0;
Types
var aNumber = 21;
var aString = "Ben";
var aBool = true;
Type Conversions:
- to number:
Number("10")
- to string:
String(123)
Operators
Operation |
Syntax |
addition |
1 + 2 |
subtraction |
1 - 2 |
multiplication |
1 * 2 |
division |
1 / 2 |
modulus |
1 % 2 |
increment |
a++ |
decrement |
a-- |
Comparison
Operation |
Syntax |
equal |
a == b |
not equal |
a != b |
greater than |
a > b |
less than |
a < b |
greater than or equal to |
a >= b |
less than or equal to |
a <= b |
Logical
Operation |
Syntax |
and |
a && b |
or |
a || b |
not |
!a |
Conditionals
if (name == "Joe") {
//...
} else if (name == "Bob") {
//...
} else {
//...
}
(name == "Joe") ? /* if part */ : /* else part */
switch (name) {
case "Joe":
break;
case "Bob":
break;
default:
break;
}
Loops:
for (var i = 0; i < 100; i++) {
// ...
}
for (var val of ["a", "b", "c"]) {
// ...
}
while (condition == true) {
// ...
}
do {
// ...
} while (condition == true);
break
: exit a loop.
continue
: skip to next iteration in loop.
Functions
function (a) {
return a + 100;
}
(a, b) => a + b;
Classes
class aClass {
aPublicField = "hi everyone!";
#aPrivateField = "shh! secret";
constructor(param) {
this.aPublicField = param;
//...
}
randomMethod() {
//...
}
//getter
get someProp() {
return null;
}
//static
static printHi() {
console.log("Hi");
}
}
class aChild extends aClass {
constructor(otherParam) {
super(otherParam);
}
// overridden method
randomMethod() {
// other stuff...
}
}
var myObj = new aClass("foo");
Advanced
Arrays/Lists
var myArr = [a, b, c];
var myDict = {key1: 1, key2: 2, key3: 3};
Function |
Syntax |
search |
indexOf(val) |
push, pop |
push(val)
pop()
|
insert |
splice(start[, deleteCount, items...]) |
concatenate |
concat(arr) |
subarray |
slice(start[, length]) |
sort |
sort([compareFunc(first, second)]) |
loop |
use for...of loop |
map |
map(callback(currentValue[, index, array])) |
Strings
Function |
Syntax |
search |
indexOf(subStr) |
insert |
not available |
replace |
replace(pattern, replacement) |
concatenate |
"a string" + " another string" |
substring |
slice(start[, length]) |
Math
Math.PI
Math.E
Function |
Syntax |
square root |
sqrt() |
exponentiation |
pow(a, b) |
random number |
random() |
absolute value |
abs(a) |
round |
round(a) |
ceiling |
ceil(a) |
floor |
floor(a) |
max |
max(a, b) |
min |
min(a, b) |
sine |
sin(a) |
cosine |
cos(a) |
tangent |
tan(a) |
arcsine |
asin(a) |
arccosine |
acos(a) |
arctangent |
atan(a) |
Dates
...
Files
...
Bitwise Operations
Operation |
Syntax |
AND |
a & b |
OR |
a | b |
XOR |
a ^ b |
NOT |
a ~ b |
Left Shift |
a << b |
Right Shift |
a >> b |
Zero fill right shift |
a >>> b |
Errors
try {
// ...
} catch (e) {
// ...
} finally {
// ...
}
throw new Error(message);
Extra
...