Categories
JavaScript Tips

Useful JavaScript Tips — Arrays, and Variables

Spread the love

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.

Assignment Operators

We can save some typing by using some compound assignment operators.

We can use the ++ and -- operators to increment and decrement by one respectively.

For instance, we can write:

a++

to increment a by 1.

Likewise, we can use:

++a

to do the same thing.

The only difference is whether it returns the later value or the old one.

We can do the same thing with -- , but decrements the value instead.

Ternary Operator

If we have:

const newValue;
if(value > 100) {
  newValue = 5;
} else {
  newValue = 2;
}

Then we can shorten it by writing:

const newValue = (`value > 100) ? 5 : 2;`

They do the same thing.

Null, Undefined, or Empty Checks

We can check for null , undefined and an empty string together by writing the following:

if (foo !== null || foo !== undefined || foo !== '') {
  const bar = foo;
}

We have to check null , undefined and empty string individually.

This is because empty string, null and undefined are different.

If we want to check other falsy values like 0 or NaN , then we can shorten it to:

const bar = foo || 'default';

Then when foo is any falsy value, then 'default' will be assigned to bar .

Array Literals

Instead of using the Array constructor:

const a = new Array();
a[0] = 'foo';
a[1] = 'bar';

We can write an array literal as follows:

const a = ['foo', 'bar'];

They do the same thing, but the array literal notation is much shorter.

Associative Array

We shouldn’t use the Array constructor for creating associative arrays.

Rather, we should create an object with dynamic keys.

For instance, we can write:

const skills = {
  'markup language' : 'HTML5',
  'programming language' : 'JavaScript'
};

We have 2 keys which aren’t valid identifiers.

But we can still use them since JavaScript objects can take string property names.

Asynchronous Loops

If we want to loop through setTimeout calls, then we can use let as follows:

for (let i = 0; i < 10; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}

let is block-scoped, so the current value of i would be passed in.

Create an Array Sequence

We can create an array with a sequence of numbers starting from 0 with the Array constructor, fill , and map .

For instance, we can write:

const arr = Array(50).fill().map((_, i) => i);

We used the Array constructor to create an array with empty slots.

Then we called fill to fill the empty array with undefined .

This way, we can use map to map the entries by passing in a callback and return the index i of each entry.

Then we get an array between 0 and 50.

Ordering Object Properties

We can use the Object.keys method to return properties in an array.

Arrays are sortable so we can use that.

For instance, we can write:

Object.keys(obj)

and get the keys.

Also, we can use the Map constructor to create a map, which is traversed in insertion order.

For instance, we can write:

const map = new Map();
map.set('foo', 1);
map.set('@', 2);
map.set('bar', 3);
for (const [key, value] of map) {
  console.log(key, value);
}

Now we have Map instance that we can loop through keys in the same order that they’re inserted.

Avoiding Using Arguments

Don’t use the arguments object to get all the arguments.

Instead, we use the rest operator to get function arguments as an array.

For instance, we can write:

const foo = (...args) => {
  `for(const a of args) {
    //...
  }
}`

The ... is the rest operator which collects all the arguments in a function call and returns it as an array.

We can then call it by writing:

foo(1, 2, 3);

and args would be [1, 2, 3] .

Conclusion

We can use the rest operator to get the arguments from a function call.

The assignment operators are great. We can use the ++ and -- operators to increment and decrement our variables.

Also, we should use array literals as much as we can.

One reply on “Useful JavaScript Tips — Arrays, and Variables”

Leave a Reply

Your email address will not be published. Required fields are marked *