10 Quick JavaScript Tips and Tricks

While learning JavaScript, I’ve made it an effort to maintain a list of every time-saving trick that I found in other people’s code, on code challenge websites, and anywhere other than the tutorials I was using. This post is intended to be useful for beginners, but I hope even intermediate JavaScript developers will find something new in this list.

1. Filter for Unique Values

The 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 myArray = [1, 1, 1, 5, 3, 5]
const uniqArray = [...new Set(my_array)]
uniqArray; // => [1, 5, 3]

2. Destructuring console.logs

When debugging, it’s extremely helpful to see some additional detail about the variable you’re logging to the console. Traditionally I’ve handled this by doing something like this:

const someVar = 'Hello World'
console.log(someVar, '- This is the someVar variable')
=> Hello World - This is the someVar variable

While this works fine on a smaller scale as your code grows more complex this becomes increasingly unsustainable. To level your code and simplify your logs try something like this:

const someVar = 'Hello World'
console.log( {someVar} ) // => {someVar: "Hello World"}

3. Destructuring Arguments in Function Definitions

Destructuring your function’s arguments enables you to pass in the arguments in any order and receive the same output. This is especially useful if your declaration is in another file or includes too large a list of arguments to remember the exact positioning of each.

function getFullName( {first, middle, last} ) {
return `${first} ${middle} ${last}`
}
const first = 'John'
const middle = 'M'
const last = 'Doe'
getFullName({last, first, middle}) // => John M Doe

4. Short Circuit Evaluation with && Operator

This is a personal favorite of mine as it’s extremely simple, practical and quite useful. Short circuiting means that when evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.

expr && doSomething()// Instead of this:if (expr) {
doSomething()
}

5. Remove Falsy Values from an Array

To filter out all the values from an array, you can pass the constructor to the method. This works since constructor returns false on any falsy value and vice versa.

const arr = [ 0, 1, '', undefined, false, 2, undefined, null, , 3, NaN ]const filtered = arr.filter(Boolean)filtered; // => [1, 2, 3]

6. Swap Values with Array Destructuring

Knowing how to destructure an array, it’s easy to use it for swapping variables. Let’s swap the variables and using destructuring assignment:

const a = 1;
const b = 2;

[a, b] = [b, a];
a; // => 2
b; // => 1

At the first step, on the right side of the destructuring, a temporary array (which evaluates to ) is created.

Then the destructuring of the temporary array occurs: . The variable is assigned with , and with . The swapping of and has been performed.

I like this approach because it’s short and expressive: swapping is performed in just one statement. It also works with any data type: numbers, strings, booleans, objects.

7. Convert to Boolean with Double Bang (!!)

How the !! works — the first ! coerces the value to a boolean and inverses it. In this case, !value will return false. So to reverse it back to true, we put another ! on it. Hence the double bang !!

const array = [1,2]
!!array[0]; // => true
!!array[1]; // => true
!!array[2]; // => falseconst obj = {
value: 5,
node: null
}
!!obj.value; // => true
!!obj.node; // => false

8. console.table

console.table() allows you to display data in the console in a nice tabular format. It comes in very handy when having to visualize complex arrays or objects. It can display tabular data for arrays or objects. In this example, I’m hitting a fake JSON API endpoint to return some dummy user data. Logging it is fine but for a better visual representation of the data we can use console.table.

fetch('https://jsonplaceholder.typicode.com/users')
.then(resp => resp.json()
.then(console.table)

9. console.assert

Sometimes you want to log ONLY when a condition is falsy — this is known as an assertion. console.assert() writes an error message to the console if and only if the assertion is false. It keeps your code concise by eliminating the need for if statements.

// verbose
if (loggedIn) {
console.error('user is logged in assertion failed');
}

// much better
console.assert(loggedIn, 'user is logged in');

10. Truncate an Array

If you want to remove values from the end of an array destructively, there’s are faster alternatives than using .

For example, if you know the size of your original array, you can re-define its length property, like so:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4
console.log(array); // => [0, 1, 2, 3]

I hope you found these tips as useful as I did when I first discovered them. Got any JavaScript tricks of your own?