Member-only story
JavaScript is full of powerful features that can make your code both elegant and efficient. In this list, we’ll explore 25 one-liners that every developer should know, whether you’re just starting or you’re a seasoned pro. These handy snippets will help you write cleaner, more concise code, making your JavaScript skills truly shine.
Not a Medium member? Read this article here
- Clone an Object
const originalObj = { name: 'Jane', age: 22 };
const clonedObj = { ...originalObj };
// Output: clonedObj = { name: 'Jane', age: 22 }
Use the spread operator to quickly create a shallow clone of an object. No need for complex cloning methods — just a simple one-liner.
2. Get the Last Item in an Array
const lastItem = arr[arr.length - 1];
// Output: lastItem = 5 (if arr = [1, 2, 3, 4, 5])
Access the last item in an array without needing to know its length explicitly.
3. Short-Circuit Conditionals
const result = isValid && doSomething();
// Output: Calls doSomething() only if isValid is true
Execute a function or assign a value only if a condition is true. This makes for more streamlined and efficient code.