Some frequently used ES6 code snippets

Summary

A compilation of frequently used ES6 code snippets provides concise solutions for various JavaScript programming challenges. It showcases efficient array manipulations, including shuffling elements, removing duplicates, finding minimum or maximum values, and filtering out falsy entries. Practical string operations are also covered, such as extracting numeric characters, reversing sequences, and determining if one string is a reversal of another. Additionally, the snippets illustrate object merging with the spread syntax, destructuring assignments for cleaner variable extraction, and freezing objects to ensure immutability. The collection concludes with examples of type comparison differences and the nullish coalescing operator for handling undefined or null values.

Below are a list of ES6 code snippets which are used frequently. Hope that it will be helpful.

1. Shuffle array elements

let arr = [67, true, false, '55']
arr = arr.sort(() => 0.5 - Math.random())
console.log(arr)
// [ '55', 67, false, true ]

2. Remove characters which are not numbers

const str = 'xieyezi 23213 is 95994 so hansome 223333'
const numbers = str.replace(/\D/g, '')
console.log(numbers)
// 2321395994223333

3. Reverse sequence or words

const sentence = 'xieyezi js so handsome, lol.'
const reverseSentence = reverseBySeparator(sentence, "")
console.log(reverseSentence);
// .lol ,emosdnah os sj izeyeix

const reverseEachWord = reverseBySeparator(reverseSentence, " ")
console.log(reverseEachWord)
// izeyeix sj os ,emosdnah .lol

function reverseBySeparator(string, separator) {
  return string.split(separator).reverse().join(separator)
}

4. Convert number to binary or hex decimal

const num = 45
num.toString(2)
num.tostring(16)

5. Merge objects

const city = {
  name: 'Chongqing',
  population: '1,234,567,890'
}
const location = {
  longitude: '116.4',
  latitude: '39.9'
}
const fullCity = { ...city, ...location }
console.log(fullCity)
// {
//   name: 'Chongqing',
//   population: '1,234,567,890',
//   longitude: '116.4',
//   latitude: '39.9'
// }

6. === vs ==

// ==   ->  type conversion compariosn
// ===  ->  non-type conversion comparison

0 == false // true
0 === false // false
1 == "1" // true
1 === "1" // false
null == undefined // true
null === undefined // false

7. Assignment to variables from object properties

const forest = {
  location: 'Sweden',
  animals: 3,
  animalsTypes: ['Lions', 'Tigers', 'Bears'],
};

const { location, animals, animalsTypes } = forest;
const [lions, tigers, bears] = animalsTypes;

console.log(location); // Sweden
console.log(animals); // 3
console.log(lions); // Lions
console.log(tigers); // Tigers
console.log(bears); // Bears

8. Swap values of variables

let bears = 'bears'
let tigers = 'tigers'
[bears, tigers] = [tigers, bears]
console.log(bears) // tigers
console.log(tribes) // bears

9. Check whether one string is reversion of another string

const isReversed = (str1, str2) => {
  const normalize = (str) =>
    str.toLowerCase()
    .normalize('NFD')
    .split('')
    .reverse()
    .join('')
  return normalize(str1) === str2
}
console.log(isReversed('anagram', 'margana')) // true
console.log(isReversed('rac', 'car')) // true

10. Freeze an object

const octopus = {
  tentacles: 8,
  color: 'blue',
}
Object.freeze(octopus)
octopus.tentacles = 10 // Error, will not update
console.log(octopus) // { tentacles: 8, color: 'blue'}

11. Remove duplicated elements in array

const animals = ['bears', 'lions', 'tigers', 'bears', 'lions']
const unique = (arr) => [...new Set(arr)]

console.log(unique(animals)) // [ 'bears', 'lions', 'tigers' ]

12. Convert RGB to Hex format

const rgbToHex = (r, g, b) => {
  const toHex = (num) => {
    const hex = num.toString(16)
    return hex.length === 1 ? `0${hex}` : hex
  }
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
console.log(rgbToHex(46, 32, 67)) // #2e2043

13. Get max or min from array

const nums = [1, 2, 3, 4, 5, -3, 99, -45, -1]
const max = Math.max(...nums)
const min = Math.min(...nums)
console.log(max) // 99
console.log(min) // -45

14. Remove false values

const nums = [1, 0 , undefined, null, false];
const truthyNums = nums.filter(Boolean);
console.log(truthyNums) // [1]

15. Return default value if undefined or null

const nullval = null
const emptyString = ''
const someNum = 13

const a = nullval ?? 'A default'
const b = emptyString ?? 'B default'
const c = SomeNum ?? 'C default'

console.log(a) // A default
console.log(b) // '' // empty string != undefined or null
console.log(c) // 13

Reference: https://github.com/xieyezi/vuepress-blog/blob/master/docs/front-end/ES6-20%E4%B8%AA%E7%BB%8F%E5%B8%B8%E4%BD%BF%E7%94%A8%E7%9A%84%E6%8A%80%E5%B7%A7.md

JAVASCRIPT TIPS CODE SNIPPET ES6

  RELATED

  COMMENTS

0

No comment for this article.