DEV Community

Cover image for My Favorite JavaScript Tips and Tricks
Tapas Adhikary
Tapas Adhikary

Posted on • Edited on • Originally published at blog.greenroots.info

My Favorite JavaScript Tips and Tricks

Motivation

Most of the programming languages are open enough to allow programmers to do things multiple ways for a similar outcome. JavaScript is in no way different. With JavaScript, we often find multiple ways of doing things for a similar outcome, and that's confusing at times.

Some of the usages are better than the other alternatives and thus, these are my favorites. I am going to list them here in this article. I am sure, you will find many of these on your list too.

1. Forget string concatenation, use template string(literal)

Concatenating strings together using the + operator to build a meaningful string is old school. Moreover, concatenating strings with dynamic values(or expressions) could lead to frustrations and bugs.

let name = 'Charlse';
let place = 'India';
let isPrime = bit => {
  return (bit === 'P' ? 'Prime' : 'Nom-Prime');
}

// string concatenation using + operator
let messageConcat = 'Mr. ' + name + ' is from ' + place + '. He is a' + ' ' + isPrime('P') + ' member.'
Enter fullscreen mode Exit fullscreen mode

Template literals(or Template strings) allow embedding expressions. It has got unique syntax where the string has to be enclosed by the backtick. Template string can contain placeholders for dynamic values. These are marked by the dollar sign and curly braces (${expression}).

Here is an example demonstrating it,

let name = 'Charlse';
let place = 'India';
let isPrime = bit => {
  return (bit === 'P' ? 'Prime' : 'Nom-Prime');
}

// using template string
let messageTemplateStr = `Mr. ${name} is from ${place}. He is a ${isPrime('P')} member.`
console.log(messageTemplateStr);
Enter fullscreen mode Exit fullscreen mode

2. isInteger

There is a much cleaner way to know if a value is an integer. The Number API of JavaScript provides a method called, isInteger() to serve this purpose. It is very useful and better to be aware.

let mynum = 123;
let mynumStr = "123";

console.log(`${mynum} is a number?`, Number.isInteger(mynum));
console.log(`${mynumStr} is a number?`, Number.isInteger(mynumStr));
Enter fullscreen mode Exit fullscreen mode

Output:

2.png

3. Value as Number

Have you ever noticed, event.target.value always returns a string type value even when the input box is of type number?

Yes, see the example below. We have a simple text box of type number. It means it accepts only numbers as input. It has an event handler to handle the key-up events.

<input type='number' onkeyup="trackChange(event)" />
Enter fullscreen mode Exit fullscreen mode

In the event handler method, we take out the value using event.target.value. But it returns a string type value. Now I will have an additional headache to parse it to an integer. What if the input box accepts floating numbers(like, 16.56)? parseFloat() then? Ah, all sorts of confusion and extra work!

function trackChange(event) {
   let value = event.target.value;
   console.log(`is ${value} a number?`, Number.isInteger(value));
}
Enter fullscreen mode Exit fullscreen mode

Use event.target.valueAsNumber instead. It returns the value as the number.

let valueAsNumber = event.target.valueAsNumber;
console.log(`is ${value} a number?`, Number.isInteger(valueAsNumber));
Enter fullscreen mode Exit fullscreen mode

3.png

4. Shorthand with AND

Let's consider a situation where we have a boolean value and a function.

let isPrime = true;
const startWatching = () => {
    console.log('Started Watching!');
}
Enter fullscreen mode Exit fullscreen mode

This is too much code to check for the boolean condition and invoke the function,

if (isPrime) {
    startWatching();
}
Enter fullscreen mode Exit fullscreen mode

How about using the short-hand using the AND(&&) operator? Yes, avoid the if statement altogether. Cool, right?

isPrime && startWatching();
Enter fullscreen mode Exit fullscreen mode

5. The default value with || or ??

If you ever like to set a default value for a variable, you can do it using the OR(||) operator easily.

let person = {name: 'Jack'};
let age = person.age || 35; // sets the value 35 if age is undefined
console.log(`Age of ${person.name} is ${age}`);
Enter fullscreen mode Exit fullscreen mode

But wait, it has a problem. What if the person's age is 0(a just born baby, maybe). The age will be computed as 35 (0 || 35 = 35). This is unexpected behavior.

Enter the nullish coalescing operator (??). It is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

To rewrite the above code with the ?? operator,

let person = {name: 'Jack'};
let age = person.age ?? 35; // sets the value 0 if age 0, 35 in case of undefined and null
console.log(`Age of ${person.name} is ${age}`);
Enter fullscreen mode Exit fullscreen mode

6. Randoms

Generating a random number or getting a random item from an array is a very useful method to keep handy. I have seen them appearing multiple times in many of my projects.

Get a random item from an array,

let planets = ['Mercury ', 'Mars', 'Venus', 'Earth', 'Neptune', 'Uranus', 'Saturn', 'Jupiter'];
let randomPlanet = planets[Math.floor(Math.random() * planets.length)];
console.log('Random Planet', randomPlanet);
Enter fullscreen mode Exit fullscreen mode

Generate a random number from a range by specifying the min and max values,

 let getRandom = (min, max) => {
     return Math.round(Math.random() * (max - min) + min);
 }
 console.log('Get random', getRandom(0, 10));
Enter fullscreen mode Exit fullscreen mode

7. Function default params

In JavaScript, function arguments(or params) are like local variables to that function. You may or may not pass values for those while invoking the function. If you do not pass a value for a param, it will be undefined and may cause some unwanted side effects.

There is a simple way to pass a default value to the function parameters while defining them. Here is an example where we are passing the default value Hello to the parameter message of the greetings function.

let greetings = (name, message='Hello,') => {
    return `${message} ${name}`;
}

console.log(greetings('Jack'));
console.log(greetings('Jack', 'Hola!'));
Enter fullscreen mode Exit fullscreen mode

8. Required Function Params

Expanding on the default parameter technique, we can mark a parameter as mandatory. First, define a function to throw an error with an error message,

let isRequired = () => {
    throw new Error('This is a mandatory parameter.');
}
Enter fullscreen mode Exit fullscreen mode

Then assign the function as the default value for the required parameters. Remember, the default values are ignored when a value is passed is as a parameter at the invocation time. But, the default value is considered if the parameter value is undefined.

let greetings = (name=isRequired(), message='Hello,') => {
    return `${message} ${name}`;
}
console.log(greetings());
Enter fullscreen mode Exit fullscreen mode

In the above code, name will be undefined and that will try to set the default value for it which is the isRequired() function. It will throw an error as,

8.png

9. Comma Operator

I was surprised when I realized, comma(,) is a separate operator and never gone noticed. I have been using it so much in code but, never realized its true existence.

In JavaScript, the comma(,) operator is used for evaluating each of its operands from left to right and returns the value of the last operand.

let count = 1;
let ret = (count++, count);
console.log(ret);
Enter fullscreen mode Exit fullscreen mode

In the above example, the value of the variable ret will be, 2. Similar way, the output of the following code will be logging the value 32 into the console.

let val = (12, 32);
console.log(val);
Enter fullscreen mode Exit fullscreen mode

Where do we use it? Any guesses? The most common usage of the comma(,) operator is to supply multiple parameters in a for a loop.

for (var i = 0, j = 50; i <= 50; i++, j--)
Enter fullscreen mode Exit fullscreen mode

10. Merging multiple objects

You may have a need to merge two objects together and create a better informative object to work with. You can use the spread operator ...(yes, three dots!).

Consider two objects, emp and job respectively,

let emp = {
 'id': 'E_01',
 'name': 'Jack',
 'age': 32,
 'addr': 'India'
};

let job = {
 'title': 'Software Dev',
  'location': 'Paris'
};
Enter fullscreen mode Exit fullscreen mode

Merge them using the spread operator as,

 // spread operator
 let merged = {...emp, ...job};
 console.log('Spread merged', merged);
Enter fullscreen mode Exit fullscreen mode

There is another way to perform this merge. Using Object.assign(). You can do it like,

 console.log('Object assign', Object.assign({}, emp, job));
Enter fullscreen mode Exit fullscreen mode

Output:

10.png

Note, both the spread operator and the Object.assign perform a shallow merge. In a shallow merge, the properties of the first object are overwritten with the same property values as the second object.

For deep merge, please use something like, _merge of lodash.

11. Destructuring

The technique of breaking down the array elements and object properties as variables called, destructuring. Let us see it with few examples,

Array

Here we have an array of emojis,

let emojis = ['πŸ”₯', '⏲️', 'πŸ†', 'πŸ‰'];
Enter fullscreen mode Exit fullscreen mode

To destructure, we would use the syntax as follows,

let [fire, clock, , watermelon] = emojis;
Enter fullscreen mode Exit fullscreen mode

This is the same as doing, let fire = emojis[0]; but with lots more flexibility.
Have you noticed, I have just ignored the trophy emoji using an empty space in-between? So what will be the output of this?

console.log(fire, clock, watermelon);
Enter fullscreen mode Exit fullscreen mode

Output:

11.png

Let me also introduce something called the rest operator here. If you want to destructure an array such that, you want to assign one or more items to variables and park the rest of it into another array, you can do that using ...rest as shown below.

let [fruit, ...rest] = emojis;
console.log(rest);
Enter fullscreen mode Exit fullscreen mode

Output:

11.a.png

Object

Like arrays, we can also destructure objects.

let shape = {
  name: 'rect',
  sides: 4,
  height: 300,
  width: 500
};
Enter fullscreen mode Exit fullscreen mode

Destructuring such that, we get a name, sides in a couple of variables and rest are in another object.

let {name, sides, ...restObj} = shape;
console.log(name, sides);
console.log(restObj);
Enter fullscreen mode Exit fullscreen mode

Output:

11.b.png

Read more about this topic from here.

12. Swap variables

This must be super easy now using the concept of destructuring we learned just now.

let fire = 'πŸ”₯';
let fruit = 'πŸ‰';

[fruit, fire] = [fire, fruit];
console.log(fire, fruit);
Enter fullscreen mode Exit fullscreen mode

13. isArray

Another useful method for determining if the input is an Array or not.

let emojis = ['πŸ”₯', '⏲️', 'πŸ†', 'πŸ‰'];
console.log(Array.isArray(emojis));

let obj = {};
console.log(Array.isArray(obj));
Enter fullscreen mode Exit fullscreen mode

14. undefined vs null

undefined is where a value is not defined for a variable but, the variable has been declared.

null itself is an empty and non-existent value that must be assigned to a variable explicitly.

undefined and null are not strictly equal,

undefined === null // false
Enter fullscreen mode Exit fullscreen mode

Read more about this topic from here.

15. Get Query Params

window.location object has a bunch of utility methods and properties. We can get information about the protocol, host, port, domain, etc from the browser URLs using these properties and methods.

One of the properties that I found very useful is,

window.location.search
Enter fullscreen mode Exit fullscreen mode

The search property returns the query string from the location URL. Here is an example URL: https://tapasadhiary.com?project=js. The location.search will return, ?project=js

We can use another useful interface called, URLSearchParams along with location.search to get the value of the query parameters.

let project = new URLSearchParams(location.search).get('project');
Enter fullscreen mode Exit fullscreen mode

Output:
js

Read more about this topic from here.

This is not the end

This is not the end of the list. There are many many more. I have decided to push those to the git repo as mini examples as and when I encounter them.

GitHub logo atapas / js-tips-tricks

List of JavaScript tips and tricks I am learning everyday!

What are your favorite JavaScript tips and tricks? How about you let us know about your favorites in the comment below?


If it was useful to you, please Like/Share so that, it reaches others as well. I am passionate about UI/UX and love sharing my knowledge through articles. Please visit my blog to know more.

You may also like,

Feel free to DM me on Twitter @tapasadhikary or follow.

Top comments (22)

Collapse
 
juliobetta profile image
Julio Betta

hey, awesome article. just a small correction

let age = person.age ?? 35; // sets the value 35 if age is undefined, 0, null, '' etc

because of the null coalescing, if person.age === 0, the variable age is 0.

const person = {
  name: 'Adhikary',
  age: 0
};

const age1 = person.age ?? 35; // => 0
const age2 = person.age || 35; // => 35
Collapse
 
atapas profile image
Tapas Adhikary

Big thank for helping me to correct the typo.

Collapse
 
elliot profile image
Elliot

Hadn't seen the isRequired idea before! Clever list :)

Collapse
 
atapas profile image
Tapas Adhikary

Thanks Elliot!

Collapse
 
hnicolas profile image
Nicolas HervΓ©

Number.isInteger method was designed to be used with numbers in order to test if it is an integer or not (NaN, Infinity, float...).

Number.isInteger(12) // true
Number.isInteger(12.0) // true
Number.isInteger(12.5) // false

developer.mozilla.org/en-US/docs/W...
Using typeof mynum === "number" is a better solution to test if a value is a number.

typeof mynum // number
typeof mynumStr // string
Collapse
 
jankapunkt profile image
Jan KΓΌster • Edited

Note, that the Number rounding of floats in JavaScript is not accurate

(0.1 + 0.2) === 0.3 // false

Since this rounding affects integer representation, too, you should also consider Number.isSafeInteger

developer.mozilla.org/en-US/docs/W...

Also please consider Integer boundaries in JS, that are represented by Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER

developer.mozilla.org/en-US/docs/W...

developer.mozilla.org/en-US/docs/W...

Edit: sry wanted to post on top level, somehow ended up as comment on yours

Collapse
 
atapas profile image
Tapas Adhikary

Awesome, thanks Jan!

Collapse
 
ocalde profile image
Oscar Calderon

I thought I would know everything in this list, but learned something new!!! Didn't know about the nullish coalescing operator, pretty useful! Thank you Tapas

Collapse
 
atapas profile image
Tapas Adhikary

Thanks, Oscar!

Collapse
 
marcellothearcane profile image
marcellothearcane

It's quite new, so it won't work everywhere yet.

Collapse
 
rajmohanpdy profile image
rajmohan s

?? operator not working for me. shows as below
SyntaxError: Unexpected token '?'

Collapse
 
atapas profile image
Tapas Adhikary

Which browser are you using? It should work.

let person = {name: 'Jack'};
let age = person.age ?? 35; // sets the value 0 if age 0, 35 in case of undefined and null
console.log(`Age of ${person.name} is ${age}`);
Enter fullscreen mode Exit fullscreen mode

Output, Age of Jack is 35

Also, check if there is a syntax error. You can paste the code as a comment.

Collapse
 
klvenky profile image
Venkatesh KL

Points 3,8,9 blew my mind away. Especially the user of a function to throw errors πŸ™πŸ‘πŸ‘

Collapse
 
atapas profile image
Tapas Adhikary

Great.. Thanks, Venkatesh!

Collapse
 
sakar_dhana profile image
Sakar

Really nice tricks to know. Nice work keep this good work going...
Good health

Collapse
 
atapas profile image
Tapas Adhikary

Thanks Sakar for the encouragements!

Collapse
 
olsard profile image
olsard

Awesome, thanks for sharing!

Collapse
 
atapas profile image
Tapas Adhikary

Thanks for reading and commenting!

Collapse
 
fahad07_khan profile image
Fahad Khan

Good tricks shared in this article I learnt some new also

Collapse
 
atapas profile image
Tapas Adhikary

Thanks Fahad!

Collapse
 
kingleo10 profile image
Niroj Dahal

I have used window.location.hash in pages where tab content need to be loaded initially based on url hash. I find this pretty useful

Collapse
 
atapas profile image
Tapas Adhikary

Cool, thanks for sharing Niroj!