1. Array Filtering
Need to find all the even numbers in an array of test scores? One-liners to the rescue!
javascriptCopy codeconst scores = [85, 92, 73, 98, 80];
const evenScores = scores.filter(num => num % 2 === 0);
// evenScores will be [92, 98, 80]
This code uses the filter method to create a new array containing only the even scores. It’s perfect for keeping your data clean and relevant.
When to use: Filtering is a common operation to remove unwanted elements from arrays.
2. Array Mapping
Want to calculate the area of squares from an array of side lengths?
This one-liner will do the trick:
javascriptCopy codeconst sideLengths = [5, 3, 7];
const areas = sideLengths.map(num => num * num);
// areas will be [25, 9, 49]
The map method creates a new array with the results of a provided function applied to each element.
When to use: This is ideal for performing mathematical operations on array elements.
3. Flattening Arrays
Dealing with nested arrays can be tricky. Flatten them easily with this one-liner:
javascriptCopy codeconst nestedGroceries = [
["Apples", ["Red", "Green"]],
["Milk", ["Whole", "2%"]]
];
const flatGroceries = nestedGroceries.flat();
// flatGroceries will be ["Apples", "Red", "Green", "Milk", "Whole", "2%"]
The flat method concatenates all sub-array elements into a single array, simplifying data manipulation.
When to use: Flatten nested arrays to work with data in a single dimension.
4. Unique Elements (No Duplicates Allowed!)
Ensure your guest list has no duplicates with this handy one-liner:
javascriptCopy codeconst guestList = ["Alice", "Bob", "Charlie", "Alice"];
const uniqueGuests = [...new Set(guestList)];
// uniqueGuests will be ["Alice", "Bob", "Charlie"]
By using a Set, this code ensures all values are unique.
When to use: Removing duplicates is essential for data cleanliness.
5. Shorthand Conditionals
Tired of lengthy if...else statements? Use shorthand conditionals:
javascriptCopy codeconst age = 18;
const message = age >= 18 ? "Welcome!" : "Sorry, not yet.";
This ternary operator checks the condition and assigns the corresponding value.
When to use: For simple conditional assignments, keeping your code clean and efficient.
6. String Reversal
Check if a string is a palindrome with this one-liner:
javascriptCopy codeconst str = "Hello, world!";
const reversedStr = str.split('').reverse().join('');
// reversedStr will be "!dlrow ,olleH"
This snippet reverses the string by splitting it into an array, reversing the array, and then joining it back into a string.
When to use: Simplify string manipulation tasks with concise code.
7. Object Property Existence
Verify if a specific property exists in an object with this:
javascriptCopy codeconst user = { name: "Alice", age: 30 };
const hasEmail = "email" in user;
// hasEmail will be false (no email property)
The in operator checks if a property is present in an object.
When to use: Validate data by checking for specific attributes.
8. Default Parameter Values
Greet users with a default name if none is provided:
javascriptCopy codeconst greet = (name = "Guest") => `Hello, ${name}!`;
console.log(greet()); // Output: Hello, Guest!
console.log(greet("Bob")); // Output: Hello, Bob!
This function uses default parameters to ensure a value is always provided.
When to use: Prevent errors when functions are called without necessary arguments.
9. Compact Arrays
Remove empty or null values from arrays effortlessly:
javascriptCopy codeconst numbers = [1, 0, null, 3];
const compactNumbers = numbers.filter(Boolean);
// compactNumbers will be [1, 3]
Using Boolean in the filter method excludes all "falsy" values from the array.
When to use: Clean up arrays by removing unnecessary elements.
10. Dynamic Object Keys
Create objects with keys determined at runtime:
javascriptCopy codeconst prop = "score";
const person = { [prop]: 90 };
// person will be {score: 90}
This one-liner uses computed property names to dynamically assign key names.
When to use: Useful for dynamic object creation where key names are variable.
These JavaScript one-liners are not just concise but also powerful in enhancing your coding efficiency. Incorporate these into your daily coding practice, and you'll find your tasks becoming much easier and more enjoyable.
See you in the next one
Shrey
