Sitemap

7 Javascript Quick Tricks

5 min readOct 24, 2021

--

Press enter or click to view image in full size
Photo by shawn henry on Unsplash

1. Console object methods

Whilst console.log is ubiquitous across nearly every codebase, there are actually quite a few other methods that can be called on the console object.

Want to display your array or object in a table? — use console.table()

const users = [ 
{
"first_name":"Harcourt",
"last_name":"Huckerbe",
"gender":"Male",
"city":"Linchen",
"birth_country":"China"
},
{
"first_name":"Allyn",
"last_name":"McEttigen",
"gender":"Male",
"city":"Ambelókipoi",
"birth_country":"Greece"
},
{
"first_name":"Sandor",
"last_name":"Degg",
"gender":"Male",
"city":"Mthatha",
"birth_country":"South Africa"
}
]
console.table(users, ['first_name', 'last_name', 'city']);
┌─────────┬────────────┬─────────────┬───────────────┐
│ (index) │ first_name │ last_name │ city |├─────────┼────────────┼─────────────┼───────────────┤
│ 0 │ 'Harcourt' │ 'Huckerbe' │ 'Linchen' │
│ 1 │ 'Allyn' │ 'McEttigen' │ 'Ambelókipoi' │
│ 2 │ 'Sandor' │ 'Degg' │ 'Mthatha' │
└─────────┴────────────┴─────────────┴───────────────┘

You can call console.table() with just a single parameter, or multiple. You can customize the columns you want to see.

When you want that timer function? Wondering how much time a piece of code takes? How much time does it take? console.time() & console.timeEnd()

You can name each timer instance by passing in a string.

Want to know how many times you’ve console logged something? console.count()

console.count('Hello');
// Hello: 1
console.count('Hello');
// Hello: 2
console.count('Hello');
// Hello: 3

Only print if something is false? console.assert()

2. array.sort()

I’ve recently worked on a project, where we needed to sort objects in an array in a specific order, based on their category. So for example; if we wanted to order the food items on a supermarket shopping spree by food category we could do so easily using this sort method.

const order = ["MEAT", "VEGETABLES", "FRUIT", "SNACKS"];const items = [
{ name: "peppers", type: "VEGETABLES", price: 2.39 },
{ name: "apples", type: "FRUIT", price: 3.99 },
{ name: "chocolate", type: "SNACKS", price: 3.45 },
{ name: "pork", type: "MEAT", price: 6 },
{ name: "ham", type: "MEAT", price: 4 }
];
items.sort((a, b) => {
return order.indexOf(a.type) > order.indexOf(b.type);
});
console.table(items, ["type", "name"]);
// ┌─────────┬──────────────┬─────────────┐
// │ (index) │ type │ name │
// ├─────────┼──────────────┼─────────────┤
// │ 0 │ 'MEAT' │ 'pork' │
// │ 1 │ 'MEAT' │ 'ham' │
// │ 2 │ 'VEGETABLES' │ 'peppers' │
// │ 3 │ 'FRUIT' │ 'apples' │
// │ 4 │ 'SNACKS' │ 'chocolate' │
// └─────────┴──────────────┴─────────────┘

3. Filter, every and some on arrays

Sticking with food shopping theme, we can use the filter method on the array to filter by any of the attributes. In our case, price. With filter, you simply return a boolean on whether it should be included. The filter method loops through all of the items in the array.

const order = ["MEAT", "VEGETABLES", "FRUIT", "SNACKS"];let items = [
{ name: "peppers", type: "VEGETABLES", price: 2.39 },
{ name: "apples", type: "FRUIT", price: 3.99 },
{ name: "chocolate", type: "SNACKS", price: 3.45 },
{ name: "pork", type: "MEAT", price: 6 },
{ name: "ham", type: "MEAT", price: 7 }
];
items = items.filter(item => {
return item.price > 4;
});
console.table(items);
// ┌─────────┬────────┬────────┬───────┐
// │ (index) │ name │ type │ price │
// ├─────────┼────────┼────────┼───────┤
// │ 0 │ 'pork' │ 'MEAT' │ 6 │
// │ 1 │ 'ham' │ 'MEAT' │ 7 │
// └─────────┴────────┴────────┴───────┘

In our case we filtered by price. For example; for ham the expression evaluates to a true boolean value, this item will be included in the revised array.

item.price > 4 // true

For apples on the other hand the expression evaluates to false, therefore it’s excluded in the revised array.

4. Optional Chaining

const object = {
family: {
father: {
age: 54
},
sister: {
age: 16
}
}
}
const ageOfFather = object.family.father.age;
console.log(`Age of Father ${ageOfFather}`);
//Age of Father 54
const ageOfBrother = object?.family?.brother?.age;
console.log(`Age of Brother ${ageOfBrother}`);
//Age of Brother undefined

Optional chaining allows you to verify and use a nested object property without determining whether each parent exists. In the above example, we can get the age of the brother and assign it if the property exists. Before optional chaining we would have to determine whether the parent existed first;

const ageOfBrother = object.family && object.family.brother && object.family.brother.age;

This chaining obviously becomes very long for a deeply nested property.

Get Aidan Hallett’s stories in your inbox

Join Medium for free to get updates from this writer.

Obviously, without object chaining and without checking the parent of the child object would cause a TypeError;

const ageOfMother = object.family.mother.age;
^
TypeError: Cannot read property 'age' of undefined

5. Simplify numbers using underscore

Introduced in ES2021, it is now possible to separate a number using underscores to make it easier to read quickly.

// ES2020
const oneMillion = 1000000;

// ES2021
const oneMillion = 1_000_000;

6. String.prototype.replaceAll

Up until now, one would need to use a regular expression with a global flag to replace characters/ words in a given string.

const result = 'Hello World'.replace(/\s/g, '-');
// result => 'Hello-World'

Now we can simply use the replaceAll string method

const result = 'Hello World'.replaceAll(' ', '-');
// result => 'Hello-World'

7. Logical Assignment Operators

Nullish Assignment Operator

Up until ES2021, we could assign determine optional type variables (i.e. variables that may or may not have a value) using a ternary operator or an OR;

Using a Ternary Operator

// Using Ternary Operator
let template;
console.log(template);
// undefined
template = template != null ? template : 'default';
console.log(template);
// default

Using an If statement

// Using If statement
let template;
console.log(template);
// undefined
if (template == null) {
template = 'default';
}
console.log(template);
// default

With ES2021, its a much simpler assignment;

let template;
console.log(template);
// undefined
template ??= 'default';
console.log(template);
// default

Logical OR Assignment Operator

The Logical OR assignment operator works similar to the Nullish assignment operator, except instead of null or undefined, it assigns to the given variable if the variable is evaluates to falsey.

const user = {id: 18, first_name: "Aidan"};
console.log(user);
// {id: 18, first_name: "Aidan"}
if(!user.profile_picture) {
user.profile_picture = "https://picsum.photos/id/237/200/300" ;
}
console.log(user);
// {id: 18, first_name: "Aidan", profile_picture: "https://picsum.photos/id/237/200/300"}

Logical AND Assignment Operator

The Logical AND assignment operator assigns a value if the variable evaluates to a truthy value.

let user = {id: 18, first_name: "Aidan" };
user &&= {...user, loggedIn: true };
console.log(user);
// {id: 18, first_name: "Aidan", loggedIn: true}

--

--