Top 10 Javascript tips

YUI Compressor

YUI Compressor is a command-line tool that was created by Yahoo! It delivers a higher compression ratio than most of its competitors. YUI Compressor can also compress CSS files. Different code compression tools may be better suited for certain applications.

Short Circuit Evaluation & Assignment

The JavaScript logical operators, AND (&&) and OR (||) are known as short circuit operators because they only evaluate the expression as far as necessary in order to determine the result of the boolean expression. For example, AND requires that both sides of the expression evaluate to true. Therefore, if the left-hand side of the expression evaluates to false, it does not bother to check the right-hand side as it would be a waste of time. Similarly, OR requires that only one side off the expression evaluates to true. Therefore, if the left-hand side evaluates to true, it doesn't bother to check the right-hand side. This short circuiting can be useful for adding some safety to expressions involving objects. For example, consider the following function:

function logIfAdult(person) {
  if(person.age >= 18) {
    console.log("Person is an adult");
  }
}

The problem with this implementation is that you cannot guarantee that the person object is not null. If you run this function with a null person, you will get the following error: Uncaught TypeError: Cannot read property 'age' of null. Thanks to short circuit evaluation, we can add some safety like this:

function logIfAdult(person) {
  if(person && person.age >= 18) {
    console.log("Person is an adult");
  }
}

This is because, if person is null it will evaluate to false (this is because null is a "falsey" value, if this concept is new to you, please read this article too), and the whole expression will short circuit. Only if person is not null will the expression move on to check the right-hand side of the expression, at which point we know it is safe to check and we wont get any errors. We can exploit this short circuiting when assigning variables too. For example, consider the following function:

function logName(person) {
  let name = person && person.name;
  console.log(name);
}

logName({ name: 'Sam' });
// logs 'Sam'

logName(null)
// logs 'null'

What is happening here? Well in the first example, we pass the function a valid person object. Because the person object is not null, the AND operator moves over to the right-hand side of the expression, and assigns the value of person.name to the name variable. In the second example, person is null so the expression short circuits and returns null to the name variable. We can extend this further to log a default name instead of just null. This time we use the OR operator, so we will only use the default value if the person object is null.

function logName(person) {
  let name = person && person.name || 'Default Name';
  console.log(name);
}

logName({ name: 'Sam' });
// logs 'Sam'

logName(null)
// logs 'Default Name'

The Fastest Way to Convert a String into a Number in JavaScript

Converting a string into a number is yet another type conversion. The trick here is the opposite of what we did in the previous one (converting to a string). All you need to do here is use the concatenation operator “+” as shown below: {% code-block language="js" %}   let int = "10";   int = +int   console.log("Value of int: "+ int);   console.log("Type of value is: ", typeof int);{% code-block-end %} Using the same method, you may also convert Booleans to numbers as done below: {% code-block language="js" %}    console.log("+true to number: " + +true);   console.log("+false to number: " + +false);{% code-block-end %} You might be using “+” as the concatenation operator instead of another operator. But, in such cases you would need to return an integer, not a float.

Double NOT bitwise operator (~~)

The double NOT bitwise operator is a substitute for Math.floor() method.

const floor = Math.floor(6.8); // 6

to ⬇

const floor = ~~6.8; // 6


The double NOT bitwise operator approach only works for 32-bit integers. So for any number higher than that, it is recommended to use Math.floor()

Optional Chaining & Nullish Coalescing Operator

Short circuit evaluation and assignment is so common that new more concise syntax is being added in to JavaScript to achieve the same aim. These are the optional chaining and nullish coalescing operators. I have decided to include both short circuiting and optional chaining/null coalescing since, at the time of writing, the latter are newer features and may not be fully compatible with older browsers. The optional chaining operator (?.) allows you to dive into objects without explicitly having to check if the object is not null. If the object is null, then the expression will just return undefined instead of throwing an error. For example, with optional chaining, the logIfAdult function from above can be rewritten as:

function logIfAdult(person) {
  if(person?.age >= 18) {
    console.log("Person is an adult");
  }
}

The nullish coalescing operator (??) is used to return a default value if the value on the left-hand side of the expression is null. In this way, it replaces the functionality of the OR operator in the logName function above:

function logName(person) {
  let name = person?.name ?? 'Default Name';
  console.log(name);
}

Avoid Using JavaScript

You must be wondering what’s the point? That's because even with ES6 and other features added by ES2016/ES7, it still has its quirks. If you are open to exploring other options, you can highly benefit from minimal setup. Based on the requirement, expertise level and the nature of the app, you can do better with TypeScript or Flow which provides strong typing. Some other options include Elm or ClojureScript which are purely functional. On the other hand, there is CoffeeScript which is another great option. When you have a requirement for a few macros, not an entirely new language, you can consider Sweet.js. It does exactly what you want. It will allow you to write code that will generate code. If you take the non-JavaScript route, you should still include the compiled code because developers may not understand your language well enough and therefore may not be able to build it properly. Here is a quick example for you to understand. Think of the VS Code which is one of the largest TypeScript projects. It uses TypeScript to patch the Node’s core module with types. Therefore in the vscode/src/vs/base/node/ of VS Code repo, you will observe familiar module names like crypto, process, etc. yet with the ts extension. You will find other ts files in the repo. But, they included vscode/build with native JavaScript code.

Converting to numbers

JavaScript is a loosely typed language, meaning we don't have to explicitly specify types of variables. JavaScript also freely type-converts values into a type depending on the context of their use. Converting values to numbers, especially strings to numbers, is a common requirement and many methods can be used.

Difference b/w === and

The == (or !=) operator performs           an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==. [10] === 10      // is false [10]  == 10       // is true ’10’ == 10        // is true ’10’ === 10      // is false []   == 0         // is true  ” == false      // is true   but true == “a” // is false  ” ===   false // is false

Destructuring

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

Use HTTP/2

HTTP/2 is the latest version of the HTTP protocol and provides some great enhancements that will not only help improve your JavaScript performance but will also help speed up your site in general. HTTP/2 uses multiplexing, therefore allowing multiple requests and responses to be sent at the same time. If you haven't moved to HTTPS yet, be sure to do so as soon as possible to take advantage of the performance improvements that HTTP/2 has to offer.

;