Console
Print to console |
console.log(...)
|
Comments
One line |
// single line comment
|
Multi lines |
/* A multi line comment */
|
Data Types
number
|
3, 3.1, -3.1, 3e5, 3e-5 |
string
|
"abc", 'abc', "", '' |
boolean
|
true, false |
undefined
|
No value |
null
|
Value of nothing |
NaN
|
Not a number |
Numbers
var x = 3.1415;
|
Declare a number |
x.toFixed(2)
|
To string, fixed decimals |
parseInt("2")
|
Convert a string to int |
parseFloat("1.23")
|
Convert a string to float |
Strings
var s = "Hello"
|
Declare and assign a string |
s.length
|
Length of string |
s.charAt(0)
|
Access a character at index |
s.indexOf("el")
|
Index of a substring |
s.slice(2, 4)
|
Part of string (start, end) |
Arithmetic Operators
+, -, *, /
|
Add, subtract, multiply, divide |
%
|
Modulus (reminder) |
=
|
Assignment |
++, --
|
Increment, decrement |
+=, -=, *=, /=, %=
|
Operation and assignment |
?
|
a = (x > y)? b: c;
|
Comparisons
==, !=
|
Equal to, not equal |
===, !==
|
with type |
>, <, >=, <=
|
Greater/Less or equal |
&&, ||, !
|
And, Or, Not |
Functions
Declare a function |
function myFunc(p1, p2) { statements; return p1 + p2; }
|
Use a function |
x = myFunc(1, 5);
|
Function variable |
var f = function(p1, p2) { statements; return p1 + p2; };
|
Use function varialbe |
x = f(1, 5);
|
|
|
Conditionals
if |
if (x > y) { statements; }
|
if..else |
if (x > y) { statements; } else { statements; }
|
if..else if |
if (x > y) { statements; } else if (x > z) { statements; } else { statements; }
|
switch..case |
switch(x) { case 1: statements; break; case 2: statements; break; default: statements; }
|
Loops
while
|
var x = 0; while (x < y) { statements; ++x; }
|
for
|
for (var x = 0; x < y; ++x) { statements; }
|
continue
|
Stop current iteration, continue with next one |
break
|
Stop loop immediately |
for/in
|
var x = [ "abc", "efg", "hij" ]; for (i in x) { statements; // i = 0,1,2... }
|
for/of
|
var x = [ "abc", "efg", "hij" ]; for (i of x) { statements; // i = "abc","efg",.. }
|
Arrays
var a = [8, "hi", 6]
|
Declare and assign |
var a = []
|
Declare empty array |
a[0]
|
Extract the first element |
a[0] = "xx"
|
Set the first element |
a.length
|
Length of array |
a.push(17)
|
Add element to array |
a.pop()
|
Remove the last element |
a.splice( s, r, e1, e2..)
|
From index s , remove r elements, then add e1, e2... |
a.forEach(f)
|
Run function f(e) for each element in array |
Objects
Literal object |
var x = { name: "cool", size: 10, sayHi = function() { console.log(this.name); } }
|
Constructor |
function MyObj(nm) { this.name = nm; this.size = 10; this.sayHi = function() { console.log(this.name); } }
|
Create new object |
var x = new MyObj("cool");
|
Use object |
console.log(x.size); x.sayHi();
|
|
Created By
Metadata
Favourited By
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets