I Tried and Loved: 7 Javascript tricks

Β·

2 min read

These are my notes for this video

  1. Removing Falsy Values from an Array:

    • Use the filter method with a callback function that returns Boolean(name) to remove falsy values.
    const filteredName = myName.filter(name => Boolean(name));
  1. Checking for Even Numbers in an Array:

    • Use the some method to check if at least one element in the array passes a test.
    const hasEvens = array.some(num => num % 2 === 0);
  1. Removing Duplicate Items from an Array:

    • Use a Set to automatically remove duplicate items and spread the set into a new array.
    const uniqueArray = [...new Set(array)];
  1. Using Nullish Coalescing Operator for Default Values:

    • Instead of using a ternary operator, use the nullish coalescing operator (??) to provide a default value for null or undefined.
    const greeting = name ?? "friend";
  1. Simplifying Sort Order in Array Sorting:

    • Use a and z as variables instead of a and b when sorting in ascending order, and use z and a for descending order.
    array.sort((a, z) => a - z); // ascending order
    array.sort((z, a) => a - z); // descending order
  1. Destructuring Arrays and Objects:

    • Use destructuring assignment to assign variables from arrays or objects.
    const [first, middle, last] = myName;
    const { name, username, age } = person;
  1. Creating Arrays of a Specific Length and Filling with Values:

    • Use the Array.from method with a mapping function to create an array of a specific length filled with arbitrary values.
    const newArray = Array.from({ length: n }, (_, index) => index);
Β