Sunday, September 24, 2017

Best Practices

Avoid Global Variables

Always Declare Local Variables

 Local variables must be declared with the var keyword, otherwise they will become global variables.

Initialize variables when you declare them.

Never Declare Number, String, or Boolean Objects

Don't Use new Object()

  • Use {} instead of new Object()
  • Use "" instead of new String()
  • Use 0 instead of new Number()
  • Use false instead of new Boolean()
  • Use [] instead of new Array()
  • Use /()/ instead of new RegExp()
  • Use function (){} instead of new Function()

Beware of Automatic Type Conversions

Use === Comparison

The == comparison operator always converts (to matching types) before comparison.
The === operator forces comparison of values and type:

Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to undefined.
Undefined values can break your code. It is a good habit to assign default values to arguments.
<script>
function myFunction(x, y) {
    if (y === undefined) {
        y = 0;
    }   
    return x * y;
}
document.getElementById("demo").innerHTML = myFunction(4);
</script>

End Your Switches with Defaults

Avoid Using eval()

 


 

 


 

No comments:

Post a Comment