|
Print to console
|
console.log(...) |
|
One line
|
// single line comment |
|
Multi lines
|
/* |
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
|
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
|
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)
|
+, -, *, / |
Add, subtract, multiply, divide
|
% |
Modulus (reminder)
|
= |
Assignment
|
++, -- |
Increment, decrement
|
+=, -=, *=, /=, %= |
Operation and assignment
|
? |
a = (x > y)? b: c; |
==, != |
Equal to, not equal
|
===, !== |
with type
|
>, <, >=, <= |
Greater/Less or equal
|
&&, ||, ! |
And, Or, Not
|
|
Declare a function
|
function myFunc(p1, p2) { |
|
Use a function
|
x = myFunc(1, 5); |
|
Function variable
|
var f = function(p1, p2) { |
|
Use function varialbe
|
x = f(1, 5); |
|
if
|
if (x > y) { |
|
if..else
|
if (x > y) { |
|
if..else if
|
if (x > y) { |
|
switch..case
|
switch(x) { |
while |
var x = 0; |
for |
for (var x = 0; x < y; ++x) { |
continue |
Stop current iteration, continue with next one
|
break |
Stop loop immediately
|
for/in |
var x = [ "abc", "efg", "hij" ]; |
for/of |
var x = [ "abc", "efg", "hij" ]; |
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( |
From index
s, remove r elements, then add e1, e2... |
a.forEach(f) |
Run function f(e) for each element in array
|
|
Literal object
|
var x = { |
|
Constructor
|
function MyObj(nm) { |
|
Create new object
|
var x = new MyObj("cool"); |
|
Use object
|
console.log(x.size); |
No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.