Top 10 Javascript tips

Values: truthy and falsy

Most new JavaScript developers may be aware of the built-in data types in JavaScript. However, not so many may know about JavaScript’s classification of truthy and falsy values. Anytime JavaScript expects a boolean value, a truthy value will behave like true, whereas a falsy value works like false. These are the falsy values:

  • 0
  • -0
  • null
  • undefined
  • ''
  • NaN
  • false As you can see, even an empty string is considered a falsy value. All other values besides the above mentioned are truthy values. The ! operator can be used to convert any value to a boolean. When using the ! operator with values, truthy values evaluate to false, while falsy values evaluate to true. You can use the double (!!) operator to get the corresponding boolean for any value. Let’s say a variable person can either contain an object or null. You can verify that the person variable is not null, by using the following condition:
if (person !== null) { ... }

Considering that null is falsy while every other object is truthy, you can use this (less strict condition):

if (person) { ... }

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);

Use pointer references

You can also cut down on DOM traversal trips by storing pointer references for in-browser objects during instantiation. If you don't expect your DOM to change, storing a reference to the DOM or jQuery objects needed to create your page can help speed everything along. Alternatively, if you need to iterate inside a function, but you haven't stored a reference, you can make a local variable with a reference to the object.

Managing objects

Destructuring is a huge part of ES6 and something you're probably going to be using often. It allows us to extract data from objects, and assigning the extracted data into variables:

const rectangle = { h: 100, w: 200 };
const { h, w } = rectangle;

We can rename the variables if we want to:

const { h: height, w: width} = rectangle;
console.log(height); // 100

Another handy thing we could do is to destructure the returned object by a function and pick and choose what values we want to use:

function getPerson() {
  return {
    firstName: 'Max',
    lastName: 'Best',
    age: 42
  }
}

const { age } = getPerson();
console.log(age); // 42

So, with destructuring, we can return multiple values from a function by returning an object and choosing the pieces we want to be returned. Removing a property in an immutable way requires a little trick provided by spread’s counterpart, the rest operator, which is written with three dots (...) like spread. However, in this case, we spread the remaining properties into a new object.

const { age:_ , ...person } = getPerson();

console.log(person); // {firstName: "Max", lastName: "Best"}

Now the person object holds all properties from the original person object except age.

Trim your HTML

The complexity of your HTML plays a large role in determining how long it takes to query and modify DOM objects. If you can cut your application's HTML by half, you could potentially double your DOM speed. That's a tough goal, but you can start by eliminating unnecessary <div> and <span> tags.

Use document.getElementById()

Using jQuery lets you create specific selectors based on tag names and classes, but this approach necessitates several iterations as jQuery loops through DOM elements to find a match. You can speed up the DOM by using the document.getElementById() method instead.

// With jQuery
var button = jQuery('body div.window > div.minimize-button:nth-child(3)')[0];

// With document.getElementById()
var button = document.getElementById('window-minimize-button');

Using Quick Powers to Get Better and Faster at JavaScript

With ES7 made available, we now have the ease to use our exponentiation operator “**”. This is a time-saving tool, or shorthand for powers, as it is much faster than using the Math.pow(2, 3) method. Here’s how you will apply this: {% code-block language="js" %}   console.log("2 ** 3: "+ 2 ** 3);{% code-block-end %} You also want to ensure that you aren’t mixing this up with the symbol “^”. This symbol is usually used to represent exponents. However, in JavaScript, it represents your bitwise XOR operator. If ES7 wasn’t there, you could use shorthand dealing with powers, with a base of 2, as done in the example below: {% code-block language="js" %}   console.log("Math.pow(2,3): ", Math.pow(2,3));{% code-block-end %}

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));

Find People To Learn JavaScript With

Learning how to program with JavaScript can be a lonely, boring exercise if you try and do it alone. One of the best ways to take your journey from novice to master JavaScript programmer - is to find like-minded people and learn alongside them. Studying with other people can be very rewarding. If you would like to find other like-minded people who are also learning how to code, start your search on Facebook. Look for 'programming', 'coding', or 'web development' groups in your area. If there isn't one, think about starting one! Alternatively, head over to Meetup.com and search for groups in your local area. If you live in or near a city or major population center, you will find that there is probably already some sort of existing meetup groups for other people who are trying to learn JavaScript, web development, and other types of coding. Join one, head down to their next event, and start connecting with your fellow novice programmers!

;