JavaScript Cheatsheet: Easy to Advanced thumbnail

{JavaScript Cheatsheet: Easy to Advanced}

A quick reference for core JavaScript syntax and methods
November 21, 2022
javascriptbeginnercheatsheet

1. Variables

There are 3 ways to declare variables in javascript -

  • var — These variables can be reassigned. They are function scoped.
  • let — These variables can also be reassigned. They are block scoped.
  • const — These variables cannot be reassigned. They are also block scoped.
var var1 = value1;  
let var2 = value2;  
const var3 = value3;

2. Operators

Comparison Operators in JavaScript -

OperatorsSymbol
Equal to==
Equal value and equal type===
Not equal to!=
Not equal value and not equal type!==
Greater than>
Less than<
Greater than equal to>=
Less than equal to<=

Logical Operators in JavaScript -

OperatorsSymbol
Logical AND&&
Logical OR||
Logical NOT!

3. Datatypes

3.1. Primitive Datatypes

// integer  
let intNum = 25;  
  
// float  
let floatNum = 98.23;  
  
// character  
let char = 'a'  
  
// string  
let str = 'This is a string'  
  
// boolean  
let boolValue1 = true;  
let boolValue2 = false;  
  
// null  
let nullValue = null;

3.2. Non-Primitive Datatypes

The non-primitive data types available in JS are
Arrays — They can store groups of values.
Objects — They can store data in key-value pairs.

4. Truthy and Falsy Values

Falsy Values -

  • false
  • 0 (zero)
  • "", '', `` (empty strings)
  • null
  • undefined
  • NaN (not a number)

Truthy Values - Everything that is not Falsy

5. Conditional Statements

5.1. If Statement

if (condition) {  
// code to be executed if the condition is true  
}

5.2. If-Else Statement

if (condition) {  
     // code to be executed if the condition is true  
} else {  
    // code to be executed if the condition is false  
}

5.3. If-Else If-Else Statement

if (condition1) {  
     // code to be executed if the condition is true  
} else if (condition2){  
    // code to be executed  
    // if the condition1 is false  
    // and condition2 is true  
} else {  
    // code to be executed  
    // if both condition1 and condition2 are false  
}

5.4. Ternary Operator

condition ? exprIfTrue : exprIfFalse;

condition - An expression whose value is used as a condition.
exprIfTrue - An expression which is executed if the condition is true.
exprIfFalse - An expression which is executed if the condition is false.

Here is a simple example to understand the ternary operator

let num1 = 10;  
let num2 = 20;  
  
num1 < num2 ? console.log('smaller number') : console.log('larger number');

Here, as num1 is lesser than the num2, the condition num1 < num2 is true. So, the code that is to the left of : will be executed.

5.5. Switch Statement

switch (expression) {  
     case a:   
         // code to be executed  
         break;  
     case b:   
         // code to be executed  
         break;  
     default:   
         // default code to be executed  
}

6. Looping

6.1. For Loop

for (let i = 0, i < 5, i++) {  
    console.log('hello everyone!')  
}  
// prints 'hello everyone' 5 times

6.2. While Loop

let count = 0;  
while (count < 5) {  
    console.log('hello world!');  
    count++;  
}

6.3. Do-While Loop

let count = 0;  
do {  
    console.log('hello world!');  
    count++;  
} while (count < 5);

7. Functions

7.1. Normal Function Declaration

function name (parameter) {  
	// code to be executed  
 }

7.2. Function stored in a variable

const name = (parameter) {  
    // code to be executed  
}

7.3. Arrow Functions

const name = () => {  
	// code to be executed  
}

8. Date Objects

8.1. Get Date Methods

Get Date MethodsUse
getFullYear()Get the year as a four digit number (yyyy)
getMonth()Get the month as a number (0-11)
getDate()Get the day as a number (1-31)
getHours()Get the hour (0-23)
getMinutes()Get the minute (0-59)
getTime()Get the time
getDay()Get the weekday as a number (0-6)
Date.now()Get the time. ECMAScript 5
getSeconds()Get the second (0-59)
getMilliseconds()Get the millisecond (0-999)

8.2. UTC Date Methods

UTC Date MethodsUse
getUTCDate()Same as getDate(), but returns the UTC date
getUTCDay()Same as getDay(), but returns the UTC day
getUTCFullYear()Same as getFullYear(), but returns the UTC year
getUTCMonth()Same as getMonth(), but returns the UTC month
getUTCHours()Same as getHours(), but returns the UTC hour
getUTCMinutes()Same as getMinutes(), but returns the UTC minutes
getUTCSeconds()Same as getSeconds(), but returns the UTC seconds
getUTCMilliseconds()Same as getMilliseconds(), but returns the UTC milliseconds

8.3. Set Date Methods

Set Date MethodsUse
setDate()Set the day as a number (1-31)
setFullYear()Set the year (optionally month and day)
setMonth()Set the month (0-11)
setHours()Set the hour (0-23)
setMinutes()Set the minutes (0-59)
setSeconds()Set the seconds (0-59)
setMilliseconds()Set the milliseconds (0-999)
setTime()Set the time

9. String Methods

9.1. Get character at an index

Get a certain character of a string.

Syntax -

string[index]

Example -

let str = 'Javascript';  
  
console.log(str[4]);  
// output: "s"

9.2. length

Return the number of characters in a string.
Syntax -

string.length

Example -

let str = 'Javascript';  
  
console.log(str.length);  
// output: 10

9.3. split

Returns an array of substrings of a given string.
Syntax -

string.split()  
split(separator)

Example -

let str1 = 'The quick brown fox jumps over the lazy dog.';  
let words = str.split(' ');  
console.log(words);  
// output: ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]  
  
let str2 = 'Javascript';  
let chars = str.split('');  
console.log(chars);  
// output: ["J", "a", "v", "a", "s", "c", "r", "i", "p", "t"]

9.4. toLowerCase

Returns a lowercase string.
Syntax -

string.toLowerCase()

Example -

let str = 'I am IRON MAN';  
  
console.log(str.toLowerCase());  
// output: "i am iron man"

9.5. toUpperCase

Returns an uppercase string.
Syntax -

string.toUpperCase()

Example -

let str = 'why are you running?';  
  
console.log(str.toUpperCase());  
// output: "WHY ARE YOU RUNNING?"

9.6. replace

Returns a new string with a substring (substr) replaced by a new one (newSubstr).
Syntax -

string.replace(regexp, newSubstr)  
string.replace(substr, newSubstr)

Example -

const str = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';  
  
console.log(str.replace('dog', 'monkey'));  
// output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

9.7. includes

Check whether a substring exists inside of a string.
Syntax -

string.includes(searchString)   
string.includes(searchString, position)

Example -

let str = 'The quick brown fox jumps over the lazy dog.';  
str.includes = 'brown'  
// output: true

9.8. indexOf

Returns the index of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.
Syntax -

string.indexOf(searchString)  
string.indexOf(searchString, position)

Example -

let str = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';  
  
console.log(str.indexOf('dog'));  
// output: 40

9.9. lastIndexOf

Returns the index of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.
Syntax -

string.lastIndexOf(searchString)  
string.lastIndexOf(searchString, position)

Example -

let str = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';  
  
console.log(str.lastIndexOf('dog'));  
// output: 52

9.10. slice

Extracts a section of a string and returns it as a new string, without modifying the original string. Syntax -

string.slice(startIndex);  
string.slice(startIndex, endIndex);

Example -

let str = 'The quick brown fox jumps over the lazy dog.';  
  
console.log(str.slice(31));  
// output: "the lazy dog."  
  
console.log(str.slice(4, 19));  
// output: "quick brown fox"

10. Arrays

10.1. Array Declaration

let nums = [];  
nums = [-20, 2, 45.23, 100, 650];  
  
let fruits = ['apple', 'mango', 'orange', 'apple'];  
  
let arr = [20, 'dog', 75.22, ['a', 'b', 'c']];

10.2. Accessing an Array Item

let students  = ['Harry', 'Hermione', 'Ron'];  
  
console.log(students[0]);    // prints 'Harry'  
console.log(students[1]);    // prints 'Hermione'  
console.log(students[2]);    // prints 'Ron'

10.3. Updating an Array Item

let students  = ['Harry', 'Hermione', 'Draco'];  
  
students[2] = 'Ron';    // 'Draco' will be updated to 'Ron'

10.4. Looping in an Array

For Loop -

let arr = [10, 20, 30, 40];  
  
for (let i = 0; i < arr.length; i++) {  
    console.log(i);  
}  
// output:  
// 10  
// 20  
// 30  
// 40

For…of Loop

let arr = [10, 20, 30, 40];  
  
for (let element of arr) {  
    console.log(element);  
}  
// output:  
// 10  
// 20  
// 30  
// 40

10.5. Array Methods

length()

Returns the number of elements in the array.
Syntax -

array.length

Example -

let arr = [10, 20, 30, 40];  
  
console.log(arr.length);  
// output: 4

push()

Adds the value at the end of the array.
Syntax -

array.push(element0)  
array.push(element0, element1)  
array.push(element0, element1, /* ... ,*/ elementN)

Example -

let arr  [10, 20, 30];  
  
arr.push(40);  
console.log(arr);  
// output: [10, 20, 30, 40]  
  
arr.push(50, 60, 70);  
console.log(arr);  
// output: [10, 20, 30, 40, 50, 60, 70]

pop()

Removes the value from the end of the array.
Syntax -

array.pop()

Example -

let arr = [10, 20, 30, 40, 50];  
  
arr.pop()  
console.log(arr);  
// output: [10, 20, 30, 40]

shift()

Removes the value from the start of the array.
Syntax -

array.shift()

Example -

let arr = [10, 20, 30, 40, 50];  
  
arr.shift()  
console.log(arr);  
// output: [20, 30, 40, 50]

unshift()

Adds the value to the start of the array.
Syntax -

array.unshift(element0)  
array.unshift(element0, element1)  
array.unshift(element0, element1, /* ... ,*/ elementN)

Example -

let arr = [10, 20, 30, 40, 50];  
  
arr.unshift(0)  
console.log(arr);  
// output: [0, 10, 20, 30, 40, 50]  
arr.unshift(-40, -20)  
console.log(arr);  
// output: [-40, -20, 0, 10, 20, 30, 40, 50]

splice()

Removes or replaces existing elements and/or adds new elements in place.
Syntax -

array.splice(start)  
array.splice(start, deleteCount)  
array.splice(start, deleteCount, item1)  
array.splice(start, deleteCount, item1, item2, itemN)

Example -

let arr = [0, 10, 20, 98, 99, 60, 70, 80];  
  
arr.splice(6)      
console.log(arr);  
// removes all elements starting form index 6  
// output: [0, 10, 20, 98, 99, 60]  
  
arr.splice(3, 2);  
console.log(arr);  
// removes two elements starting from index 3  
// output: [0, 10, 20, 60]  
  
arr.splice(3, 0, 30)  
console.log(arr);  
// adds 30 at index 3  
// output: [0, 10, 20, 30, 60]  
  
arr.splice(4, 0, 40, 50)  
console.log(arr);  
// adds [40, 50] at index 4  
// output: [0, 10, 20, 30, 40, 50, 60]

concat()

Join several arrays into one.
Syntax -

array1.concat(array2)

Example -

let arr1 = [10, 20, 30];  
let arr2 = [40, 50, 60];  
  
let arr3 = arr1.concat(arr2);  
console.log(arr3);  
// output: [10, 20, 30, 40, 50, 60]

reverse()

Reverse the order of the elements in an array.
Syntax -

array.reverse()

Example -

let arr = [10, 20, 30, 40, 50];  
  
arr.reverse();  
console.log(arr);  
// output: [50, 40, 30, 20, 10]

toString()

Returns a string representing the specified array and its elements.
Syntax -

array.toString()

Example -

let arr = [10, 20, 30, 40];  
  
console.log(arr.toString());  
// output: "10, 20, 30, 40"

includes()

Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
Syntax -

array.includes(searchElement)

Example -

let arr = [10, 20, 30, 40];  
  
console.log(arr.includes(30));  
// output: true

sort()

It sorts the elements of an array in place and returns the sorted array. It sorts an array alphabetically.
Syntax -

array.sort()

Example -

let fruits = ['watermelon', 'mango', 'apple', 'orange'];  
  
fruits.sort();  
console.log(fruits);  
// output: ["apple", "mango", "orange", "watermelon"]

indexOf()

Returns the index of the first occurrence of that value.
Syntax -

array.indexOf(searchElement)

Example -

let arr = [10, 20, 30, 40, 30, 30];  
  
console.log(arr.indexOf(30));  
// output: 2

lastIndexOf()

Returns the index of the last occurrence of that value.
Syntax -

array.lastIndexOf(searchElement)

Example -

let arr = [10, 20, 30, 40, 30, 30];  
  
console.log(arr.indexOf(30));  
// output: 5

10.6. Array methods with Looping

forEach()

It executes a provided function once for each array element.
Syntax -

array.forEach((element, index) => {  
    // code to be executed  
});

Example -

let arr = [10, 20, 30];  
  
arr.forEach(element => {  
    // adds 5 to each element of arr  
    element = element + 5;  
    console.log(element);  
});  
// output:   
// 15  
// 25  
// 35

map()

It creates a new array populated with the results of calling a provided function on every element in the calling array.
Syntax -

array.map((element, index) => {  
    // code to be executed  
}

Example -

let array1 = [1, 4, 9, 16];  
  
// multiplies each element with 2  
let map1 = array1.map(x => x * 2);  
console.log(map1);  
// expected output: [2, 8, 18, 32]

filter()

It creates a new array with all elements that pass the test implemented by the provided function.
Syntax -

array.filter((element, index) => {  
    // code to be executed  
})

Example -

let arr = [100, -43, 76, -2, -67, 34];  
  
// filters out and prints all nums that are less than 0  
const result = arr.filter(num => num < 0);  
console.log(result);  
// output: [-43, -2, -67]

findIndex()

It returns the index of the first element in the array that satisfies the provided testing function.
Syntax -

array.findIndex((element, index, array) => {  
    // code to be executed  
})

Example -

let array1 = [5, 12, 8, 130, 44];  
  
const isLargeNumber = (element) => element > 13;  
console.log(array1.findIndex(isLargeNumber));  
// output: 3

some()

It tests whether at least one element in the array passes the test implemented by the provided function.
Syntax -

array.some((element, index, array) => {  
    // code to be executed  
})

Example -

let array = [1, 2, 3, 4, 5];  
  
// checks whether an element is even  
const even = (element) => element % 2 === 0;  
console.log(array.some(even));  
// output: true

every()

It tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
Syntax -

array.every((element, index) => {  
    // code to be executed  
})

Example -

const isBelowLimit = (currentValue) => currentValue < 35;  
  
let array1 = [1, 30, 39, 29, 10, 13];  
console.log(array1.every(isBelowLimit));  
// output: false

reduce()

It runs a function on each array element to produce (reduce it to) a single value. It works from left to right.
Syntax -

array.reduce((prevValue, currentValue) => {  
    // code to be executed  
})

Example -

let array1 = [1, 2, 3, 4];  
  
const add = (prev, current) => prev + current;  
  
// 0 + 1 + 2 + 3 + 4  
let initialValue = 0;  
let total = array1.reduce(add, initialValue);  
  
console.log(total);  
// expected output: 10

11. Objects

11.1. Creating a new Object

const user = {  
    name: 'John Smith',  
    username: 'john1234',  
    gender: 'male',  
    age: 30,  
    isHuman: true,  
    greet: function () {  
        console.log('Hello World!')  
    }  
};

11.2. Accessing Properties in an Object

const student = {  
    name: 'John',  
    age: 30  
};  
  
console.log(student['name']);    // John  
console.log(student['age']);    // 30  
// OR  
console.log(student.name);    // John  
console.log(student.age);    // 30

11.3. Adding Object Properties

const user = {  
    name: 'John',  
    age: 30,  
};  
  
user.hobby = 'painting';

11.4. Looping in an Object

Syntax -

for (property in object) {  
    // code block to be executed  
}

Example -

const obj = {a: 1, b: 2, c: 3};  
  
for (let key in obj) {  
    console.log(`${property}: ${object[property]}`);  
}  
// output:   
// "a: 1"  
// "b: 2"  
// "c: 3"

Congratulations on completing the key topics in JavaScript! I recommend implementing the examples to gain hands-on experience with each function or method to enhance your comprehension.

In upcoming articles, we’ll delve into JavaScript’s interaction with HTML elements, DOM manipulation, modular programming, AJAX, and more. These topics will further deepen your understanding and broaden your skill set.

Happy Learning!

For more resources, please visit the official JavaScript guide by MDN -
JavaScript|MDN