Top 10 Javascript tips

Swapping two variables

Using what we learned in the last trick makes swapping variables as easy as:

let me = 'happy', you = 'sad';
[me, you] = [you, me];
// me = 'sad', you = 'happy'

The above code creates an array of [you, me] and immediately destructures them into the opposite variables. No need for temp variables anymore!

Named Callback Functions

Anonymous functions can be really useful - they can be declared when and where you want, and are great if you only need the function as a one-off.

let people = [
  {
    id: 1,
    firstName: 'Sam',
    lastName: 'Walpole',
  },
  ...
];

let viewModels = people.map(p => ({
  id: p.id,
  name: `${p.firstName} ${p.lastName}`,
}));
// viewModels = [{ id: 1, name: 'Sam Walpole' }]

However, since the function has no name, you are leaving it up to future developers to work out what the code inside your callback function does - that's ok here, but in a longer, more complex functions it may waste unnecessary time. By declaring the function first as a named function, you instantly make the code more readable and give future developers some clues as to the intent of the function.

let people = [
  {
    id: 1,
    firstName: 'Sam',
    lastName: 'Walpole',
  },
  ...
];

let toViewModel = p => ({
  id: p.id,
  name: `${p.firstName} ${p.lastName}`,
});

let viewModels = people.map(toViewModel);
// viewModels = [{ id: 1, name: 'Sam Walpole' }]

If you access a DOM item several times, save it in a local variable

Accessing the DOM is slow. If you are going to read the content of an element several times, it's better to save it in a local variable. But it’s important to keep in mind, if you will later remove the value of the DOM, the variable should be set to "null", so it doesn’t cause any memory leaks.

Merge Objects

The need to merge multiple objects in JavaScript has been around forever,  especially as we started creating classes and widgets with options: const person = { name: ‘David Walsh’, gender: ‘Male’ }; const tools = { computer: ‘Mac’, editor: ‘Atom’ };const attributes = { handsomeness: ‘Extreme’, hair: ‘Brown’, eyes: ‘Blue’ };const summary = {…person, …tools, …attributes}; /* Object { “computer”: “Mac”, “editor”: “Atom”,  “eyes”: “Blue”, “gender”: “Male”, “hair”: “Brown”, “handsomeness”: “Extreme”, “name”: “David Walsh”, } */

Setting defaults

We have all seen them. The endless if statements checking if the values have been set. What if I said there was a better way? Well, that's exactly what I'm saying, default values.

The Smoothest Quick Float to Integer Conversion Method

This type of conversion is an operational or type conversion. To convert a float all you need to do is to apply Math.floor() , Math.ceil() or Math.round(). Since we are here to make your life easier though, it’s fastest to do this using the bitwise OR operator “|”. Here’s how it’s done: {% code-block language="js" %}   console.log("24.9 | 0: ", 24.9 | 0);//24   console.log("-24.9 | 0: ", -24.9 | 0);//24{% code-block-end %} Keep in mind that the behavior of your bitwise OR operator “|” may differ from your expectations. It may differ based on positive or negative numbers. Thus, you will want to be sure about them before using the bitwise OR operator in JavaScript. When using the bitwise OR operator, if your n is positive, n | 0  rounds down. The opposite will happen if n is negative, resulting in rounding up. You can also use Tildes “~~”  for the same purpose of rounding. This operation also removes large numbers of digits from the end of an integer. This makes your life easier as you can convert your integers as shown below: {% code-block language="js" %}console.log("27433/100 | 0: ", 27433/100 | 0);//274{% code-block-end %}

Type Conversion: Number and String

One of the most common things you find yourself doing in JavaScript is using arithmetic operators: +, -, *, /. These operators expect operands that are numbers. So when any of the operands is not a number, JavaScript implicitly coerces it into a number. But there are times when you may not get the result you may be expecting, especially when you are using the + operator. This is majorly because the + operator is also used for string concatenation. See the following snippet: As you can see, implicit type coercion may not always give you the result you are expecting. This is because of how JavaScript handles type conversion especially for objects. The difference is due to the order in which JavaScript calls the toString() and valueOf() methods on the object for object-to-primitive conversion. Now here is the trick. The + operator when used as a unary operator always converts its operand to a number. Hence, the following: Using the unary + operator on a value is functionally equivalent to casting the value using the Number() function.

+new Date === Number(new Date); // true

The + operator can also be used to convert values to string. Concatenate an empty string('') to any value using the + operator to convert the value to a string. Using the + operator to convert values to string is functionally equivalent to casting values to string using the String() function.

([100, 50] + '') === String([100, 50]); // true

Make Use Of Different Types Of Resources

When you are learning something as difficult as programming, it is a good idea to make use of as many different resources as you can. Some of the best resources for people learning how to code with JavaScript include:

  • Online videos - If you are looking for a more in-depth explanation of a difficult concept or of something that you can't quite get your head around, head over to YouTube. You will almost certainly find a video that clearly explains things, allowing you to gain a deeper understanding of the concept in question.
  • Reference guides - As noted above, reference guides are essential when it comes to learning and using any programming language.
  • Other people - There are hundreds of high-quality, active coding forums and chat rooms on the internet. You would be stupid not to take your questions to them, as you will almost certainly find someone who can help you with anything you're struggling with.
  • Online courses - If you aren't already enrolled in a free or low-cost online coding course, then now is your chance! Head over and explore some of the courses on the BitDegree platform and learn JavaScript in no-time. It can be very difficult to start learning a programming language like JavaScript. However, things will be a lot simpler if you make use of the full range of resources available to you.

Multiple conditions in an if statement

If you have to deal with checking a large number of conditions, you can use includes.if([“invoice”, “payment”, “pending”].includes(status)) { }

Short-Circuiting

When working with the (|| and &&) logical operators, you may have noticed an interesting behavior called short-circuiting. Here is how it works: The logical && operator returns the first operand if it is falsy, otherwise it returns the second operand. The logical && short-circuiting is commonly used as a replacement for very simple if statements as shown in the following snippet: Note that using short-circuiting actually returns a value since it is a JavaScript expression. Hence, the result of a short-circuiting operation can be stored in a variable or used anywhere JavaScript expects a value.

var personProfile = person && fetchProfile(person);

However, using if statement does not return a value because it is a JavaScript statement. The logical || operator returns the first operand if it is truthy, otherwise it returns the second operand. The logical || short-circuiting is commonly used when assigning fallback values to local variables as shown in the following snippet: In the following snippet, short-circuiting is used to create two functions that always return a boolean value. If the first argument is a boolean value, it is returned, otherwise the desired fallback boolean value is returned.

;