Useful JavaScript Tips — Properties and Arrays
By: John Au-Yeung
Tags: JavaScript, Web Development, Software Development, Technology, Programming

Photo by Srecko Skrobic on Unsplash

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Check if a property is in an Object

There are a few ways that we can use to check if a property is in an object.

For instance, we can use the hasOwnProperty method as follows:

obj.hasOwnProperty('name');

hasOwnProperty is a method of an object that’s inherited from Object.prototype .

It returns true if 'name' is a non-inherited property of an object/

Also, we can use the in operator to check if a property is part of the object, including in prototypes.

For instance, if we write:

'valueOf' in obj;

Then it would return true since valueOf is inherited from the obj ‘s prototype.

Template Strings

Template strings are great form combing various expressions into a string.

Instead of concatenation, we can use template strings.

For instance, instead of writing:

const firstName = 'jane';

const lastName = 'smith';

const name = firstName + ' ' + lastName;

We can write:

const firstName = 'jane';

const lastName = 'smith';

const name = `${firstName} ${lastName}`;

It’s shorter and there are no plus signs.

Converting a Node List to an Array

We can use the spread operator to convert a node list to an array.

For instance, we can write:

const nodeList = document.querySelectorAll('div');

const nodeArr = [...nodeList];

We can do this because a node list is an array-like iterable object, which means that it can be converted with the spread operator to an array.

Now we can use any array methods on a node list, making our lives much easier.

Write a Method that Works with Both Arrays and a Single Value

We can write a method that works with both arrays and a single value by checking if it’s an array.

For instance, we can write:

const foo = (val) => {

if (Array.isArray(val)){

//...

}

else {

//...

}

}

We used the Array.isArray method to check if val is an array.

Then we can have a function that works with both arrays and a single value.

Hoisting

We should be aware of the hoisting of function declarations.

Hoisting means that the value is pulled to the top of the file.

Function declarations are hoisted.

So if we have:

function foo(){

//...

}

Then it can be called anywhere in the file.

Sorting Strings with Accented Characters

To sort strings with accented characters, we can use the localeCompare method to order them properly.

For instance, we can write:

[' marrón ', 'árbol', ' dulce ', 'fútbol'].sort((a, b) => a.localeCompare(b));

Then we can sort them without hassle.

We get:

["árbol", "dulce", "fútbol", "marrón"]

which is what we expect.

Likewise, we can use the Intl.Collator method as follows to do the same thing:

[' marrón ', 'árbol', ' dulce ', 'fútbol'].sort(Intl.Collator().compare);

It takes 2 arguments with the strings to compare and return the same thing as localeCompare , so we can pass the function straight in.

It’s faster than localeCompare when comparing a large number of strings.

Therefore, when we compare non-English strings, we should use these 2 functions to compare them.

Improving Nested Conditionals

We can eliminate nested conditionals by using the switch statement.

For instance, instead of writing:

if (color) {

if (color === 'black') {

doBlack();

} else if (color === 'red') {

doRed();

} else if (color === 'blue') {

doBlue();

} else {

doSomething();

}

}

We can use the switch statement instead:

switch(color) {

case 'black':

doBlack();

break;

case 'red':

doRed();

break;

case 'blue':

doBlue();

break;

default:

doSomething();

}

It’s shorter and we don’t need to check whether color is falsy before doing the other checks.

This is because the default clause takes care of the falsy check.

Add Item Inside an Array

We can add an item by using the concat method.

For instance, we can write:

const arr = [1,2,3];

const four = arr.concat(4);

concat returns the array with the new item appended to it.

So we get [1, 2, 3, 4] for four .

We can use push to add an item to an array in place.

For instance, we can write:

const arr = [1,2,3];

arr.push(4);

arr is now [1, 2, 3, 4] .

Photo by Krisztina Papp on Unsplash

Conclusion

We can use concat or push to add items to an array.

Also, we can use in or hasOwnProperty to check if a property is in an object.

If we sort string arrays with strings that have accents, then we need to use localeCompare or Intl.Collator().compare .

JavaScript In Plain English

Did you know that we have four publications and a YouTube channel? Find them all at plainenglish.io and subscribe to our YouTube channel!