JS cheat sheet
Basics
On page script
<script type="text/javascript"> ...
</script>
Include external JS file
<script src="filename.js"></script>
Delay - 1 second timeout
setTimeout(function () {
}, 1000);
Functions
function addNumbers(a, b) {
return a + b; ;
}
x = addNumbers(1, 2);
Edit DOM element
document.getElementById("elementID").innerHTML = "Hello World!";
Output
console.log(a); // write to the browser console
document.write(a); // write to the HTML
alert(a); // output in an alert box
confirm("Really?"); // yes/no dialog, returns true/false depending on user click
prompt("Your age?","0"); // input dialog. Second argument is the initial value
Comments
/* Multi line
comment */
// One line
If - Else
if ((age >= 14) && (age < 19)) { // logical condition
status = "Eligible."; // executed if condition is true
} else { // else block is optional
status = "Not eligible."; // executed if condition is false
}
Switch Statement
switch (new Date().getDay()) { // input is current day
case 6: // if (day == 6)
text = "Saturday";
break;
case 0: // if (day == 0)
text = "Sunday";
break;
default: // else...
text = "Whatever";
}
Loops
While Loop
while (condition) {
// code block to be executed
}
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Reverse Loop
const fruits = ["apple", "orange", "banana"];
for (let i = fruits.length - 1; i >= 0; i--) {
console.log(`${i}. ${fruits[i]}`);
}
// => 2. banana
// => 1. orange
// => 0. apple
Do…While Statement
x = 0
i = 0
do {
x = x + i;
console.log(x)
i++;
} while (i < 5);
// => 0 1 3 6 10
For Loop
for (let i = 0; i < 4; i += 1) {
console.log(i);
};
// => 0, 1, 2, 3
Looping Through Arrays
for (let i = 0; i < array.length; i++){
console.log(array[i]);
}
// => Every item in the array
Break
for (let i = 0; i < 99; i += 1) {
if (i > 5) {
break;
}
console.log(i)
}
// => 0 1 2 3 4 5
Continue
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
Nested
for (let i = 0; i < 2; i += 1) {
for (let j = 0; j < 3; j += 1) {
console.log(`${i}-${j}`);
}
}
for...of loop
const fruits = ["apple", "orange", "banana"];
for (let fruit of fruits) {
console.log(fruit);
}
// => apple
// => orange
// => banana
for...in loop
const fruits = ["apple", "orange", "banana"];
for (let index in fruits) {
console.log(index);
}
// => 0
// => 1
// => 2
for...in loop (Object)
let user = {
firstName: 'Lady',
lastName: 'Gaga',
gender: 'female'
}
for (let index in user) {
alert(index); // firstName, lastName, gender
alert(user[index]); // 'Lady', 'Gaga', 'female'
}
Variables x
var a; // variable
var b = "init"; // string
var c = "Hi" + " " + "Joe"; // = "Hi Joe"
var d = 1 + 2 + "3"; // = "33"
var e = [2,3,5,8]; // array
var f = false; // boolean
var g = /()/; // RegEx
var h = function(){}; // function object
const PI = 3.14; // constant
var a = 1, b = 2, c = a + b; // one line
let z = 'zzz'; // block scope local variable
Strict mode
"use strict"; // Use strict mode to write secure code
x = 1; // Throws an error because variable is not declared
Values
false, true // boolean
18, 3.14, 0b10011, 0xF6, NaN // number
"flower", 'John' // string
undefined, null , Infinity // special
Operators
a = b + c - d; // addition, substraction
a = b * (c / d); // multiplication, division
x = 100 % 48; // modulo. 100 / 48 remainder = 4
a++; b--; // postfix increment and decrement
Arithmetic
a * (b + c) // grouping
person.age // member
person[age] // member
!(a == b) // logical not
a != b // not equal
typeof a // type (number, object, function...)
x << 2 x >> 3 // minary shifting
a = b // assignment
a == b // equals
a != b // unequal
a === b // strict equal
a !== b // strict unequal
a < b a > b // less and greater than
a <= b a >= b // less or equal, greater or eq
a += b // a = a + b (works with - * %...)
a && b // logical and
a || b // logical or
Data types
var age = 18; // number
var name = "Jane"; // string
var name = {first:"Jane", last:"Doe"}; // object
var truth = false; // boolean
var sheets = ["HTML","CSS","JS"]; // array
var a; typeof a; // undefined
var a = null; // value null
Objects
var student = { // object name
firstName:"Jane", // list of properties and values
lastName:"Doe",
age:18,
height:170,
fullName : function() { // object function
return this.firstName + " " + this.lastName;
}
};
student.age = 19; // setting value
student[age]++; // incrementing
name = student.fullName(); // call object function
Strings
var abc = "abcdefghijklmnopqrstuvwxyz";
var esc = 'I don\'t \n know'; // \n new line
var len = abc.length; // string length
abc.indexOf("lmno"); // find substring, -1 if doesn't contain
abc.lastIndexOf("lmno"); // last occurance
abc.slice(3, 6); // cuts out "def", negative values count from behind
abc.replace("abc","123"); // find and replace, takes regular expressions
abc.toUpperCase(); // convert to upper case
abc.toLowerCase(); // convert to lower case
abc.concat(" ", str2); // abc + " " + str2
abc.charAt(2); // character at index: "c"
abc[2]; // unsafe, abc[2] = "C" doesn't work
abc.charCodeAt(2); // character code at index: "c" -> 99
abc.split(","); // splitting a string on commas gives an array
abc.split(""); // splitting on characters
128.toString(16); // number to hex(16), octal (8) or binary (2)
Numbers & Math
var pi = 3.141;
pi.toFixed(0); // returns 3
pi.toFixed(2); // returns 3.14 - for working with money
pi.toPrecision(2) // returns 3.1
pi.valueOf(); // returns number
Number(true); // converts to number
Number(new Date()) // number of milliseconds since 1970
parseInt("3 months"); // returns the first number: 3
parseFloat("3.5 days"); // returns 3.5
Number.MAX_VALUE // largest possible JS number
Number.MIN_VALUE // smallest possible JS number
Number.NEGATIVE_INFINITY// -Infinity
Number.POSITIVE_INFINITY// Infinity
Math.
var pi = Math.PI; // 3.141592653589793
Math.round(4.4); // = 4 - rounded
Math.round(4.5); // = 5
Math.pow(2,8); // = 256 - 2 to the power of 8
Math.sqrt(49); // = 7 - square root
Math.abs(-3.14); // = 3.14 - absolute, positive value
Math.ceil(3.14); // = 4 - rounded up
Math.floor(3.99); // = 3 - rounded down
Math.sin(0); // = 0 - sine
Math.cos(Math.PI); // OTHERS: tan,atan,asin,acos,
Math.min(0, 3, -2, 2); // = -2 - the lowest value
Math.max(0, 3, -2, 2); // = 3 - the highest value
Math.log(1); // = 0 natural logarithm
Math.exp(1); // = 2.7182pow(E,x)
Math.random(); // random number between 0 and 1
Math.floor(Math.random() * 5) + 1; // random integer, from 1 to 5
Constants like Math.PI:
E, PI, SQRT2, SQRT1_2, LN2, LN10, LOG2E, Log10E
Dates
//Fri Mar 24 2023 13:37:29 GMT+0200 (EET)
var d = new Date();
//1679657849400 miliseconds passed since 1970
Number(d)
Date("2017-06-23"); // date declaration
Date("2017"); // is set to Jan 01
Date("2017-06-23T12:00:00-09:45"); // date - time YYYY-MM-DDTHH:MM:SSZ
Date("June 23 2017"); // long date format
Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time
Get Times
var d = new Date();
a = d.getDay(); // getting the weekday
getDate(); // day as a number (1-31)
getDay(); // weekday as a number (0-6)
getFullYear(); // four digit year (yyyy)
getHours(); // hour (0-23)
getMilliseconds(); // milliseconds (0-999)
getMinutes(); // minutes (0-59)
getMonth(); // month (0-11)
getSeconds(); // seconds (0-59)
getTime(); // milliseconds since 1970
Setting part of a date
var d = new Date();
d.setDate(d.getDate() + 7); // adds a week to a date
setDate(); // day as a number (1-31)
setFullYear(); // year (optionally month and day)
setHours(); // hour (0-23)
setMilliseconds(); // milliseconds (0-999)
setMinutes(); // minutes (0-59)
setMonth(); // month (0-11)
setSeconds(); // seconds (0-59)
setTime(); // milliseconds since 1970)
Events
<button onclick="myFunction();">
Click here
</button>
Mouse
onclick, oncontextmenu, ondblclick, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseover, onmouseout, onmouseup
Keyboard
onkeydown, onkeypress, onkeyup
Frame
onabort, onbeforeunload, onerror, onhashchange, onload, onpageshow, onpagehide, onresize, onscroll, onunload
Form
onblur, onchange, onfocus, onfocusin, onfocusout, oninput, oninvalid, onreset, onsearch, onselect, onsubmit
Drag
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop
Clipboard
oncopy, oncut, onpaste
Media
onabort, oncanplay, oncanplaythrough, ondurationchange, onended, onerror, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, onsuspend, ontimeupdate, onvolumechange, onwaiting
Animation
animationend, animationiteration, animationstart
Miscellaneous
transitionend, onmessage, onmousewheel, ononline, onoffline, onpopstate, onshow, onstorage, ontoggle, onwheel, ontouchcancel, ontouchend, ontouchmove, ontouchstart
Arrays
var dogs = ["Bulldog", "Beagle", "Labrador"];
var dogs = new Array("Bulldog", "Beagle", "Labrador"); // declaration
alert(dogs[1]); // access value at index, first item being [0]
dogs[0] = "Bull Terier"; // change the first item
for (var i = 0; i < dogs.length; i++) { // parsing with array.length
console.log(dogs[i]);
}
Methods
dogs.toString(); // convert to string: results "Bulldog,Beagle,Labrador"
dogs.join(" * "); // join: "Bulldog * Beagle * Labrador"
dogs.pop(); // remove last element
dogs.push("Chihuahua"); // add new element to the end
dogs[dogs.length] = "Chihuahua"; // the same as push
dogs.shift(); // remove first element
dogs.unshift("Chihuahua"); // add new element to the beginning
delete dogs[0]; // change element to undefined (not recommended)
dogs.splice(2, 0, "Pug", "Boxer"); // add elements (where, how many to remove, element list)
var animals = dogs.concat(cats,birds); // join two arrays (dogs followed by cats and birds)
dogs.slice(1,4); // elements from [1] to [4-1]
dogs.sort(); // sort string alphabetically
dogs.reverse(); // sort string in descending order
x.sort(function(a, b){return a - b}); // numeric sort
x.sort(function(a, b){return b - a}); // numeric descending sort
highest = x[0]; // first item in sorted array is the lowest (or highest) value
x.sort(function(a, b){return 0.5 - Math.random()}); // random order sort
dogs.forEach(element => { // Перебор элементов массива через foreach
console.log(element);
});
Global functions
eval(); // executes a string as if it was script code
String(23); // return string from number
(23).toString(); // return string from number
Number("23"); // return number from string
decodeURI(enc); // decode URI. Result: "my page.asp"
encodeURI(uri); // encode URI. Result: "my%page.asp"
decodeURIComponent(enc); // decode a URI component
encodeURIComponent(uri); // encode a URI component
isFinite(); // is variable a finite, legal number
isNaN(); // is variable an illegal number
parseFloat(); // returns floating point number of string
parseInt(); // parses a string and returns an integer
Errors
try { // block of code to try
undefinedFunction();
}
catch(err) { // block to handle errors
console.log(err.message);
}
Throw error
throw "My error message"; // throw a text
Input validation
var x = document.getElementById("mynum").value; // get input value
try {
if(x == "") throw "empty"; // error cases
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x > 10) throw "too high";
}
catch(err) { // if there's an error
document.write("Input is " + err); // output error
console.error(err); // write the error in console
}
finally {
document.write("</br />Done"); // executed regardless of the try / catch result
}
Error name values
RangeError
A number is "out of range"
ReferenceError
An illegal reference has occurred
SyntaxError
A syntax error has occurred
TypeError
A type error has occurred
URIError
An encodeURI() error has occurred
JSON j
var str = '{"names":[' + // crate JSON object
'{"first":"Hakuna","lastN":"Matata" },' +
'{"first":"Jane","lastN":"Doe" },' +
'{"first":"Air","last":"Jordan" }]}';
obj = JSON.parse(str); // parse
document.write(obj.names[1].first); // access
Send
var myObj = { "name":"Jane", "age":18, "city":"Chicago" }; // create object
var myJSON = JSON.stringify(myObj); // stringify
window.location = "demo.php?x=" + myJSON; // send to php
Storing and retrieving
myObj = { "name":"Jane", "age":18, "city":"Chicago" };
myJSON = JSON.stringify(myObj); // storing data
localStorage.setItem("testJSON", myJSON);
text = localStorage.getItem("testJSON"); // retrieving data
obj = JSON.parse(text);
document.write(obj.name);
Promises
function sum (a, b) {
return Promise(function (resolve, reject) {
setTimeout(function () { // send the response after 1 second
if (typeof a !== "number" || typeof b !== "number") { // testing input types
return reject(new TypeError("Inputs must be numbers"));
}
resolve(a + b);
}, 1000);
});
}
var myPromise = sum(10, 5);
myPromsise.then(function (result) {
document.write(" 10 + 5: ", result);
return sum(null, "foo"); // Invalid data and return another promise
}).then(function () { // Won't be called because of the error
}).catch(function (err) { // The catch handler is called instead, after another second
console.error(err); // => Please provide two numbers to sum.
});
States
pending, fulfilled, rejected
Properties
Promise.length, Promise.prototype
Methods
Promise.all(iterable), Promise.race(iterable), Promise.reject(reason), Promise.resolve(value)
Scope
Scope
function myFunction() {
var pizzaName = "Margarita";
// Code here can use pizzaName
}
// Code here can't use pizzaName
Block Scoped Variables
const isLoggedIn = true;
if (isLoggedIn == true) {
const statusMessage = 'Logged in.';
}
// Uncaught ReferenceError...
console.log(statusMessage);
Global Variables
// Variable declared globally
const color = 'blue';
function printColor() {
console.log(color);
}
printColor(); // => blue
let vs var
for (let i = 0; i < 3; i++) {
// This is the Max Scope for 'let'
// i accessible ✔️
}
// i not 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.
for (var i = 0; i < 3; i++) {
setTimeout(_ => console.log(i), 10);
}
// Prints 0, 1 and 2, as expected.
for (let j = 0; j < 3; j++) {
setTimeout(_ => console.log(j), 10);
}
// The variable has its own copy using let,
// and the variable has shared copy using var.
Objects
Accessing Properties
const apple = {
color: 'Green',
price: { bulk: '$3/kg', smallQty: '$4/kg' }
};
console.log(apple.color); // => Green
console.log(apple.price.bulk); // => $3/kg
Naming Properties
// Example of invalid key names
const trainSchedule = {
// Invalid because of the space between words.
platform num: 10,
// Expressions cannot be keys.
40 - 10 + 2: 30,
// A + sign is invalid unless it is enclosed in quotations.
+compartment: 'C'
}
Non-existent properties
const classElection = {
date: 'January 12'
};
console.log(classElection.place); // undefined
Mutable
const student = {
name: 'Sheldon',
score: 100,
grade: 'A',
}
console.log(student)
// { name: 'Sheldon', score: 100, grade: 'A' }
delete student.score
student.grade = 'F'
console.log(student)
// { name: 'Sheldon', grade: 'F' }
student = {}
// TypeError: Assignment to constant variable.
Assignment shorthand syntax
const person = {
name: 'Tom',
age: '22',
};
const {name, age} = person;
console.log(name); // 'Tom'
console.log(age); // '22'
Delete operator
const person = {
firstName: "Matilda",
age: 27,
hobby: "knitting",
goal: "learning JavaScript"
};
delete person.hobby; // or delete person[hobby];
console.log(person);
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
}
*/
Objects as arguments
const origNum = 8;
const origObj = {color: 'blue'};
const changeItUp = (num, obj) => {
num = 7;
obj.color = 'red';
};
changeItUp(origNum, origObj);
// Will output 8 since integers are passed by value.
console.log(origNum);
// Will output 'red' since objects are passed
// by reference and are therefore mutable.
console.log(origObj.color);
Shorthand object creation
const activity = 'Surfing';
const beach = { activity };
console.log(beach); // { activity: 'Surfing' }
this Keyword
const cat = {
name: 'Pipey',
age: 8,
whatName() {
return this.name
}
};
console.log(cat.whatName()); // => Pipey
Factory functions
// A factory function that accepts 'name',
// 'age', and 'breed' parameters to return
// a customized dog object.
const dogFactory = (name, age, breed) => {
return {
name: name,
age: age,
breed: breed,
bark() {
console.log('Woof!');
}
};
};
Methods
const engine = {
// method shorthand, with one argument
start(adverb) {
console.log(`The engine starts up ${adverb}...`);
},
// anonymous arrow function expression with no arguments
sputter: () => {
console.log('The engine sputters...');
},
};
engine.start('noisily');
engine.sputter();
Getters and setters
const myCat = {
_name: 'Dottie',
get name() {
return this._name;
},
set name(newName) {
this._name = newName;
}
};
// Reference invokes the getter
console.log(myCat.name);
// Assignment invokes the setter
myCat.name = 'Yankee';
Classes
Static Methods
class Dog {
constructor(name) {
this._name = name;
}
introduce() {
console.log('This is ' + this._name + ' !');
}
// A static method
static bark() {
console.log('Woof!');
}
}
const myDog = new Dog('Buster');
myDog.introduce();
// Calling the static method
Dog.bark();
Class
class Song {
constructor() {
this.title;
this.author;
}
play() {
console.log('Song playing!');
}
}
const mySong = new Song();
mySong.play();
Class Constructor
class Song {
constructor(title, artist) {
this.title = title;
this.artist = artist;
}
}
const mySong = new Song('Bohemian Rhapsody', 'Queen');
console.log(mySong.title);
Class Methods
class Song {
play() {
console.log('Playing!');
}
stop() {
console.log('Stopping!');
}
}
extends
// Parent class
class Media {
constructor(info) {
this.publishDate = info.publishDate;
this.name = info.name;
}
}
// Child class
class Song extends Media {
constructor(songData) {
super(songData);
this.artist = songData.artist;
}
}
const mySong = new Song({
artist: 'Queen',
name: 'Bohemian Rhapsody',
publishDate: 1975
});
Modules
Export/Import
// Export
// myMath.js
// Default export
export default function add(x,y){
return x + y
}
// Normal export
export function subtract(x,y){
return x - y
}
// Multiple exports
function multiply(x,y){
return x * y
}
function duplicate(x){
return x * 2
}
export {
multiply,
duplicate
}
// Import
// main.js
import add, { subtract, multiply, duplicate } from './myMath.js';
console.log(add(6, 2)); // 8
console.log(subtract(6, 2)) // 4
console.log(multiply(6, 2)); // 12
console.log(duplicate(5)) // 10
// index.html
<script type="module" src="main.js"></script>
Export Module / Require Module
// Export
// myMath.js
function add(x,y){
return x + y
}
function subtract(x,y){
return x - y
}
function multiply(x,y){
return x * y
}
function duplicate(x){
return x * 2
}
// Multiple exports in node.js
module.exports = {
add,
subtract,
multiply,
duplicate
}
// Require
// main.js
const myMath = require('./myMath.js')
console.log(myMath.add(6, 2)); // 8
console.log(myMath.subtract(6, 2)) // 4
console.log(myMath.multiply(6, 2)); // 12
console.log(myMath.duplicate(5)) // 10
Requests
JSON
const jsonObj = {
"name": "Rick",
"id": "11A",
"level": 4
};
XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', 'mysite.com/getjson');
// XMLHttpRequest is a browser-level API that enables the client to script data
// transfers via JavaScript, NOT part of the JavaScript language.
GET
const req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', '/getdata?id=65');
req.onload = () => {
console.log(xhr.response);
};
req.send();
POST
const data = {
fish: 'Salmon',
weight: '1.5 KG',
units: 5
};
const xhr = new XMLHttpRequest();
xhr.open('POST', '/inventory/add');
xhr.responseType = 'json';
xhr.send(JSON.stringify(data));
xhr.onload = () => {
console.log(xhr.response);
};
fetch api
fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'apikey': apiKey
},
body: data
}).then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message)
})
}
JSON Formatted
fetch('url-that-returns-JSON')
.then(response => response.json())
.then(jsonResponse => {
console.log(jsonResponse);
});
promise url parameter fetch api
fetch('url')
.then(
response => {
console.log(response);
},
rejection => {
console.error(rejection.message);
);
Fetch API Function
fetch('https://api-xxx.com/endpoint', {
method: 'POST',
body: JSON.stringify({id: "200"})
}).then(response => {
if(response.ok){
return response.json();
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message);
}).then(jsonResponse => {
console.log(jsonResponse);
})
async await syntax
const getSuggestions = async () => {
const wordQuery = inputField.value;
const endpoint = `${url}${queryParams}${wordQuery}`;
try{
const response = await fetch(endpoint, {cache: 'no-cache'});
if(response.ok){
const jsonResponse = await response.json()
}
}
catch(error){
console.log(error)
}
}
Last updated