In fact, most programming languages are open enough to allow programmers to program in multiple ways to achieve similar results. The same goes for JavaScript. When using JavaScript, we often find many ways to get similar results, but sometimes confusion can occur.

Some of these uses are better than others, so these are my favorites and I’ll list them in this article. I’m sure you’ll find them in your own list, too.

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

In general, when building a meaningful string, we use the + operator to concatenate strings together. However, concatenating strings with dynamic values (or expressions) can result in some error conditions.

Template literals (or template strings) allow expressions to be embedded. It has the unique syntax that strings must be enclosed in backquotes (‘ ‘). Template strings can contain placeholders for dynamic values. These can be marked with dollar signs and braces (${expression}).

Let’s do a demonstration this way:

2. Want to know whether the value is an integer? Here’s a clearer way to do it.

JavaScript’s NumberAPI provides a method called isInteger() to know if a value is an integer. This is very useful and much easier to notice.

The output is as follows:

Value as a number

Have you ever noticed that event.target.value always returns a string value even if it is typed as a number?

Yes, look at the following example. We have a simple numeric type text box. This means that it only accepts numeric inputs. It has event handlers to handle keystroke events.

In the event handler method, we use event.target.value to fetch values. But it returns a string value. Now I’m going to have to parse it to an integer, which is a little tricky. What if the input box accepts a floating point number, such as 16.56? ParseFloat () and then what? There will be extra work and all sorts of confusing things going on!

Use event. Target. ValueAsNumber instead. It returns the value as a number.

4. The AND shorthand

Let’s consider a case with Boolean values and functions.

There’s too much code here to check Boolean conditions and call this function,

So what about trying to use shorthand with the AND (&&) operator? Yes, avoiding the full statement of if. Cool!!!!

5. With the default value of OR

You can use the OR (| |) operator, easy set default values for variables.

But wait, there’s a problem. What if the person’s age is 0 (probably a newborn baby). Age will be calculated for 35 (0 | | 35 = 35), this belongs to the operation of unexpected behavior.

At this time, enter nullishcoalescing operator(??). . It is a logical operator that returns its right-hand operand if its left-hand operand is null or undefined, otherwise returns its left-hand operand.

You want to use?? The operator overrides the above code,