Javascript
Cheatsheet
Variable and Data Types
Hello World
Description: Print Hello World.
console .log ( "Hello World" ) ;
Data Type
Description: There are 8 types of data in Javascript.
1 Number
150 9.81 //Decimal
2.99e8 1E5 1.23e-3 //Exponential
0b10001101 0B10110011 //Binary
0O552 //Octal
0xF36A //Hex
1_000_000_000 //Numeric separators
2 String
"foo" 'boo'
`Name: ${ myName } ` //String Template
3 Boolean
true false
4 BigInt
BigInt ( "4262469846813823682736836827368" )
1382438263843 n 0x5BC294D4E n
5 Undefined
void 1
6 Null
null
7 Object
{ name: "Mary" , score: 82 }
[ 2 , 4 , 8 , 16 ] //Array is an object
8 Symbol
Symbol ( "key" )
Variables & Constants
Description: Assign memory slot a name then read/write data to the slot.
let myVar = 10 ;
let a = 20 , b = 30 , c = 40 ;
var myVar2 = 12 ; // The old way to declare variable
const PI = 3.14 ;
Type Operator
Description: Check the data type of a variable.
// check the data type of a variable
typeof ( myVar ) ;
// check whether variable is an instance of a class
myCar instanceof Car ;
Void
Description: Return an undefined value.
let undefinedVar = void 1 ;
Operators
Arithmetic
Description: Perform basic mathematics operation on variable and values.
let x = 5 , y = 3 , z ;
Arithmetics
z = x + y ; //z = 5+3 = 8
z = x - y ; //z = 5-3 = 2
z = x * y ; //z = 5x3 = 15
z = x / y ; //z = 5/3 = 1.6667
z = x % y ; //z = 5 mod 3 = 2
z = x ** y ; //z = 5^3 = 125
Arithmetic Assignment
x += y ; //x = x+y
x -= y ; //x = x-y
x *= y ; //x = x*y
x /= y ; //x = x/y
x %= y ; //x = x%y
x **= y ; //x = x**y
Increment/Decrement
x ++; // x+= 1; (return value first then do increment)
x --; // x-= 1;
++x ; // x+= 1; (increment first then return value)
--x ; // x-= 1;
Parentheses
z = ( ( x *3.5 ) + y ) / 8 ;
Comparison
Description: Compare two value and return boolean result.
let bool_ans , d1 = 3 , d2 = 5 ;
Comparison
bool_ans = ( d1 == d2 ) ; //is 3 equal 5? -> False
bool_ans = ( d1 != d2 ) ; //is 3 not equal 5? -> True
bool_ans = ( d1 > d2 ) ; //is 3 larger than 5? -> False
bool_ans = ( d1 < d2 ) ; //is 3 smaller than 5? -> True
bool_ans = ( d1 >= d2 ) ; //is 3 larger or equal 5? -> False
bool_ans = ( d1 <= d2 ) ; //is 3 small or equal 5? -> True
Comparison with types
bool_ans = ( d1 === d2 ) ; //is 3 equal 5 and share same data type? -> False
bool_ans = ( d1 !== d2 ) ; //is 3 and 5 neither equal value nor the same data type? -> True
Boolean
Description: Perform boolean mathematics on Boolean variable and values.
Boolean
bool_ans = !true //flip the true/false value -> false
bool_ans = true && false ; //return True when BOTH values are true -> false
bool_ans = true || false ; //return True when ANY values are true -> true
Boolean Assignment
bool_ans &&= true ; //bool_ans = bool_ans && true
bool_ans ||= true ; //bool_ans = bool_ans || true
Decision
Description: Choose a value between two option base on comparison operation.
foo = ( d1 > d2 ) ? 10 : 2 ; //if condition is true return 10 (left), else return 2 (right).
foo = null ?? 100 ; //return left by default. If it is null/undefined, return right
foo ??= 100 ; // if foo is null, assign 100, else foo does not change.
Bitwise
Description: Operating on each bit's value within a variable or value.
let c1 = 0b01000010 , mask = 0b00110010 , bit_ans ;
Bitwise
bit_ans = c1 | mask ; // or -> 01110010
bit_ans = c1 & mask ; // and -> 00000010
bit_ans = c1 ^ mask ; // xor -> 01110000
bit_ans = ~c1 ; // not -> 10111101
Bitwise Shift
bit_ans = c1 << 1 ; // left shift -> 10000100
bit_ans = c1 >> 2 ; // right shift -> 00010000
bit_ans = c1 >>> 2 ; // unsigned right shift -> 00010000
Bitwise Assignment
bit_ans |= mask ; // bit_ans = bit_ans | mask
bit_ans &= mask ; // bit_ans = bit_ans & mask
bit_ans ^= mask ; // bit_ans = bit_ans ^ mask
bit_ans <<= mask ; // bit_ans = bit_ans << mask
bit_ans >>= mask ; // bit_ans = bit_ans >> mask
bit_ans >>>= mask ; // bit_ans = bit_ans >>> mask
Condition and Loop
If...else
Description: Select a block of code to run base on a set of conditions.
if ( x == 2 ){
console .log ( "x is 2" ) ;
}
else if ( y < ( x - 4 ) ){
console .log ( "y is smaller than (x-4)" ) ;
}
else {
console .log ( "none of the above is true" ) ;
}
Switch...case
Description: Run a selected block of code to run base on the value of a variable.
switch ( x ){
case 1 :
console .log ( "x is 1" ) ;
break ;
case 2 :
console .log ( "x is 2" ) ;
break ;
case 3 :
console .log ( "x is 3" ) ;
break ;
default :
console .log ( "none of the above" ) ;
break ;
}
While Loops
Description: Repeat a block of code when a given condition is met.
While Loop
let x = 1 ;
while ( ( x % 13 ) != 0 ){
// do something until a multiples of 13 is found
x += 7 ;
}
while ( true ){
// loop forever
}
Do...while Loop
let x = 1 ;
do {
// loop at least once, then decided by the while condition
x += 7 ;
} while ( ( x % 13 ) != 0 )
For Loops
Description: Repeat a block of code for a known amount.
For Loop
for ( let i = 0 ; i < 5 ; i ++){
/* (counter; exit condition; update counter) */
// do something 5 times
}
for ( ;;){
// loop forever
}
For...of Loop
const arr = [ 10 , 5 , 8 , 9 , 4 ] ;
for ( let x of arr ){
// loop through every value in array or string
}
For...in Loop
const carObj = { type :"car" , price :2500 , qnt :10 } ;
for ( let x in carObj ){
// loop through every object property
}
Break
Description: Exit the loop entirely.
while ( x > num ){
// ...
if ( my_condition ){
break ; /* exit the while loop */
}
}
Continue
Description: Exit the current iteration and start the next iteration.
while ( x > num ){
// ...
if ( my_condition ){
continue ; /* skip the remaining of this iteration */
}
// ...
}
Function
Functions
Description: A re-usable block of code which can take input values to generate an output value.
Default Style:
function toCelsius ( fahrenheit ){ // Declaration
return ( 5 /9 *( fahrenheit -32 ) ) ;
}
let sum = toCelsius ( 100 ) ; // Use function
Alternative Form:
(1) - Function Object
const toCelsius1 = new Function ( "fahrenheit" , "return (5/9) * (fahrenheit-32);" ) ;
(2) - Anonymous Function
const toCelsius2 = function ( fahrenheit ){
return ( 5 /9 *( fahrenheit -32 ) ) ;
}
(3) - Arrow Function
const toCelsius = ( fahrenheit ) => ( 5 /9 ) * ( fahrenheit -32 ) ;
// (param) => return contents
(4) - Immediately Invoked Function
( function invokeFunc (){
// Run immediately after declaration
} ) () ;
Default Parameter Value
Description: Provide a default input value if it is not given.
function myFunc ( param = 1 ){
return param *2 ;
}
myFunc ( 5) ;
myFunc ( ) ; // --- myFunc(1) by default ---
Indefinite Arguments
Description: Accept varying amount of input in similar type.
function myFunc2 ( ...args ){
for ( a of args ){
// --- Loop over every arguments as array ---
}
}
myFunc2 ( 1 ,3 ,5 ,7 ) ;
Function Variable
Description: Assign function to a variable. Programmatically select functions to execute.
function func1 (){
}
function func2 (){
}
let funcVar = func2 ;
funcVar () ; // Call func2()
Nested Function
Description: Function can be nested inside each other.
function outFunc (){
// ---------------------
// outFunc Task
// ---------------------
function inFunc (){
// ---------------------
// inFunc Task
// ---------------------
}
inFunc ()
}
Generator Functions
Description: Function that pause its execution when yielding a value and resume later.
function * generatorFunc ( i ){
yield i ;
yield i+1 ;
yield i+2 ;
return i+10 ;
}
const gen = generatorFunc ( 10 ) ;
gen .next () .value ; // 10
gen .next () .value ; // 11
gen .next () .value ; // 12
gen .next () .value ; // 20
Object
Object
Description: A bundle of variables and functions.
const person = {
/* --- Variables (aka. Properties) --- */
name :"Tom" ,
age :25 ,
gender :"Male" ,
/* --- Functions (aka. Methods) --- */
info :function (){
}
} ;
person .name ;
person [ "name" ] ;
person .info () ;
Add/Delete Property
Description: Modify the content of an object.
// Add/delete property
person .height = 178 ;
delete person .age ;
// Add/delete method
person .sayHi = function (){ }
delete person .sayHi ;
Function Constructor
Description: A function which create objects with the same format repeatedly.
/* --- Function constructor --- */
function Person ( n ,a ,g ){
this .name = n ;
this .age = a ;
this .gender = g ;
this .info = function (){ } ; // Default parameter
}
const person3 = new Person ( "May" , 24 , "Female" ) ; // <= Using function constructor here
Person .prototype .sayHi = function (){
} ;
Getter & Setter
Description: Read/writre into object property with special operation, instead of direct assignment.
const temperature = {
celcius :25 ,
get fahrenheit (){ /* Getter */
return this .celcius *9 /5 +32 ;
} ,
set fahrenheit ( f ){ /* Setter */
this .celcius = ( f -32 ) *5 /9 ;
}
}
temperature .fahrenheit = 50 ;
console .log ( temperature .celcius ) ; // >> 10
console .log ( temperature .fahrenheit ) ; // >> 50
Nested Object
Description: Object can be defined in an object.
const person2 = {
name :"Jack" ,
age :35 ,
gender :"Male" ,
vehicle :{ // <= Nested Object
brand :"Toyota" ,
model :"Corolla" ,
year :2025
}
}
person2 .vehicle .brand ; // >> Toyota
person2 [ "vehicle" ] [ "brand" ] ; // >> Toyota
Class
Class
Description: A blueprint of object for repeated creation.
class Airplane {
constructor ( m ,y ){
/* Declare properties in constructor function */
this .model = m ;
this .year = y ;
}
takeoff ( ){
/* Do something that takeoff the plane */
}
}
let plane = new Airplane ( "Boeing 737" , 2010 ) ;
plane .takeoff () ;
Inheritance
Description: Create a new class by extending features bases on an existing class.
class FighterJet extends Airplane {
constructor ( m ,y ,ap ){
super ( m ,y )
this .attackPower = ap ;
}
attack ( ){
/* Do something that attack */
}
}
let f35 = new FighterJet ( "F35" , 2018 , 120 ) ;
f35 .takeoff () ;
f35 .attack () ;
Static
Description: Property/method which is defined under the class.
class Math {
static PI = 3.14 ;
static cos (){
// Calculate cosine
}
static sqrt (){
// Calculate square
}
}
let x = Math .cos () ;
console .log ( Math .PI ) ;
Priavte Property/Method
Description: Internal data/operaion which can only be used inside the class.
class MyClass {
#privateVar = 1 ; // Internal Data
publicVar = 2 ;
#privateFunc (){
// -----------------------
// Internal Operations
// -----------------------
this .#privateVar += 1 ; // <= Use private property
}
publicFunc (){
// -----------------------
// Do Something
// -----------------------
this .#privateFunc () ; // <= Use private method
}
}
let myclass = new MyClass () ;
myclass .publicFunc () ;
myclass .publicVar = 6 ;
/* Error (Not available outisde MyClass) */
myclass .privateFunc () ;
myclass .privateVar = 7 ;
Error Handling
Try...Catch...Finally
Description: Run a block of risky code. If it crash, run another block as follow-up.
try {
// -------------------------
// Do task that may crash
// -------------------------
throw "Error Message" ; // throw -> Artifical crash from programmer
}
catch ( err ){
// --------------------------------------------
// Error Handling (run if try block crashed)
// --------------------------------------------
}
finally {
// ---------------------------------------
// Run regradless of try...catch result
// ---------------------------------------
}
Example:
function area ( x ,y ){
if ( x < 0 || y < 0 ){
throw "Negative Side Length" ; // Undesireble condition -> throw
}
return x *y ;
}
try {
area ( -1 ,5 ) ; // <= Do something risky
}
catch ( err ){
console .log ( "Error is " , err ) ; // >> Error is Negative Side Length
}
finally {
// ...
}
Asynchronous
Async...Await
Description: Run an asynchronous function as if it is normal line-by-line code.
async function myPostRequest (){
const data = await fetch ( 'https://jsonplaceholder.typicode.com/posts' ) ; // <= wait for asynchronus operation finish
// ---------------------------------
// Display Data on screen
// ---------------------------------
}
myPostRequest () ;
File System
Export...Import
Description: Share variable and function across files.
/* --- util.js --- */
export const PI = 3.14 ; // export one variable
let x = 10 , y = 20 ;
export { x , y } ; // export multiple data
/* --- main.js --- */
import { PI , x , y } from './util.js' ;
Default Export
Description: Assign one export data as the only default export.
/* --- util.js --- */
let x = 10 ;
export default x ; // <- the only export data
/* --- main.js --- */
import y from './util.js' ;
Debug
Debugger
Description: Use code to create a breakpoint which trigger when run through.
function myFunc (){
let x = 10 ;
debugger; // <- Breakpoint (F12 developer tool need to be turned on to trigger)
x += 5 ;
}