- var Used before ES6 to declare variables. It is function-scoped
- let Allows reassignment and is block-scoped. Can be declared without an initial value (defaults to undefined).
- const Assigned at declaration and cannot be reassigned.
JavaScript cheatsheet
This is a quick reference cheat sheet for understanding and writing JavaScript.
# Variables
Variable Declarations
Interpolation
Template literals allows to embed variables and expressions directly within strings.
const myPet = 'armadillo';
console.log(`I own a pet ${myPet}.`);
// Output: I own a pet armadillo.
ES6
Falsy values
- 0
- Empty strings ("" or '')
- null
- undefined
- NaN
Scope
- Global Scope Variables declared outside any block are global. They reside in the global namespace and can be accessed from anywhere.
- Block Scope Variables declared inside a block ({ ... }) are only accessible within that block.
{
let blockVar = 'I am block scoped';
console.log(blockVar); // Works here
}
console.log(blockVar); // Error: blockVar is not defined
Swap two variables using destructuring technique
exampleFunction = (num, start, end) => {
if(!end) {
end = start;
start = 0;
}
if (start > end) [start, end] = [end, start]
return (num >= start) && (num < end)
}
# Operators
Arithmetic Operators
- + Addition: sums two values.
- - Subtraction: subtracts one value from another.
- * Multiplication.
- / Division.
- % Modulus: returns the remainder after division.
- ++ Increment: increases a value by one.
- -- Decrement: decreases a value by one.
let a = 10, b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // ≈3.33
console.log(a % b); // 1
Assignment Operators
Assignment operators set a variable’s value and can combine operations with assignment.
- = Assigns a value.
- += Adds and assigns the result.
- -= Subtracts and assigns the result.
- *= Multiplies and assigns the result.
- /= Divides and assigns the result.
- %= Calculates the remainder and assigns it.
- **= Performs exponentiation and assigns the result.
let x = 5;
x += 3; // equivalent to x = x + 3
console.log(x); // 8
Comparison Operators
Comparison operators compare two values and return a Boolean result.
- == Loose equality, performs type coercion.
- === Strict equality, no type coercion.
- != Loose inequality check.
- !== Strict inequality check.
- > Greater than.
- >= Greater than or equal to.
- < Less than.
- <= Less than or equal to.
console.log(5 == '5'); // true (loose equality)
console.log(5 === '5'); // false (strict equality)
Logical Operators
Logical operators are used to combine or invert Boolean values.
- && Logical AND: true if both operands are true.
- || Logical OR: true if at least one operand is true.
- ! Logical NOT: inverts the Boolean value.
console.log(true && false); // false
console.log(true || false); // true
console.log(!false); // true
Comma Operator
The comma operator evaluates multiple expressions and returns the value of the last expression.
let x = (1, 2, 3);
console.log(x); // 3
Bitwise Operators
Bitwise operators perform operations on the binary representations of numbers.
- & Bitwise AND: compares corresponding bits of two numbers.
- | Bitwise OR: combines bits of two numbers.
- ^ Bitwise XOR: returns a 1 in each bit position where the bits are different.
- ~ Bitwise NOT: inverts all bits of a number.
- << Left shift: shifts bits to the left.
- >> Right shift (with sign): shifts bits to the right, preserving the sign.
- >>> Unsigned right shift: shifts bits to the right, filling with zeros.
console.log(5 & 3); // 1 (0101 & 0011 = 0001)
console.log(5 | 3); // 7 (0101 | 0011 = 0111)
Type Operators
Type operators determine or manipulate the type of values and objects.
- typeof Returns a string indicating the type of variable.
- instanceof Checks if an object is an instance of a particular constructor.
- in Checks if a property exists in an object.
- delete Removes a property from an object.
- void Evaluates an expression and returns undefined.
let num = 42;
console.log(typeof num); // "number"
console.log('length' in {length: 10}); // true
Spread Operator (...)
Expands an iterable (e.g., an array) into individual elements.
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4];
console.log(newNumbers); // [1, 2, 3, 4]
ES6
Optional Chaining (?.)
Safely accesses nested properties, returning undefined if any reference is nullish.
const obj = { a: { b: 5 } };
console.log(obj?.a?.b); // 5
ES6
Nullish Coalescing (??)
Returns the right-hand operand when the left-hand operand is null or undefined.
let value = null;
console.log(value ?? 'default'); // "default"
ES6
Exponentiation Operator (**)
Raises the left operand to the power of the right operand.
console.log(2 ** 3); // 8
ES6
# JavaScript Conditionals
Operators
Logical OR (||)
true || false; // => true
true || (10 > 20); // => true
false || false; // => false
(10 > 100) || (10 > 20); // => false
Logical AND (&&)
true && false; // => false
(2 > 1) && (2 > 1); // => true
true && false; // => false
4 && 5; // => 5
Comparison Operators
3 == 3; // => true
250 >= 250; // => true
1 === 1; // => true
1 == '1'; // => true
1 === '1'; // => false
Logical Operator (!)
let lateToWork = true;
let oppositeValue = !lateToWork; // => false
Nullish Coalescing Operator (??)
null ?? 'I win'; // => 'I win'
undefined ?? 'Me too'; // => 'Me too'
false ?? 'I lose'; // => false
'' ?? 'I lose again'; // => ''
If...else...
if(condition){
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
If...else if...else
if(condition1){
// code to be executed if condition1 is true
} else if(condition2){
// code to be executed if condition2 is true
} else {
// code to be executed if condition1 and condition2 are false
}
Switch Statement
It compares a given expression with several cases and executes the matching block of code.
let groceryItem = 'papaya';
switch (groceryItem) {
case 'tomato':
console.log('Tomatoes are $0.49');
break;
case 'lime':
console.log('Limes are $1.49');
break;
case 'papaya':
console.log('Papayas are $1.29');
break;
default:
console.log('Invalid item');
break;
}
// Prints 'Papayas are $1.29'
- Break: The break keyword terminates the switch block, preventing the execution of subsequent cases. Without it, cases would fall through.
- Default: The default case runs if no other cases match. It acts like an else condition.
Ternary Operator
isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');
- Condition
- True statement
- False statement
# JavaScript Arrays
Array literal
let myArray = [1, 'apple', true, null, undefined];
Access and valorize array data
let myArray = [1, 'apple', true, null, undefined];
console.log(myArray[2]);
// Output: true
myArray[3] = 'Autumn';
// The array now is [1, 'apple', true, Autumn, undefined]
When you pass an array into a function, if the array is mutated inside the function, that change will be maintained outside the function as well. You might also see this concept explained as pass-by-reference since what we’re actually passing to the function is a reference to where the variable memory is stored and changing the memory.
Const arrays
Variables declared with the const keyword cannot be reassigned. However, elements in an array declared with const remain mutable.
const myArray = [1, 'apple', true];
myArray[2] = 'banana'; //allows reassignment
myArray = [2, 'banana', false]; // Error: Assignment to constant variable
Properties
.length
let numbers = [1,2,3,4];
numbers.length // 4
.push()
Adds one or more elements to the end of an array, mutating the original array.
let fruits = ['apple', 'banana'];
fruits.push('cherry');
console.log(fruits); // ['apple', 'banana', 'cherry']
Destructive
.pop()
Removes the last element from an array and returns that element.
let fruits = ['apple', 'banana', 'cherry'];
let removedFruit = fruits.pop();
console.log(removedFruit); // 'cherry'
console.log(fruits); // ['apple', 'banana']
Destructive
.splice()
Adds, removes, or replaces elements in an array and returns an array of the deleted elements.
// Remove 1 element starting at index 1:
let fruits = ['apple', 'banana', 'cherry'];
let deleted = fruits.splice(1, 1);
console.log(deleted); // ['banana']
console.log(fruits); // ['apple', 'cherry']
Destructive
.shift()
Removes the first element of an array and returns it.
let fruits = ['apple', 'banana', 'cherry'];
let firstFruit = fruits.shift();
console.log(firstFruit); // 'apple'
console.log(fruits); // ['banana', 'cherry']
Destructive
.unshift()
Adds one or more elements to the beginning of an array, mutating the original array.
let fruits = ['banana', 'cherry'];
fruits.unshift('apple');
console.log(fruits); // ['apple', 'banana', 'cherry']
Destructive
.indexOf()
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
let cars = ['Fiat', 'Alfa Romeo'];
cars.indexOf('Alfa Romeo'); // 1
Non-destructive
.join()
Creates a string by concatenating all elements of an array, with an optional separator.
let words = ['Hello', 'World'];
console.log(words.join(' ')); // "Hello World"
Non-destructive
.slice()
Returns a shallow copy of a portion of the array as a new array, without modifying the original.
let fruits = ['apple', 'banana', 'cherry', 'date'];
let part = fruits.slice(1, 3);
console.log(part); // ['banana', 'cherry']
Non-destructive
.concat()
Returns a new array that is the combination of two or more arrays, leaving the original arrays unmodified.
let arr1 = ['apple', 'banana'];
let arr2 = ['cherry', 'date'];
let combined = arr1.concat(arr2);
console.log(combined); // ['apple', 'banana', 'cherry', 'date']
Non-destructive
Remove Duplicates with Set
// Given the companies array:
['Visa', 'Mastercard', 'Visa', 'Amex', 'Mastercard']
// The result of:
return [...new Set(companies)];
// will be:
['Visa', 'Mastercard', 'Amex']
- new Set(companies) Creates a Set object from the array companies. A Set only stores unique values, automatically removing duplicates.
-
[...new Set(companies)]
Uses the spread operator (
...
) to convert the Set back into an array. This step is required because a Set is not an array.
Set objects don't have the .push() method. Instead, .add() should be used
const createSpecimens30 = () => {
let resArr = new Set();
while(resArr.size < 30) {
...
resArr.add(specie);
}
return resArr
};
# JavaScript Array Iterators
.forEach()
Executes a provided function once for each array element. It does not return a new array.
Function Expression
const arr = ['a', 'b', 'c'];
arr.forEach(function(item) {
console.log(item);
});
Arrow Function
arr.forEach(item => console.log(item));
Named Function
function printItem(item) {
console.log(item);
}
arr.forEach(printItem);
Creates a new array
.map()
Creates a new array by applying a callback function to every element of the original array.
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
Creates a new array
.filter()
Creates a new array with all elements that pass the test implemented by the provided function.
const words = ['dog', 'elephant', 'cat'];
const shortWords = words.filter(word => word.length <= 3);
console.log(shortWords); // ['dog', 'cat']
Creates a new array
.every()
Tests whether all elements in the array pass the provided test. It returns true only if every element passes the test.
const nums = [2, 4, 6];
const allEven = nums.every(num => num % 2 === 0);
console.log(allEven); // true
.some()
Tests whether at least one element in the array satisfies the provided test. It returns true if any element passes the test, otherwise false.
const nums = [1, 3, 5, 8];
const hasEven = nums.some(num => num % 2 === 0);
console.log(hasEven); // true
.split()
Divides a string into an array of substrings, based on a specified separator.
const sentence = "Hello World";
const words = sentence.split(" ");
console.log(words); // ["Hello", "World"]
Creates a new array
.reduce()
Applies a reducer function on each element of the array, resulting in a single output value.
const numbers = [1, 2, 3];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum); // 6

An optional accumulator initial value can be provided
const sumWithInitial = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 10);
console.log(sumWithInitial); // 16

.findIndex()
Returns the index of the first element that satisfies the provided testing function, or -1 if none do.
const nums = [10, 20, 5, 40];
const index = nums.findIndex(num => num < 10);
console.log(index); // 2
.join()
Concatenates all the elements of an array into a string, separated by a specified delimiter.
const fruits = ["apple", "banana", "cherry"];
const fruitString = fruits.join(", ");
console.log(fruitString); // "apple, banana, cherry"
.sort()
Sorts the elements of an array in place and returns the sorted array. A comparator function can be provided to define the sort order. If the comparator returns a negative number, zero, or a positive number, the positions of elements are determined accordingly.
Descending Order
const sortYearsDescending = (yearsArray) => {
return yearsArray.sort((a, b) => b - a);
};
console.log(sortYearsDescending([2020, 2010, 2005])); // [2020, 2010, 2005]
Ascending Order
const sortYearsAscending = (yearsArray) => {
return yearsArray.sort((a, b) => a - b);
};
console.log(sortYearsAscending([2020, 2010, 2005])); // [2005, 2010, 2020]
Modify the input array
# Loops
For Loop
for (let counter = 0; counter < 4; counter++) {
console.log(counter);
}
// 1
// 2
// 3
// 4
For…of Loop
Iterates over the values of an iterable object (such as Arrays, Strings, Maps, etc.) without needing an index.
const hobbies = ['singing', 'eating', 'quidditch', 'writing'];
for (const hobby of hobbies) {
console.log(`I enjoy ${hobby}.`);
}
// I enjoy singing
// I enjoy eating
// I enjoy quidditch
// I enjoy writing
for...in Loop
The for...in loop iterates over all enumerable string properties of an object.
const obj = { a: 1, b: 2, c: 3 };
for (const property in obj) {
console.log(`${property}: ${obj[property]}`);
}
// Expected output:
// "a: 1"
// "b: 2"
// "c: 3"
While Loop
A while loop runs as long as its condition remains true and is ideal when the number of iterations is not known in advance.
let counterTwo = 1;
while (counterTwo < 4) {
console.log(counterTwo);
counterTwo++;
}
Do…while Loop
A do...while loop executes its code block at least once, and then continues to loop while the condition is true.
let countString = '';
let i = 0;
do {
countString = countString + i;
i++;
} while (i < 5);
console.log(countString);
// 0
// 01
// 012
// 0123
Break Statement
Exit a loop prematurely when a certain condition is met. It prevents further iterations even if the loop’s condition is still true.
for (let i = 0; i < 99; i++) {
if (i > 2) {
console.log("I am free!")
break;
}
console.log('Banana');
}
// Banana
// Banana
// Banana
// I am free!
Continue Statement
Skips the current iteration and proceeds to the next one.
const strangeBirds = ['Shoebill', 'Cow', 'Terrorbird', 'Parotia', 'Kakapo'];
for (const bird of strangeBirds) {
if (bird === 'Cow') {
continue;
}
console.log(bird);
}
// Output:
// Shoebill
// Terrorbird
// Parotia
// Kakapo
# Functions
Defining a Function
A basic function declaration with two parameters and a return value.
function sum(num1, num2) {
return num1 + num2;
}
Named Function
Use a descriptive name to clarify what the function does.
function rocketToMars() {
return 'BOOM!';
}
// Invoke:
rocketToMars(); // "BOOM!"
Anonymous Function
Assigned to a variable instead of having its own name.
const rocketToMars = function() {
return 'BOOM!';
};
// Invoke:
rocketToMars(); // "BOOM!"
Arrow Functions
Basic Arrow Function
It takes two parameters and returns their sum using implicit return.
const sum = (a, b) => a + b;
console.log(sum(3, 4)); // 7
Arrow Function with Block Body
When using a block body (curly braces), you must explicitly return a value.
const multiply = (a, b) => {
return a * b;
};
console.log(multiply(3, 4)); // 12
No-Parameter Arrow Function
Parentheses are required even if there are no parameters.
const greet = () => 'Hello, world!';
console.log(greet()); // "Hello, world!"
Arrow Function with Default Parameters
Default values can be assigned to parameters in an arrow function.
const greetWithDefault = (name = 'stranger') => `Hello, ${name}!`;
console.log(greetWithDefault('Alice')); // "Hello, Alice!"
console.log(greetWithDefault()); // "Hello, stranger!"
Arrow Function Expression
Can be assigned to a variable as a function expression.
const bark = () => 'Woof!';
console.log(bark()); // "Woof!"
ES6
Function Expression
Store a function in a variable. The function can be named or anonymous.
const bark = function() {
return 'Woof!';
};
console.log(bark()); // "Woof!"
Function Parameters
Parameters act as placeholders for arguments passed to the function.
function sayHello(name = 'stranger') {
console.log('Hello, ' + name);
}
sayHello('Simone'); // "Hello, Simone"
sayHello(); // "Hello, stranger"
Return Keyword
If a function hits return, it exits immediately and passes the specified value back.
function checkAge(age) {
if (age < 0) {
return; // Exits with undefined
}
return age >= 18;
}
Calling a Function
Invoke a function by using its name followed by parentheses. Include arguments if needed.
function greet(name) {
console.log('Hello, ' + name);
}
greet('Simone'); // "Hello, Simone"
Helper Functions
Helper functions are functions called within another function to perform specific tasks
function multiplyByNineFifths(number) {
return number * (9/5);
};
function getFahrenheit(celsius) {
return multiplyByNineFifths(celsius) + 32;
};
getFahrenheit(15); // Returns 59
High-order Functions
Functions as Data
Since functions in JavaScript are first-class objects, they can be assigned to variables and passed around as data. This allows you to rename or reuse a function without duplicating its code.
const announceThatIAmDoingImportantWork = () => {
console.log("I’m doing very important work!");
};
const busy = announceThatIAmDoingImportantWork;
busy(); // This function call barely takes any space!
Functions as Parameters
Functions can also be passed as arguments to other functions.The functions passed as parameters are commonly known as callback functions.
const higherOrderFunc = param => {
// Invoke the callback function
param();
return `I just invoked ${param.name} as a callback function!`;
};
const anotherFunc = () => {
return "I'm being invoked by the higher-order function!";
};
console.log(higherOrderFunc(anotherFunc));
// Expected output: "I just invoked anotherFunc as a callback function!"
You can also use higher-order functions to validate the consistency of other functions:
const addTwo = num => {
return num + 2;
};
const checkConsistentOutput = (func, val) => {
let checkA = val + 2;
let checkB = func(val);
if(checkA === checkB)
return checkB;
else
return 'inconsistent results';
};
console.log(checkConsistentOutput(addTwo, 5)); // Expected output: 7
# Objects
Object Literals
let spaceship = {
'Fuel Type': 'diesel', // key is 'Fuel Type', value is 'diesel'
color: 'silver' // key is color, value is 'silver'
};
Accessing Properties
let spaceship = {
'Fuel Type': 'Turbo Fuel',
'Active Duty': true,
homePlanet: 'Earth',
numCrew: 5
};
console.log(spaceship.numCrew); // 5
console.log(spaceship['Fuel Type']); // 'Turbo Fuel'
Deleting Properties
Use the delete operator to remove a property from an object.
const spaceship = {
'Fuel Type': 'Turbo Fuel',
homePlanet: 'Earth',
mission: 'Explore the universe'
};
delete spaceship.mission; // Removes the 'mission' property
console.log(spaceship);
Updating Properties
You cannot reassign a constant object, but you can update its properties.
const spaceship = {
'Fuel Type': 'Turbo Fuel',
'Active Duty': true,
homePlanet: 'Earth',
numCrew: 5,
type: 'Shuttle'
};
// Updating properties:
spaceship.type = 'alien'; // Modify existing property
spaceship.speed = 'Mach 5'; // Add a new property
spaceship['Active Duty'] = false; // Change property using bracket notation
spaceship.numCrew = 6; // Update numeric value
spaceship = {'key': 'value'}; // Error: Assignment to constant variable
Nested Objects
const spaceship = {
telescope: {
yearBuilt: 2018,
focalLength: 2032
},
crew: {
captain: {
name: 'Sandra',
encourageTeam() { console.log('We got this!'); }
}
},
engine: {
model: 'Nimbus2000'
},
nanoelectronics: {
computer: {
terabytes: 100,
},
'back-up': {
battery: 'Lithium',
terabytes: 50
}
}
};
console.log(spaceship.nanoelectronics['back-up'].battery); // 'Lithium'
Pass By Reference
If properties are defined within a function, the object itself is mutated. However, reassigning the object within a function does not change the original variable.
let spaceship = {
homePlanet: 'Earth',
color: 'red'
};
let tryReassignment = obj => {
obj = {
identified: false,
'transport type': 'flying'
};
obj.color = 'blue';
console.log(obj); // Prints the new object
};
tryReassignment(spaceship);
console.log(spaceship); // { homePlanet: 'Earth', color: 'blue' }
// Regular reassignment works:
spaceship = {
identified: false,
'transport type': 'flying'
};
console.log(spaceship); //{identified: false,'transport type': 'flying'}
this keyword & Arrow Functions
In methods defined using the traditional function syntax, this refers to the calling object.
const goat = {
dietType: 'herbivore',
diet() {
console.log(this.dietType);
}
};
goat.diet(); // Outputs: herbivore
Arrow functions, do not bind their own this, and will refer to the global object (or remain undefined in strict mode)
const goat2 = {
dietType: 'herbivore',
diet: () => {
console.log(this.dietType);
}
};
goat2.diet(); // Outputs: undefined
Custom Methods
Objects can have methods/functions assigned as property values to encapsulate behavior. With ES6, you can omit the colon and function
keyword.
const alienShip = {
invade() {
console.log('Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.');
},
takeOff() {
console.log('Take of...');
}
};
alienShip.invade(); // Invokes the invade method
//Output: 'Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.'
Getters
If properties must remain unaltered, a common convention is to prefix the property name with an underscore (_). Getter methods allow controlled access to these properties.
const person = {
_firstName: 'John',
_lastName: 'Doe',
get fullName() {
if (this._firstName && this._lastName) {
return `${this._firstName} ${this._lastName}`;
} else {
return 'Missing a first name or last name.';
}
}
};
console.log(person.fullName); // 'John Doe'
Setters
Setter methods allow controlled modification of properties designated as private by convention. Setters perform validation before updating the property value.
const person2 = {
_age: 37,
set age(newAge) {
if (typeof newAge === 'number') {
this._age = newAge;
} else {
console.log('You must assign a number to age');
}
}
};
person2.age = 40;
console.log(person2._age); // 40
person2.age = '40'; // Logs: You must assign a number to age
Factory Functions
A factory function creates and returns an object. This approach permits the generation of multiple similar object instances through reusable code.
const monsterFactory = (name, age, energySource, catchPhrase) => {
return {
name: name,
age: age,
energySource: energySource,
scare() {
console.log(catchPhrase);
}
};
};
const ghost = monsterFactory('Ghouly', 251, 'ectoplasm', 'BOO!');
ghost.scare(); // 'BOO!'
// Using property shorthand in a factory function:
const monsterFactory2 = (name, age) => {
return {
name,
age
};
};
Destructuring Technique
Property shorthand simplifies object creation, and destructuring assignment permits the extraction of object properties into variables.
const vampire = {
name: 'Dracula',
residence: 'Transylvania',
preferences: {
day: 'stay inside',
night: 'satisfy appetite'
}
};
const { residence } = vampire;
console.log(residence); // 'Transylvania'
const { day } = vampire.preferences;
console.log(day); // 'stay inside'
ES6
Object Methods
JavaScript objects have several built-in methods to work with their properties:
- .hasOwnProperty() Checks if an object has the specified property as its own property.
- .valueOf() Returns the primitive value of the specified object.
- Object.assign() Copies the values of all enumerable own properties from one or more source objects to a target object.
- Object.entries() Returns an array of [key, value] pairs of an object’s own enumerable properties.
- Object.keys() Returns an array of the names of an object’s own enumerable properties.
const robot = {
name: "Robo",
version: 1.0
};
console.log(robot.hasOwnProperty('name')); // true
console.log(robot.valueOf()); // { name: "Robo", version: 1.0 }
const newRobot = Object.assign({}, robot, {laserBlaster: true, voiceRecognition: true});
console.log(newRobot); // [ 'name', 'version', 'laserBlaster', 'voiceRecognition' ]
console.log(Object.entries(newRobot)); // [ [ 'name', 'Robo' ], [ 'version', 1 ], [ 'laserBlaster', true ], [ 'voiceRecognition', true ] ]
console.log(Object.keys(newRobot)); // [ 'name', 'version', 'laserBlaster', 'voiceRecognition' ]