DEV Community

Cover image for JavaScript: Tips and Tricks
Phat Nguyen
Phat Nguyen

Posted on • Updated on

JavaScript: Tips and Tricks

1. Filter Unique values

You can easily find unique value using Set.
The Set object type was introduced in ES6, and along with ..., the Spread operator, we can use it to create a new array with only the unique values

const array = [1, 2, 1, 3, 5, 5, 1];
const uniqueArray = [...new Set(array)];

console.log(uniqueArray); // 1, 2, 3, 5
Enter fullscreen mode Exit fullscreen mode

2. Short-Circuit Evaluation

Using && will return the first false or falsy value. If every operand evaluates to true, the last evaluated expression will be returned

console.log(true && false && 1); // false
console.log(true && true && 1); // 1
Enter fullscreen mode Exit fullscreen mode

Using || will return the first true or truthy value. If every operand evaluates to false, the last evaluated expression will be returned

console.log(true || false || 1); // true
console.log(true || true || 1); // 1
Enter fullscreen mode Exit fullscreen mode

3. Convert to Boolean

All values in JavaScript are truthy with the exception of 0, "", null, undefined, NaN and of course false, which are falsy.

We can easily switch between true and false by using the navigate operator !, which will alse convert the type to boolean

console.log(!0); // true
console.log(!1); // false
console.log(!!0); // false
Enter fullscreen mode Exit fullscreen mode

4. Convert to Number

The opposite can be quickly achieved using the addition operator +

let int = "1";
console.log(int); // "1"
console.log(typeof int); // "string"

int = +int;
console.log(int); // 1
console.log(typeof int); // "number"
Enter fullscreen mode Exit fullscreen mode

5. Quick Float to Integer

If you want to convert a float to an integer, you can use Math.floor(), Math.ceil() or Math.round(). But there is also a faster way to truncate a float to an integer using |, the bitwise OR operator.

console.log(15.9 | 0); // 15
console.log(-15.9 | 0); // -15
Enter fullscreen mode Exit fullscreen mode

6. Async/Await

Async

When we append the keyword async to the function, this function returns the Promise by default on execution. Async keyword provides extra information to the user of the function:

  • The function contains some Asynchronous Execution
  • The returned value will be the Resolved Value for the Promise
async function func() {
    return 1;
}

func().then(alert); // 1
Enter fullscreen mode Exit fullscreen mode

Await

The keyword await make JavaScript wait until that Promise settles and returns its result. The await works only inside async function.

async function func() {
    let promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("Done"), 1000);
    });

    let result = await promise;
    alert(result); // "Done"
}

func();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)