Elevate Your Coding Skills with These JavaScript One-Liners
Written on
Chapter 1: Introduction to JavaScript One-Liners
In this article, we present more than ten efficient one-liner JavaScript snippets aimed at improving your coding prowess. These snippets cover everything from array and string manipulations to more intricate topics such as asynchronous programming and object-oriented techniques. Let’s get started! 🏊♂️
Section 1.1: Random Element Selection from an Array
Fetching a random item from an array is a breeze with the combination of Math.random() and the array's length:
const arr = [1, 2, 3, 4, 5];
const randomElement = arr[Math.floor(Math.random() * arr.length)];
console.log(randomElement);
Section 1.2: Flattening Nested Arrays
You can easily flatten arrays using the reduce() and concat() methods:
const arr = [[1, 2], [3, 4], [5, 6]];
const flattenedArr = arr.reduce((acc, cur) => acc.concat(cur), []);
console.log(flattenedArr); // Output: [1, 2, 3, 4, 5, 6]
Section 1.3: Sorting Arrays by a Specific Property
Sort an array of objects based on a specific property value with ease:
const sortedArray = array.sort((a, b) => (a.property > b.property ? 1 : -1));
Section 1.4: Filtering Out Unwanted Elements
You can swiftly remove specific elements from an array:
const removedArray = array.filter((item) => item !== elementToRemove);
Section 1.5: Checking for Duplicates in an Array
To determine if there are duplicates in an array:
const hasDuplicates = (array) => new Set(array).size !== array.length;
Section 1.6: Checking for the Existence of a Value
Quickly check if a value exists in an array:
const hasValue = arr.includes(value);
Section 1.7: Capitalizing the First Letter of a String
Transform the initial character of a string to uppercase:
const capitalized = str.charAt(0).toUpperCase() + str.slice(1);
Section 1.8: Generating a Random Integer
Create a random integer within a specified range:
const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
Section 1.9: Creating a Random String
Generate a random string of a defined length:
const randomStr = Math.random().toString(36).substring(2, length);
Section 1.10: Swapping Values of Variables
You can easily swap values between two variables using destructuring:
let a = 1, b = 2;
[b, a] = [a, b];
console.log(a, b); // 2, 1
Section 1.11: Converting a String to camelCase
Effortlessly convert any string to camelCase format:
const str = 'hello world';
const camelCase = str.replace(/s(.)/g, ($1) => $1.toUpperCase()).replace(/s/g, '').replace(/^(.)/, ($1) => $1.toLowerCase());
console.log(camelCase); // "helloWorld"
Section 1.12: Calculating Time Intervals
Determine the number of days between two dates:
const diffInDays = (dateA, dateB) => Math.floor((dateB - dateA) / (1000 * 60 * 60 * 24));
Section 1.13: Discovering the Day of the Year
Find out which day of the year a particular date falls on:
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
Section 1.14: Copying Text to Clipboard
Effortlessly copy text to your clipboard:
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
Section 1.15: Identifying Variable Types
Determine the type of any variable in JavaScript:
const getType = (variable) => Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
getType(''); // string
Section 1.16: Checking if an Object is Empty
Quickly check whether an object contains no properties:
const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;
These concise JavaScript one-liners not only save time but also contribute to writing cleaner and more efficient code. Happy coding! 🎉
Chapter 2: Video Resources
To further enhance your understanding of JavaScript one-liners, check out these informative videos:
The first video, Top 10 JavaScript One-Liners YOU MUST KNOW!, provides a comprehensive overview of essential JavaScript snippets to streamline your coding process.
The second video, 10 Life-Saving JavaScript One-Liners 🔥 CODE LIKE A PRO 2022, showcases additional practical one-liners that can significantly improve your coding efficiency.