Skip to main content

How To – Code Snippets

Learn how to code with simplified code snippets.

How to Add Items to the Start of an Array

Use unshift() to add one or more items to the start of an array.

const fruitsArray = ["Mango", "Apple"];

fruitsArray.unshift("Orange", "Lemon", "Grape");

console.log(fruitsArray);

// The fruitsArray's invocation above will return:
// ["Orange", "Lemon", "Grape", "Mango", "Apple"]

How to Add Items to the End of an Array

Use push() to add one or more items to the end of an array.

const fruitsArray = ["Mango", "Apple"];

fruitsArray.push("Orange", "Lemon", "Grape");

console.log(fruitsArray);

// The fruitsArray's invocation above will return:
// ["Mango", "Apple", "Orange", "Lemon", "Grape"]

How to Add Multiple Items to an Array

Use splice() to add multiple items to an array.

// Define an array:
const colorsArray = ["red", "blue", "green", "white"];

// Add three items to the colorsArray:
colorsArray.splice(1, 0, "purple", "pink", "tan");

// Print colorsArray's content on the console:
console.log(colorsArray);

// The invocation above will return:
// ["red", "purple", "pink", "tan", "blue", "green", "white"]

How to Check If a Number Is an Integer

Use Number.isInteger() to check if a number is an integer.

Number.isInteger(578);

// The invocation above will return: true

Try it on StackBlitz

How to Check If a String Includes a Value

Use includes() to check if a string includes a value.

"SunDay, Tuesday, and Friday are good Days".includes("day");

// The invocation above will return: true

Try it on StackBlitz

How to Check If an Array Includes a Value

Use includes() to check if an array includes a value.

[1, 3, 5, 7].includes(5);

// The invocation above will return: true

Try it on StackBlitz

How to Compute a Property's Name

Use a square bracket encased expression as the property's name.

let num = 0;
let enSuites = "East";

const doorNo = {
[enSuites + ++num]: num,
[enSuites + ++num]: num,
[enSuites + ++num]: num,
};

console.log(doorNo);

// The invocation above will return:
{East1: 1, East2: 2, East3: 3}

How to Convert a Boolean Value to Number Type

Use Number() to convert a Boolean value to Number type.

Number(true);

// The invocation above will return: 1

Try it on StackBlitz

How to Convert a Date to Number Type

Use Number() to convert a date to Number type.

Number(new Date(2022, 06, 01));

// The invocation above will return: 1656630000000

Try it on StackBlitz

How to Convert a JavaScript Array to JSON

Use stringify() to convert a JavaScript Array to a JSON text.

// Create a JavaScript array:
const myBio = ["Oluwatobi", "Sofela", "CodeSweetly"];

// Convert myBio array to JSON (text format):
JSON.stringify(myBio);

// The invocation above will return: '["Oluwatobi","Sofela","CodeSweetly"]'

How to Convert a JavaScript Object to JSON

Use stringify() to convert a JavaScript object to a JSON text.

// Create a JavaScript object:
const myBio = {
firstName: "Oluwatobi",
lastName: "Sofela",
company: "CodeSweetly",
};

// Convert myBio object to JSON (text format):
JSON.stringify(myBio);

// The invocation above will return:
// '{"firstName":"Oluwatobi","lastName":"Sofela","company":"CodeSweetly"}'

How to Convert a JSON Text to a JavaScript Array

Use parse() to convert a JSON text to a JavaScript array.

// Create a JSON text:
const myBio = '["Oluwatobi","Sofela","CodeSweetly"]';

// Convert myBio array to JSON (text format):
JSON.parse(myBio);

// The invocation above will return:
["Oluwatobi", "Sofela", "CodeSweetly"];

How to Convert a JSON Text to a JavaScript Object

Use parse() to convert a JSON text to a JavaScript object.

// Create a JSON text:
const myBio = '{"firstName":"Oluwatobi","lastName":"Sofela","company":"CodeSweetly"}';

// Convert the myBio JSON text to a JavaScript object:
JSON.parse(myBio);

// The invocation above will return:
{ firstName: "Oluwatobi", lastName: "Sofela", company: "CodeSweetly" };

How to Convert a Number to a String

Use toString() to convert a number to a string.

(45).toString();

// The invocation above will return: "45"

Try it on StackBlitz

How to Convert a String Number to Number Type

Use Number() to convert a string number to Number type.

Number("578");

// The invocation above will return: 578

Try it on StackBlitz

How to Convert a String to an Array

Use the spread operator (...) within an array to expand the string value into individual array items.

const myName = "Oluwatobi Sofela";

console.log([...myName]);

// The invocation above will return:
// ["O", "l", "u", "w", "a", "t", "o", "b", "i", " ", "S", "o", "f", "e", "l", "a"]

Try it on StackBlitz

How to Convert a String to Decimal

Use parseInt() to convert a string to decimal.

parseInt("1011001", 2);

// The invocation above will return: 89

Try it on StackBlitz

How to Convert a String to Lowercase

Use toLowerCase() to convert a string to lowercase.

"FRIDAY, MY FRIEND, WAS BORN ON FRIDAY".toLowerCase();

// The invocation above will return: "friday, my friend, was born on friday"

Try it on StackBlitz

How to Convert a String to Uppercase

Use toUpperCase() to convert a string to uppercase.

"friday, my friend, was born on friday".toUpperCase();

// The invocation above will return: "FRIDAY, MY FRIEND, WAS BORN ON FRIDAY"

Try it on StackBlitz

How to Convert Array to Object

Use the spread operator (...) within an object to expand the array into individual object properties.

const myNames = ["Oluwatobi", "Sofela"];
const bio = { ...myNames };

console.log(bio);

// The invocation above will return:
{0: "Oluwatobi", 1: "Sofela"}

How to Convert Binary to Decimal

Use parseInt() to convert a binary string to decimal.

parseInt("1011001", 2);

// The invocation above will return: 89

Try it on StackBlitz

How to Convert Hexadecimal to Decimal

Use parseInt() to convert a hexadecimal string to decimal.

parseInt("4fc", 16);

// The invocation above will return: 1276

Try it on StackBlitz

How to Copy Multiple Items from an Array

Use slice() to copy multiple items from an array.

// Define an array:
const colorsArray = ["red", "blue", "green", "white", "yellow", "pink"];

// Copy four items from colorsArray—starting from the first index position:
colorsArray.slice(1, 4);

// The invocation above will return: ["blue", "green", "white"]

How to Copy Part of a String in JavaScript

Use slice() to copy part of a string.

// Define a string:
const colorsString = "red, blue, green, white, yellow, pink";

// Duplicate three of colorsString's characters from the first index position:
const duplicatedColors = colorsString.slice(1, 4);

console.log(duplicatedColors);

// The invocation above will return: "ed,"

Try it on StackBlitz

How to Delete an Object's Property

Use the delete operator to delete an object's property.

const bookmark = { year: 2022, month: "December", day: 25 };

delete bookmark.year;

console.log(bookmark);

// The invocation above will return:
{month: "December", day: 25}

How to Determine If Users Have Scrolled a Web Page to the Bottom

Check if the web page's remaining scrollable height is equal to or less than zero.

window.addEventListener("scroll", checkIfScrolledToPageBottom);

function checkIfScrolledToPageBottom() {
const htmlElement = document.getElementsByTagName("html")[0];
const htmlPageHeight = htmlElement.scrollHeight;
const viewportHeight = htmlElement.clientHeight;
const lengthScrolled = htmlElement.scrollTop;
const totalWebpageScrollableHeight = htmlPageHeight - viewportHeight;
const remainingScrollableHeight =
totalWebpageScrollableHeight - lengthScrolled;

if (remainingScrollableHeight <= 0) {
alert("Scrolled to the bottom!");
}
}

How to Duplicate an Array's Content into Another Array

Use the spread operator (...) to copy an array's content into another array.

const myName = ["Sofela", "is", "my"];
const aboutMe = [...myName];

console.log(aboutMe);

// The invocation above will return: ["Sofela", "is", "my"]

How to Duplicate an Object's Properties into Another Object

Use the spread operator (...) to copy an object's properties into another object.

const myName = { firstName: "Oluwatobi", lastName: "Sofela" };
const bio = { ...myName };

console.log(bio);

// The invocation above will return:
{firstName: "Oluwatobi", lastName: "Sofela"}

How to Get a Webpage's Headings and IDs

Use forEach() to loop over a NodeList of the webpage's heading elements.

// Get all the webpage's elements with an id attribute:
const elementsWithID = document.querySelectorAll("[id]");

// Invoke a function for each element in the elementsWithID object:
elementsWithID.forEach((element) => {
if (element.localName === "h2") {
console.log(element.innerText);
console.log(`#${element.id}`);
}
});
Alternate solution
// Get all the webpage's elements with an id attribute:
const elementsWithID = document.querySelectorAll("[id]");

// Get the JavaScript array's forEach method and call it inside the elementsWithID object. Then, pass a function to the forEach() method:
[].forEach.call(elementsWithID, (element) => {
if (element.localName === "h2") {
console.log(element.innerText);
console.log(`#${element.id}`);
}
});
note

[].forEach is equivalent to Array.prototype.forEach.

How to Get First String Index from Array in JavaScript

Use indexOf() to get the first index position of an array's string.

["Sunday", "Tuesday", "Friday"].indexOf("Tuesday");

// The invocation above will return: 1

Try it on StackBlitz

How to Get First String Index from String in JavaScript

Use indexOf() to get the first index position of a string's text.

"SunDay, Tuesday, and Friday are good Days".indexOf("day");

// The invocation above will return: 12

Try it on StackBlitz

How to Get Last String Index from Array in JavaScript

Use lastIdexOf() to get the last index position of an array's string.

let daysOfTheWeek = [
"Sunday",
"Tuesday",
"Friday",
"Sunday",
"Tuesday",
"Friday",
];

daysOfTheWeek.lastIndexOf("Tuesday");

// The invocation above will return: 4

Try it on StackBlitz

How to Get Last String Index from String in JavaScript

Use lastIdexOf() to get the last index position of an string's text.

"Sunday, Tuesday, Friday, Sunday, Tuesday, Friday".lastIndexOf("Tuesday");

// The invocation above will return: 33

Try it on StackBlitz

How to Remove an Array’s First Item

Use shift() to remove an array’s first item.

const numbersArray = [1, 2, 3, 4];

numbersArray.shift();

console.log(numbersArray);

// The invocation above will return: [2, 3, 4]

How to Remove an Array’s Last Item

Use pop() to remove an array’s last item.

const numbersArray = [1, 2, 3, 4];

numbersArray.pop();

console.log(numbersArray);

// The invocation above will return: [1, 2, 3]

How to Remove Multiple Items from an Array

Use splice() to remove multiple items from an array.

// Define an array:
const colorsArray = ["red", "blue", "green", "white", "yellow", "pink"];

// Remove four items from colorsArray—starting from the first index position:
colorsArray.splice(1, 4);

// Print colorsArray's content on the console:
console.log(colorsArray);

// The invocation above will return: ["red", "pink"]

How to Remove Whitespace from a String's End part

Use trimEnd() to remove whitespace from a string's end part.

const myColor = "          I love blue.          ";

// Remove whitespace characters from the end part of myColor:
myColor.trimEnd();

// The invocation above will return: " I love blue."

Try it on CodePen

How to Remove Whitespace from Both Ends of a String

Use trim() to remove whitespace from both ends of a string.

const myColor = "          I love blue.          ";

// Remove whitespace characters from both ends of myColor:
myColor.trim();

// The invocation above will return: "I love blue."

Try it on CodePen

How to Remove Whitespace from the Start of a String

Use trimStart() to remove whitespace from the beginning of a string.

const myColor = "          I love blue.          ";

// Remove whitespace characters at the beginning of myColor:
myColor.trimStart();

// The invocation above will return: "I love blue. "

Try it on CodePen

How to Replace Part of a Text String

Use replace() to replace parts of a text.

"Friday, my friend, was born on Friday.".replace("Friday", "Sunday");

// The invocation above will return: "Sunday, my friend, was born on Friday."

Try it on StackBlitz

How to Search a String in JavaScript

Use search() to search a JavaScript string.

"SunDay, Tuesday, and Friday are good DAYS".search(/day/);

// The invocation above will return: 12

Try it on StackBlitz

How to Split a String in JavaScript

Use split() to split a JavaScript string.

"On the day".split("");

// The invocation above will return:
// ["O", "n", " ", "t", "h", "e", " ", "d", "a", "y"]

Try it on StackBlitz

How to Swap Two or More Variables' Values

Option 1: Use object destructuring

Use object destructuring to swap the values of two or more different variables.

// Define two variables:
let firstName = "Oluwatobi";
let website = "CodeSweetly";

// Reassign the firstName variable with the firstName property's value.
// And reassign the website variable with the website property's content:
({ firstName, website } = { firstName: website, website: firstName });

console.log(firstName); // "CodeSweetly"
console.log(website); // "Oluwatobi"

Try it on StackBlitz

Option 2: Use array destructuring

Use array destructuring to swap the values of two or more different variables.

// Define two variables:
let firstName = "Oluwatobi";
let website = "CodeSweetly";

// Reassign the firstName variable with the array's first item.
// And reassign the website variable with the array's second item:
[firstName, website] = [website, firstName];

console.log(firstName); // "CodeSweetly"
console.log(website); // "Oluwatobi"

Try it on StackBlitz

How to test if a string contains a RegExp in JavaScript

Use test() to test if a string contains a regular expression.

/Color/i.test("My best color is blue.");

// The invocation above will return: true

Try it on StackBlitz

How to Use an Array as a Function's Argument

Use the spread operator (...) to spread the array across the function's parameters.

const numbers = [1, 3, 5, 7];

function addNumbers(a, b, c, d) {
return a + b + c + d;
}

console.log(addNumbers(...numbers));

// The invocation above will return: 16

Try it on StackBlitz

How to Use JSON.stringify() with an Object without Deleting the Object's Function

Convert the object into a string before invoking JSON.stringify().

// Create a JavaScript object:
const myBio = {
firstName: "Oluwatobi",
lastName: function () {
return "Sofela";
},
company: "CodeSweetly",
};

// Convert the lastName function to a string:
myBio.lastName = myBio.lastName.toString();

// Convert myBio object to JSON (text format):
JSON.stringify(myBio);

// The invocation above will return:
// '{"firstName":"Oluwatobi","lastName":"function () {\\n return \\"Sofela\\";\\n }","company":"CodeSweetly"}'