Notes for Javascript Best Practices

Ternary Conditional

condition ? ifConditionTrue : ifConditionFalse ;
var cheese = isFeta ? "Feta" : "Cheese"

In Javascript any value returns true except from: false, 0, undefined, NaN, "", null

OR operator - short circuiting

In the following syntax, will the empty array get checked?
this.cheese = this.cheese || [ ]; (By the way, this syntax can be used to initialization)

If this.cheese is undefined then yes, [ ] will be checked and return an empty array since it's not false, 0, undefined, NaN, "", null.
So, this.cheese = [ ];

if this.cheese includes ["feta", "edam"] then, no the [ ] will not be checked.
And this.cheese = ["feta", "edam"];

This is called short circuiting, meaning the OR operator will accept the first truthy value found.

AND operator - short circuiting

Short circuiting in AND operator takes the last true value or the first false value.


Splice can be executed against an array. It gets two parameters, first the index of the element and second how many elements will be extracted from the array. Finally, it returns an array which include the extracted elements.

So, so in this array:
var cheese = ["feta", "edam"];
when we runvar favorite_cheese = cheese.splice(0,1); we'll get favorite_cheese = ["feta"] and cheese = ["edam"]


Here, we have an array called cheese = [ "feta", "edam", "cheddar", "gouda", "mascarpone", "mozzarella", "kefalotyri"]
Which of the following syntaxes is faster?
for ( var i = 0 ; i < cheese.length ; i ++ ) {
for (var i = 0, x = cheese.length; i < x ; i++) {
The answer: The second, because cheese.length is calculated one time while in the first example it is calculated each time.

Loading scripts

Scripts should be loaded after the page is presented to user to enhance user experience. The only reason to execute a script is if it is absolutely necessary for the presentation.
So, to load your scripts prefer one of the following solutions.

  • At the end before the closing body tag ()
  • Add the async attribute (eg )

comments powered by Disqus