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 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 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 String to 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 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 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 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 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