JavaScript – Write less not use less.

Whether it is Angular or knockout or any other client side library, in all my training I always make one statement. “Write less JavaScript. Write less doesn’t mean use less”.

Let me explain it a little detail.

Unlike other Programming languages, JavaScript is not a compiled language hence it is very important how much code we write it comes to JavaScript. Look at the following two code snippets.

Code Snippet 1:

for(i=0;i<100;i++)
{
      if(flag==true)
{
PrintRandomNumberLessThanSpecifiedNumber(i);
}
else
{
            PrintRandomNumberGreaterThanSpecifiedNumber(i);
}
}

Code Snippet 2:

if(flag==true)
{
      for(i=0;i<100;i++)
      {
            PrintRandomNumberLessThanSpecifiedNumber(i);
      }
}
else
{
      for(i=0;i<100;i++)
      {
            PrintRandomNumberGreaterThanSpecifiedNumber(i);
      }
}

Both will generates the same output, then which code is a better code?

Correct answer is,

  • If it is written using a language like C#, Java which supports compiler then without any doubt second one is a better code because it will provide a better execution performance.
  • But if it is a JavaScript then the first code is better because it is less in size.

As I said before, JavaScript is not a compiled language. It’s an interpreted language. “JavaScript code will get downloaded as it is to client machine”. It means “More we write, more will be downloaded and less performance”. Hence while writing JavaScript it’s very important to keep an eye on how much we write. “Less we write, better will be the performance”.

On the other hand, it doesn’t mean we should use less JavaScript. Use it wherever it is required but with the help of some custom logic and strategy try to accomplish the requirement with less code.

Hence it’s said, “Write less JavaScript, not Use less”

Comments

comments

Leave a Reply