• My Favorite JavaScript Tips and Tricks
  • Originally written by Tapas Adhikary
  • Translation from: The Gold Project
  • This article is permalink: github.com/xitu/gold-m…
  • Translator: zenblo
  • Proofreader: tanglie1993 and Chorer

Share 15 JavaScript development tips

The purpose of this article

Most programming languages are open enough to allow programmers to get similar results in many ways. The same is true of JavaScript, with which we can often achieve similar results in a variety of ways, though sometimes confusing.

Some of them are better than others, and those are the ones I want to share. I’ll list them all in this article, and I’m sure as you read this, you’ll find that in many ways you and I do the same thing.

1. Use a template string

Using the + operator to concatenate strings to build meaningful strings is an outdated practice. In addition, concatenating a string with a dynamic value (or expression) can result in evaluation or expression errors.

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

String concatenation using the '+' operator
let messageConcat = 'Mr. ' + name + ' is from ' + place + '. He is a' + ' ' + isPrime('P') + ' member.'
Copy the code

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

Here’s an example to demonstrate it,

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

// Use the template string
let messageTemplateStr = `Mr. ${name} is from ${place}. He is a ${isPrime('P')} member.`
console.log(messageTemplateStr);
Copy the code

2. isInteger

There is a more concise way to find out if the value is an integer. JavaScript’s Number API provides a method called isInteger() to do this. This is very useful and it is best to know about it.

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

console.log(`${mynum}is a number? `.Number.isInteger(mynum));
console.log(`${mynumStr}is a number? `.Number.isInteger(mynumStr));
Copy the code

Output results:

3. The value is a number

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

See the following example. We have a simple numeric text box. This means that it only accepts numbers as input, and it has event handlers to handle key events.

<input type='number' onkeyup="trackChange(event)" />
Copy the code

In the event handler, we use event.target.value to fetch the value, but it returns a string value. Now, I’ll have to parse it to integers. What if the input box accepts a floating point number, such as 16.56? ParseFloat () and then what? Ah, I have to face all kinds of confusion and extra work!

function trackChange(event) {
   let value = event.target.value;
   console.log(`is ${value}a number? `.Number.isInteger(value));
}
Copy the code

Please switch to the event. Target. ValueAsNumber, it returns a value in digital form.

let valueAsNumber = event.target.valueAsNumber;
console.log(`is ${value}a number? `.Number.isInteger(valueAsNumber));
Copy the code

4. Use the && operator to simplify the expression

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

let isPrime = true;
const startWatching = () = > {
    console.log('Started Watching! ');
}
Copy the code

It’s too much code to determine whether a function is called by checking a Boolean value like this.

if (isPrime) {
    startWatching();
}
Copy the code

Can I use the shorthand form with the AND (&&) operator? Yes, you can completely avoid using if statements. Cool!!!!

isPrime && startWatching();
Copy the code

5. Use the | | operator handling the default values

If you want to set default values for variables, you can use the OR (| |) operators easily.

let person = {name: 'Jack'};
let age = person.age || 35; // If age is not defined, set the value to 35
console.log(`Age of ${person.name} is ${age}`);
Copy the code

6. Obtain random items

Generating random numbers or getting random items from an array is a very useful and convenient method. I’ve seen them many 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);
Copy the code

Generate a random number in a range by specifying a minimum and a maximum,

let getRandom = (min, max) = > {
    return Math.round(Math.random() * (max - min) + min);
}
console.log('Get random', getRandom(0.10));
Copy the code

7. Default function arguments

In JavaScript, function arguments (or parameters) act like local variables to the function. When you call a function, you may or may not pass a value. If you do not pass a value for an argument, the value will be undefined and may cause some unwanted side effects.

There is a simple way to pass default values to function arguments when you define them. In the following example, we pass the default value Hello to the message parameter to the Greetings function.

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

console.log(greetings('Jack'));
console.log(greetings('Jack'.'Hola! '));

Copy the code

8. Required function arguments

Based on the nature of the default parameters, we can make the parameters required. First define a function to throw an error using an error message,

let isRequired = () = > {
    throw new Error('This is a mandatory parameter.');
}
Copy the code

Then take the functions as the default values for the required arguments. Remember that if you pass values for arguments when you call a function, the default values are ignored. However, if the parameter value is “undefined”, the default value is used.

let greetings = (name=isRequired(), message='Hello,') = > {
    return `${message} ${name}`;
}
console.log(greetings());
Copy the code

In the above code, the name will be undefined, so you will try to use the default, which is the isRequired() function. It will raise an error like this:

9. Comma operator

I was surprised to realize that the comma (,) is a single operator that I had never noticed before. I’ve used a lot of commas in my code, but have never been aware of their other uses.

The operator evaluates each of its operands from left to right and returns the value of the last one.

let count = 1;
let ret = (count++, count);
console.log(ret);
Copy the code

In the example above, the variable ret will have a value of 2. Similarly, the following code records the value 32 in the console output.

let val = (12.32);
console.log(val);
Copy the code

Where do we use it? Any ideas? The most common use of the comma (,) operator is to provide multiple arguments in a for loop.

for (var i = 0, j = 50; i <= 50; i++, j--)
Copy the code

10. Merge objects

You may need to merge the two objects together and create a better, richer object to use. To do this, you can use the extension operator… (Yes, three points!) .

Consider the emP and job objects separately,

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

let job = {
 'title': 'Software Dev'.'location': 'Paris'
};
Copy the code

Use the extension operator to merge them into

// spread operator
letmerged = {... emp, ... job};console.log('Spread merged', merged);
Copy the code

There is another way to implement merges. You can use object.assign () as follows:

console.log('Object assign'.Object.assign({}, emp, job));
Copy the code

Output results:

Note that both the extension operator and object.assign perform shallow merges. In a shallow merge, the property of the first object is overwritten by the same property value of the second object.

For deep merges, consider using _merge in lodash.

11. Deconstruction

The technique of splitting array elements and object attributes into variables is called “deconstruction.” Let’s look at a few examples,

An array of

Here, we have a series of emojis,

let emojis = ['🔥'.'⏲ ️'.'🏆'.'🍉'];
Copy the code

To deconstruct, we’ll use the following syntax,

let [fire, clock, , watermelon] = emojis;
Copy the code

Let fire = emojis [0]; Same, but with more flexibility. Did you notice that I just used a space in the place of the trophy emoji and ignored it? So, what will this output?

console.log(fire, clock, watermelon);
Copy the code

Output results:

Let me introduce one more thing here called the “REST” operator. If you want to deconstruct an array to assign one or more items to variables and temporarily put the rest in another array, you can use… Rest, as shown below.

let [fruit, ...rest] = emojis;
console.log(rest);
Copy the code

Output results:

object

Like arrays, we can deconstruct objects.

let shape = {
  name: 'rect'.sides: 4.height: 300.width: 500
};
Copy the code

To do this, we can assign the object’s name and sides properties to two variables, and store the rest of the properties in another object.

let{name, sides, ... restObj} = shape;console.log(name, sides);
console.log(restObj);
Copy the code

Output results:

Read more about this topic from here.

12. Swap variables

Now, using the deconstruction we just learned, swapping variables will become very easy.

let fire = '🔥';
let fruit = '🍉';

[fruit, fire] = [fire, fruit];
console.log(fire, fruit);
Copy the code

13. isArray

Another useful way to determine whether the input is an array.

let emojis = ['🔥'.'⏲ ️'.'🏆'.'🍉'];
console.log(Array.isArray(emojis));

let obj = {};
console.log(Array.isArray(obj));
Copy the code

14. Undefined and null

Undefined refers to a variable that has not yet been defined but has been declared.

Null itself is an empty, nonexistent value that must be explicitly assigned to a variable.

Undefined and null are not strictly equal,

undefined= = =null // false
Copy the code

Read more about this topic from here.

15. Obtain the query parameters

The window.location object has a number of utility methods and properties. Using these properties and methods, we can get information about protocols, hosts, ports, domains, and so on from the browser URL.

Here’s one property I found very useful:

window.location.search
Copy the code

The search attribute returns a query string from the location URL. Take this url as an example: https://tapasadhiary.com? Project = js. Location.search will return? project = js

We can use another useful interface called URLSearchParams and location.search to get the value of the query parameter.

let project = new URLSearchParams(location.search).get('project');
Copy the code

The output is js

Read more about this topic from here.

This article is not over

JavaScript programming tips are much more than that, and I plan to update my GitHub project with new tips as examples as I learn them github.com/atapas/js-t…

If you find any errors in the translation or other areas that need improvement, you are welcome to revise and PR the translation in the Gold Translation program, and you can also get corresponding bonus points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


Diggings translation project is a community for translating quality Internet technical articles from diggings English sharing articles. The content covers the fields of Android, iOS, front end, back end, blockchain, products, design, artificial intelligence and so on. For more high-quality translations, please keep paying attention to The Translation Project, official weibo and zhihu column.