공부/JavaScript

I Bet You Don’t Use These JavaScript Tricks and Practices | Medium

Dev_YJ 2024. 9. 30. 13:27

1. Flatmap : filter + map

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// using filterAndMap
const squaredOddNumbers = numbers
    .filter(num => num % 2 !== 0)
    .map(num => num * num)

console.log(squaredOddNumbers); // [1, 9, 25, 49, 81]

// using flatMap
const squaredOddNumbers = numbers.flatMap(num => 
    num % 2 !== 0 ? [num * num] : []
);


console.log(squaredOddNumbers); // [1, 9, 25, 49, 81]

 

2. Nullish Coalescing

  • It provides a concise way to handle default values in situations where null or undefined are considered falsy values.
    ( ES11 / ECMA Script 2020 )
// Without Nullish Coalescing
let userInput = null; // This value can come from user input or an external source

let username = userInput !== null && userInput !== undefined ? userInput : 'Guest';

console.log(username); // 'Guest' when userInput is null or undefined

// With Nullish Coalescing
let userInput = null;

let username = userInput ?? 'Guest';

console.log(username); // 'Guest' when userInput is null or undefined

 

3. Dynamic Import

  • Dynamic import is a feature in JavaScript that allows you to import modules conditionally or on-demand during runtime. It is implemented using the import() function, which returns a Promise that resolves to the module namespace object.
// Assuming you have a module named 'mathFunctions' with various functions
// export const add = (a, b) => a + b;
// export const subtract = (a, b) => a - b;

// Importing the module dynamically
const mathModulePromise = import('./mathFunctions');

// Resolving the promise to get the module namespace object
mathModulePromise.then((mathModule) => {
  const result1 = mathModule.add(5, 3);
  const result2 = mathModule.subtract(8, 4);

  console.log('Result of addition:', result1);
  console.log('Result of subtraction:', result2);
})
.catch((error) => {
  console.error('Error during dynamic import:', error);
});

 

4. String.prototype.replaceAll()

  • replaceAll method on string replaces all occurrence of particular string with passed string. It returns a new string, it does not modify the original string. ( ES12 / ECMA Script 2021 )
const str = "hello there, hello mr, hello how?";
const newStr = str.replaceAll("hello", "bye");

console.log(newStr); // bye there, bye mr, bye how?

 

5. Promise.any

  • It takes an iterable of Promises and returns a single Promise. This new Promise is fulfilled with the value of the first fulfilled Promise from the iterable.
  • If all Promises in the iterable are rejected, it returns a single rejected Promise with an AggregateError containing an array of rejection reasons.
  • If any promise get rejected in between, if waits for other promises to get resolve.
const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Promise 1 resolved'), 1000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => reject('Promise 2 rejected'), 500);
});

const promise3 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Promise 3 resolved'), 1500);
});

Promise.any([promise1, promise2, promise3])
  .then(result => {
    console.log('Fulfilled:', result);
  })
  .catch(error => {
    console.log('Rejected:', error);
  });

 

6. WeakRef

ES12 / ECMA Script 2021

  • In JavaScript, a WeakRef is an object that holds a weak reference to another object. A weak reference is a reference that does not prevent the object it references from being garbage-collected. This is in contrast to a strong reference, which keeps an object alive as long as the reference exists.
let weakRef;
{
  const localObj = { data: 'local' };
  weakRef = new WeakRef(localObj);
}

// At this point, 'localObj' is out of scope, and it can be garbage-collected

const retrievedObj = weakRef.deref();
console.log(retrievedObj); // Outputs: undefined (because 'localObj' has been garbage-collected)

 

7. &&=||= and ??=

ES12 / ECMA Script 2021

  • &&= (Logical AND Assignment)
let x = 5;
let y = 10;

x &&= y;

console.log(x); // Outputs: 10 
// (because x is truthy, it gets assigned the value of y)
// x, y가 모두 true이면 x 에 y 할당. x 가 false 또는 null이면 x 출력
  • ||= (Logical OR Assignment)
    This operator assigns the right operand to the left operand if the left operand is falsy.
let a = 0;
let b = 20;

a ||= b;

console.log(a); // Outputs: 20 
// (because a is falsy, it gets assigned the value of b)
// a 또는 b 가 true 이면 a 에 b 할당
  • ??= (Nullish Coalescing Assignment)
let p = null;
let q = 42;

p ??= q;

console.log(p); // Outputs: 42 
// (because p is null, it gets assigned the value of q)
// p 가 null 이나 undefined 일때 p 에 q 할당

 

8. at() method for StringsArrays

ES13 / ECMA Script 2022

const str = 'Hello, World!';

console.log(str.at(1));     // "e"
console.log(str.at(-1));    // "!"
console.log(str.at(1000));  // undefined

const arr = ['apple', 'banana', 'orange'];

console.log(arr.at(0));    // "apple"
console.log(arr.at(-1));   // "orange"
console.log(arr.at(5));    // undefined

 

9. Array Find from Last

ES13 / ECMA Script 2022
find, findIndex 와 비슷하지만 뒤에서부터 찾는다

const array1 = [5, 12, 50, 130, 44];
const found = array1.findLast((element) => element > 45);
console.log(found);
// Expected output: 130


const array1 = [5, 12, 50, 130, 44];
const isLargeNumber = (element) => element > 45;
console.log(array1.findLastIndex(isLargeNumber));
// Expected output: 3
// Index of element with value: 130

 

※ 참고

'공부 > JavaScript' 카테고리의 다른 글

진법 변환 (toString, parseInt)  (0) 2025.01.09
Object Validation in JavaScript  (0) 2024.09.30
JSON (dreamcoding) | ES6  (0) 2021.01.31
Array-APIs (dreamcoding) | ES6  (0) 2021.01.31
Array (dreamcoding) | ES6  (0) 2021.01.28