Js Cheat Sheet
Js Cheat Sheet
Numbers
let amount = 6 ;
Variables
let x = null ;
var a;
Strings
// => 21
Arithmetic Operators
5 + 5 = 10 // Addition
10 - 5 = 5 // Subtraction
5 * 10 = 50 // Multiplication
10 / 5 = 2 // Division
10 % 5 = 0 // Modulo
Comments
// This line will denote a comment
/*
The below configuration must be
changed before deployment.
*/
Assignment Operators
number = number + 10 ;
number += 10 ;
console . log (number);
// => 120
String Interpolation
let age = 7 ;
// String concatenation
// String interpolation
let Keyword
let count;
count = 10 ;
const Keyword
const numberOfColumns = 4 ;
numberOfColumns = 8 ;
#JavaScript Conditionals
if Statement
Ternary Operator
var x= 1 ;
// => true
Operators
Comparison Operators
1 > 3 // false
3 > 1 // true
1 === 1 // true
1 === 2 // false
Logical Operator !
// => false
else if
const size = 10 ;
if (size > 100 ) {
} else {
// Print: Small
switch Statement
switch (food) {
case 'oyster' :
break ;
case 'pizza' :
console . log ( 'A delicious pie' );
break ;
default :
== vs ===
0 == false // true
The == just check the value, === check both the value and the type.
#JavaScript Functions
Functions
// Defining the function:
sum ( 3 , 6 ); // 9
Anonymous Functions
// Named function
function rocketToMars () {
return 'BOOM!' ;
// Anonymous function
return 'BOOM!' ;
};
With no arguments
const printHello = () => {
};
};
// => 60
num1 + num2;
Calling Functions
// Defining the function
sum ( 2 , 4 ); // 6
Function Expressions
return 'Woof!' ;
Function Parameters
// The parameter is name
Function Declaration
function add ( num1, num2 ) {
#JavaScript Scope
Scope
function myFunction () {
if (isLoggedIn == true ) {
// Uncaught ReferenceError...
Global Variables
// Variable declared globally
const color = 'blue' ;
function printColor () {
let vs var
// i not accessible ❌
// i accessible ✔️
// i accessible ✔️
var is scoped to the nearest function block, and let is scoped to the nearest
enclosing block.
Loops with closures
// Prints 3 thrice, not what we meant.
The variable has its own copy using let, and the variable has shared copy
using var.
#JavaScript Arrays
Arrays
Property .length
const numbers = [ 1 , 2 , 3 , 4 ];
numbers. length // 4
Index
// Accessing an array element
push ✔
pop ✔
unshift ✔ ✔
shift ✔ ✔
Method .push()
// Adding a single element:
const numbers = [ 1 , 2 ];
numbers. push ( 3 , 4 , 5 );
Add items to the end and returns the new array length.
Method .pop()
Remove an item from the end and returns the removed item.
Method .shift()
Remove an item from the beginning and returns the removed item.
Method .unshift()
Add items to the beginning and returns the new array length.
Method .concat()
const numbers = [ 3 , 2 , 1 ]
const newFirstNumber = 4
// => [ 4, 3, 2, 1 ]
// => [ 3, 2, 1, 4 ]
if you want to avoid mutating your original array, you can use concat.
#JavaScript Loops
While Loop
while (condition) {
let i = 0 ;
while (i < 5 ) {
i++;
Reverse Loop
// => 2. banana
// => 1. orange
// => 0. apple
Do…While Statement
x = 0
i = 0
do {
x = x + i;
i++;
} while (i < 5 );
// => 0 1 3 6 10
For Loop
};
// => 0, 1, 2, 3
Looping Through Arrays
if (i > 5 ) {
break ;
}
// => 0 1 2 3 4 5
Continue
if (i === 3 ) { continue ; }
Nested
for...in loop
// => 0
// => 1
// => 2
for...of loop
// => apple
// => orange
// => banana
#JavaScript Iterators
return number + 5 ;
};
let f = plusFive;
plusFive ( 3 ); // 8
Callback Functions
return n % 2 == 0 ;
{isNumEven}.` )
printMsg (isEven, 4 );
const numbers = [ 1 , 2 , 3 , 4 ];
"Natasha" , "Bobby" ];
});
const numbers = [ 28 , 77 , 45 , 99 , 27 ];
});
const randomNumbers = [ 4 , 11 , 42 , 14 , 39 ];
});
#JavaScript Objects
Accessing Properties
const apple = {
color : 'Green' ,
'$4/kg' }
};
Naming Properties
// Example of invalid key names
const trainSchedule = {
platform num : 10 ,
40 - 10 + 2 : 30 ,
+ compartment : 'C'
}
Non-existent properties
const classElection = {
};
Mutable
const student = {
name : 'Sheldon' ,
score : 100 ,
grade : 'A' ,
const person = {
name : 'Tom' ,
age : '22' ,
};
Delete operator
const person = {
firstName : "Matilda" ,
age : 27 ,
hobby : "knitting" ,
};
delete person. hobby ; // or delete person[hobby];
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
}
*/
Objects as arguments
const origNum = 8 ;
num = 7 ;
};
this Keyword
const cat = {
name : 'Pipey' ,
age : 8 ,
whatName () {
};
Factory functions
// A factory function that accepts 'name',
// 'age', and 'breed' parameters to return
// a customized dog object.
return {
name : name,
age : age,
breed : breed,
bark () {
};
};
Methods
const engine = {
start ( adverb ) {
{adverb}...` );
},
sputter : () => {
};
const myCat = {
_name : 'Dottie' ,
get name () {
},
};
#JavaScript Classes
Static Methods
class Dog {
constructor ( name ) {
introduce () {
!' );
// A static method
static bark () {
Class
class Song {
constructor () {
this . title ;
this . author ;
play () {
Class Constructor
class Song {
constructor ( title, artist ) {
'Queen' );
Class Methods
class Song {
play () {
stop () {
}
}
extends
// Parent class
class Media {
constructor ( info ) {
// Child class
constructor ( songData ) {
super (songData);
publishDate : 1975
});
#JavaScript Modules
Export
// myMath.js
// Default export
return x + y
// Normal export
return x - y
// Multiple exports
return x * y
}
function duplicate ( x ){
return x * 2
export {
multiply,
duplicate
Import
// main.js
'./myMath.js' ;
// index.html
Export Module
// myMath.js
function add ( x,y ){
return x + y
return x - y
return x * y
function duplicate ( x ){
return x * 2
module . exports = {
add,
subtract,
multiply,
duplicate
Require Module
// main.js
#JavaScript Promises
Promise states
// An asynchronous operation.
if (res) {
resolve ( 'Resolved!' );
else {
reject ( Error ( 'Error' ));
});
Executor function
resolve ( 'Resolved!' );
};
setTimeout()
};
.then() method
resolve ( 'Result' );
}, 200 );
});
}, (err) => {
});
.catch() method
setTimeout ( () => {
Unconditionally.' ));
}, 1000 );
});
promise. then ( (res) => {
});
});
Promise.all()
setTimeout ( () => {
resolve ( 3 );
}, 300 );
});
setTimeout ( () => {
resolve ( 2 );
}, 200 );
});
});
setTimeout ( () => {
resolve ( '*' );
}, 1000 );
});
};
};
};
Creating
promise!' );
};
}, (err) => {
});
setTimeout ( () => {
if (success) {
} else {
}, timeout);
});
try {
} catch (e) {
#JavaScript Async-Await
Asynchronous
function helloWorld () {
setTimeout ( () => {
}, 2000 );
});
}
Expression
Resolving Promises
let pro2 = 44 ;
let pro3 = new Promise ( function ( resolve,
reject ) {
});
});
function helloWorld () {
setTimeout ( () => {
}, 2000 );
});
}
async function msg () {
Error Handling
try {
} catch (e) {
function helloWorld () {
setTimeout ( () => {
resolve ( 'Hello World!' );
}, 2000 );
});
#JavaScript Requests
JSON
const jsonObj = {
"name": "Rick",
"id": "11A",
"level": 4
} ;
};
POST
const data = {
fish : 'Salmon' ,
units : 5
};
};
fetch api
fetch (url, {
method : 'POST' ,
headers : {
'Content-type' : 'application/json' ,
'apikey' : apiKey
},
body : data
if (response. ok ) {
}, networkError => {
})
JSON Formatted
fetch ( 'url-that-returns-JSON' )
});
fetch ( 'url' )
. then (
response => {
},
rejection => {
);
fetch ( 'https://api-xxx.com/endpoint' , {
method : 'POST' ,
if (response. ok ){
}, networkError => {
})
try {
'no-cache' });
if (response. ok ){
catch (error){