Mastering essential JavaScript code snippets can significantly enhance your front-end development skills. This article covers 30 practical code snippets that can help you streamline your coding process and improve efficiency.
Basic Code Snippets
Array Operations
Flatten Arrays: Convert multi-dimensional arrays into one-dimensional arrays.
const flatArray = [].concat(...arr);Manual Delay: Set a process to wait for a specified number of milliseconds.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));Randomize Array Order: Generate a random order for array elements.
const randomArr = (arr) => arr.sort(() => Math.random() - 0.5);Remove Duplicates from Arrays: Remove duplicate elements from an array.
const getSingleArr = (arr) => [...new Set(arr)];
Date and Time Operations
Check if Date is on Weekend:
const isWeekend = (date) => date.getDay() === 6 || date.getDay() === 0;Check if Date is Within a Year:
const isInAYear = (date, year) => date.getUTCFullYear() === new Date(`${year}`).getUTCFullYear();Check if Date is Valid:
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
String Operations
Capitalize First Letter of String:
const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.slice(1);Reverse String:
const reverseString = (str) => str.split("").reverse().join("");Generate Random String:
const randomString = () => Math.random().toString(36).slice(2);
Advanced Code Snippets
Utility Functions
Calculate Time Difference Between Two Dates:
const dayDif = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000);Get Days Since Start of Year:
const dayOfYear = (d) => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 86400000);Format Date as Time (HH:mm:ss):
const getTimeFormat = (date) => date.toTimeString().slice(0, 8);Truncate String to Specified Length:
const substr = (str, len) => (str.length < len ? str : `${str.slice(0, len - 3)} ...`);Remove HTML Content from String:
const stripHtml = (html) => new DOMParser().parseFromString(html, "text/html").body.textContent || "";
Miscellaneous
Check if Array is Empty:
const isNotEmpty = (arr) => Array.isArray(arr) && arr.length > 0;Merge Two Arrays:
const merge = (a, b) => [...a, ...b];Check if Number is Even:
const isEven = (num) => num % 2 === 0;Calculate Average of Numbers:
const average = (...args) => args.reduce((a, b) => a + b) / args.length;Generate Random Number:
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);Round to Specified Decimal Places:
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d);Get Random Color:
const randomHex = () =>`#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
Conclusion
Mastering these JavaScript code snippets can significantly enhance your front-end development skills. By incorporating these snippets into your toolkit, you can streamline your coding process and improve efficiency. We hope the content of this article helps you become more proficient in JavaScript!