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 in a little more 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 generate the same output, then which code is better?
The correct answer is:
- If it is written using a language like C#, Java which supports compiler, then without any doubt, the second one is better because it will provide a better execution performance.
- But if it is JavaScript, then the first code is better because it is smaller 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 the 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”
CodeProject