How To – Code Snippets
Use code snippets to learn software development concepts.
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"]
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"]
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"]
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
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
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
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}
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
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
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"]'
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"}'
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"];
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" };
Convert a Number to a String
Use toString()
to convert a number to a string.
(45).toString();
// The invocation above will return: "45"
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
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"]
Convert a String to Decimal
Use parseInt()
to convert a string to decimal.
parseInt("1011001", 2);
// The invocation above will return: 89
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"
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"
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"}
Convert Binary to Decimal
Use parseInt()
to convert a binary string to decimal.
parseInt("1011001", 2);
// The invocation above will return: 89
Convert Hexadecimal to Decimal
Use parseInt()
to convert a hexadecimal string to decimal.
parseInt("4fc", 16);
// The invocation above will return: 1276
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"]
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,"
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}
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
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
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"}
Find the Central NPX Cache
Run the following command on your terminal to get the central NPX cache:
npm config get cache
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) => { 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
Use indexOf()
to get the first index position of an array’s string.
["Sunday", "Tuesday", "Friday"].indexOf("Tuesday");
// The invocation above will return: 1
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
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
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
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]
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]
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"]
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."
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."
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. "
Use CSS Grid like a pro
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."
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
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"]
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"
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"
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
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
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"}'