10 JavaScript One-Liner Code You Should Know
Published: 2024-07-07 18:30:00

---
title: "10 JavaScript One-Liner Code You Should Know"
excerpt: "Explore these 10 essential JavaScript one-liners that simplify common tasks and enhance your coding efficiency! From concise array manipulations to elegant string operations, discover how these compact lines of code can streamline your development process. Whether you're a beginner looking to level up or an experienced developer seeking handy tricks, these snippets offer valuable insights into leveraging JavaScript's power with minimal syntax. Dive into the world of succinct solutions and elevate your coding game today! 🚀 #JavaScript #CodingTips #WebDevelopment"
coverImage: "https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q5nkbn9lxj6x1kbet6xd.png"
author:
  name: manjushsh
  picture: "https://avatars.githubusercontent.com/u/94426452"
ogImage:
  url: "https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q5nkbn9lxj6x1kbet6xd.png"
---

## 1. Deep clone object
This one-Liner will make a Deep clone of a javascript object:

```typescript
const originalObject = {
  "studentId": 26334,
  "studentName":"John Doe",
  "totalMarks": 348.50
};

const clonedObject = structuredClone(originalObject);

console.log("Student details: ", clonedObject);

// Output: { studentId: 26334, studentName: "John Doe", totalMarks: 348.5 }
```

## 2. Truncate a String To a Specific Length
This is One-Liner is to truncate a string and add "..." to an end on a specific given length

```typescript
const originalString = "The quick brown fox jumps over the lazy dog";

const truncate = (str, len) => str?.length > len ? str.slice(0, len) + "..." : str;

console.log("Truncated string: ", truncate(originalString, 9));

// Output: The quick...
```

## 3. Remove duplicate elements in array
This one-Liner will return a new array without duplicate elements from original array

```typescript
const originalArray = [9,'a',8,'a','b',9,5,3,9,3.5,'b'];

const removeDuplicates = arr => [...new Set(arr)]

console.log("Array without duplicates: ", removeDuplicates(originalArray));

 // Output: [ 9, "a", 8, "b", 5, 3, 3.5 ]
```

## 3. Swap numbers
This one liner swaps 2 numbers: 

```typescript
let a=6, b=9;

[a,b] = [b,a]

console.log(`Swapped Values - a: ${a} b: ${b}`);

// Output: Swapped Values - a: 9 b: 6

```

## 4. Flatten a nested array
This one liner helps you to flatten a nested array
```typescript
const flattenArray = (arr) => [].concat(...arr);
console.log("Flattened: ", flattenArray([1, [2, 5, 6], 7,6, [2,3]])

// Output: Flattened: [ 1, 2, 5, 6, 7, 6, 2, 3 ]
```

## 5. Scroll To Top
This one liner instantly navigates you to the top of the page:
```typescript
window.scrollTo(0, 0)
```

## 6. Find the Last Occurrence in an Array:
This one liner returns last occurrence of element in an array:

```typescript
const lastIndexOf = (arr, item) => arr.lastIndexOf(item);
console.log("Last index of 7 is: ", lastIndexOf([7, 5, 6 , 7 , 3 , 4], 7))

// Output: Last index of 7 is:  3
```

## 7. Make Your Code Wait for a Specific Time
Sometimes we want to make our code wait out for a seconds,
```typescript
const waitForIt = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
  console.log("Before waiting");
  await waitForIt(5000);
  console.log("After waiting for 5 seconds");
})();

/* Output: 
Before waiting
Promise { <state>: "pending" }
After waiting for 5 seconds   
*/
```

## 8. Extract a Property from an Array of Objects
Need to grab a specific property from an array of objects? Cherry-pick it!

```typescript
const getValuesOfAKey = (arr, key) => arr.map(obj => obj[key]);
console.log("Values of a: ", getValuesOfAKey([{a: 1}, {a: 2}], 'a'));

// Output: Values of a: Array [ 1, 2 ]
```

## 9. Generate a Random Hexadecimal Color Code:
Get a random hex color code!
```typescript
const randomColor = "#" + (~~(Math.random() * 8**8)).toString(16).padStart(6,0);
console.log("Generated code: ", randomColor);

// Output: Generated code:  #0cf199
```

## 10. Remove falsy values from array
```typescript
const removeFalsy = (arr) => arr.filter(Boolean);
console.log("Without falsy:", removeFalsy([true, false, undefined, NaN, null, false, true]))

// Output: Without falsy: [ true, true ] 
```