Skip to content
Latest: Publish JavaScript Packages to NPM Like a Pro!

How To – Code Snippets

Use code snippets to learn software development concepts.

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"]

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"]

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"]

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

Number.isInteger(578);
// The invocation above will return: true

Try Editing It

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 Editing It

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

[1, 3, 5, 7].includes(5);
// The invocation above will return: true

Try Editing It

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}

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

Number(true);
// The invocation above will return: 1

Try Editing It

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

Number(new Date(2022, 06, 01));
// The invocation above will return: 1656630000000

Try Editing It

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"]'

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"}'

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"];

Convert a JSON Text to a JavaScript Object

Section titled “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" };

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

(45).toString();
// The invocation above will return: "45"

Try Editing It

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

Number("578");
// The invocation above will return: 578

Try Editing It

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 Editing It

Use parseInt() to convert a string to decimal.

parseInt("1011001", 2);
// The invocation above will return: 89

Try Editing It

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 Editing It

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 Editing It

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"}

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

parseInt("1011001", 2);
// The invocation above will return: 89

Try Editing It

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

parseInt("4fc", 16);
// The invocation above will return: 1276

Try Editing It

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"]

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 Editing It

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}

Determine If Users Have Scrolled a Web Page to the Bottom

Section titled “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!");
}
}

Duplicate an Array’s Content into Another Array

Section titled “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"]

Duplicate an Object’s Properties into Another Object

Section titled “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"}

Run the following command on your terminal to get the central NPX cache:

Terminal
npm config get cache

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) => {
const text = element.innerText;
const id = `#${element.id}`;
if (element.localName === "h2") {
console.log(text);
console.log(id);
}
});

Get First String Index from Array in JavaScript

Section titled “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 Editing It

Get First String Index from String in JavaScript

Section titled “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 Editing It

Get Last String Index from Array in JavaScript

Section titled “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 Editing It

Get Last String Index from String in JavaScript

Section titled “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 Editing It

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]

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]

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"]

Remove Whitespace from a String’s End part

Section titled “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

Remove Whitespace from Both Ends of a String

Section titled “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

Remove Whitespace from the Start of a String

Section titled “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

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 Editing It

Use search() to search a JavaScript string.

"SunDay, Tuesday, and Friday are good DAYS".search(/day/);
// The invocation above will return: 12

Try Editing It

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 Editing It

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 Editing It

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 Editing It

Test If a String Contains a RegExp in JavaScript

Section titled “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 Editing It

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 Editing It

Use JSON.stringify() with an Object without Deleting the Object’s Function

Section titled “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"}'