JS Best Practices

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

JavaScript Classes

Avoid global variables, avoid new, avoid ==, avoid eval()

Avoiding Global Variables

Minimizing the use of global variables

This consists of all data types, objects, and functions.

Global variables and functions can be overwritten by other scripts.

Always Declare Local Variables

All variables used in a function must be declared as local variables.

Local variables can be declared using the var keyword or the let keyword, or the const keyword, otherwise, they will become global variables.

The strict mode does not permit undeclared variables.

Declarations on Top

It is a great coding practice to declare at the top of each script or function.

This will:

  • Provides cleaner code.
  • Gives a single place to look for local variables.
  • Make it easier to avoid unwanted (implied) global variables

Reduce the possibility of unwanted re-declarations

// Declare at the beginning

let firstName, lastName, price, discount, fullPrice;

// Use later

firstName = “John”;

lastName = “Doe”;

price = 19.90;

discount = 0.10;

fullPrice = price – discount;

This also goes for loop variables:

for (let i = 0; i < 5; i++) 

Initialize Variables

It is a practice to initialize variables to declare them.

This will:

  • Provide cleaner code.
  • Gives a single place to initialize variables.
  • Avoid undefined values.

// Declare and initiate at the beginning

let firstName = “”,

let lastName = “”,

let price = 0,

let discount = 0,

let fullPrice = 0,

const myArray = [],

const myObject = {};

Declare Objects with const

Declaring objects with const avoids any accidental change of type:

let car = {type:”Fiat”, model:”500″, color:”white”};

car = “Fiat”;      // Changes object to string

const car = {type:”Fiat”, model:”500″, color:”white”};

car = “Fiat”;      // Not possible

Declare Arrays with const

Declaring arrays with const avoids any accidential change of type:

let cars = [“Saab”, “Volvo”, “BMW”];

cars = 3;    // Changes array to number

const cars = [“Saab”, “Volvo”, “BMW”];

cars = 3;    // Not possible

Don’t Use new Object()

Use “” instead of new String()

Use 0 instead of new Number()

Use false instead of new Boolean()

Use {} instead of new Object()

Use [] instead of new Array()

Use /()/ instead of new RegExp()

Use function (){} instead of new Function()

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Literal Constructors</h2>

<p id=”demo”></p>

<script>

let x1 = “”;

let x2 = 0;

let x3 = false;

const x4 = {};

const x5 = [];

const x6 = /()/;

const x7 = function(){};

document.getElementById(“demo”).innerHTML =

“x1: ” + typeof x1 + “<br>” +

“x2: ” + typeof x2 + “<br>” +

“x3: ” + typeof x3 + “<br>” +

“x4: ” + typeof x4 + “<br>” +

“x5: ” + typeof x5 + “<br>” +

“x6: ” + typeof x6 + “<br>” +

“x7: ” + typeof x7 + “<br>”;

</script>

</body>

</html>

Output

JavaScript Literal Constructors

Beware of Automatic Type Conversions

JavaScript is loosely typed.

A variable can have all data types.

A variable can change its data type:

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Variables</h2>

<p>A variable can chang its type. In this example x is first a string then a number:</p>

<p id=”demo”></p>

<script>

let x = “Hello”;

x = 5;

document.getElementById(“demo”).innerHTML = typeof x;

</script>

</body>

</html>

Output

JavaScript Variables

A variable can chang its type. In this example x is first a string then a number:

number

Avoid using numbers that can accidentally be converted to strings or NaN (Not a Number).

When doing mathematical operations, JavaScript converting numbers to strings:

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Variables</h2>

<p>Remove the comment (at the beginning of the lines) to test each case:</p>

<p id=”demo”></p>

<script>

let x = 5;

//x = 5 + 7;    // x.valueOf() is 12, typeof x is a number

//x = 5 + “7”;  // x.valueOf() is 57, typeof x is a string

//x = “5” + 7;  // x.valueOf() is 57, typeof x is a string

//x = 5 – 7;    // x.valueOf() is -2, typeof x is a number

//x = 5 – “7”;  // x.valueOf() is -2, typeof x is a number

//x = “5” – 7;  // x.valueOf() is -2, typeof x is a number

//x = 5 – “x”;  // x.valueOf() is NaN, typeof x is a number

document.getElementById(“demo”).innerHTML = x.valueOf() + ” ” + typeof x;

</script>

</body>

</html>

Output

JavaScript Variables

Remove the comment (at the beginning of the lines) to test each case:

5 number

Subtracting a string from a string, does not generate an error but returns NaN (Not a Number):

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Variables</h2>

<p>Subtracting a string from a string, does not generate an error but returns NaN (Not a Number):</p>

<p id=”demo”></p>

<script>

document.getElementById(“demo”).innerHTML = “Hello” – “Dolly”;

</script>

</body>

</html>

Output

JavaScript Variables

Subtracting a string from a string, does not generate an error but returns NaN (Not a Number):

NaN

Use === Comparison

The == comparison operator converts (to matching types) before comparison.

The === operator forces comparison of values and type:

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Comparisons</h2>

<p>Remove the comment (at the beginning of each line) to test each case:</p>

<p id=”demo”></p>

<script>

let x;

//x = (0 == “”);   // true

//x = (1 == “1”);  // true

//x = (1 == true);   // true

//x = (0 === “”);  // false

//x = (1 === “1”);   // false

//x = (1 === true);  // false

document.getElementById(“demo”).innerHTML = x;

</script>

</body>

</html>

Output

JavaScript Comparisons

Remove the comment (at the beginning of each line) to test each case:

undefined

Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to undefine.

Undefined values can break your code. Always assign default values to arguments.

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Functions</h2>

<p>Setting a default value to a function parameter.</p>

<p id=”demo”></p>

<script>

function myFunction(x, y) {

  if (y === undefined) {

    y = 0;

  } 

  return x * y;

}

document.getElementById(“demo”).innerHTML = myFunction(4);

</script>

</body>

</html>

Output

JavaScript Functions

Setting a default value to a function parameter.

0

End Your Switches with Defaults

Switch statements must end with a default. Even if you think there is no need for it.

Example

<!DOCTYPE html>

<html>

<body>

<p id=”demo”></p>

<script>

let day;

switch (new Date().getDay()) {

  case 0:

    day = “Sunday”;

    break;

  case 1:

    day = “Monday”;

    break;

  case 2:

    day = “Tuesday”;

    break;

  case 3:

    day = “Wednesday”;

    break;

  case 4:

    day = “Thursday”;

    break;

  case 5:

    day = “Friday”;

    break;

  case  6:

    day = “Saturday”;

    break;

  default:

     day = “unknown”;

}

document.getElementById(“demo”).innerHTML = “Today is ” + day;

</script>

</body>

</html>

Output

Today is Friday

Avoid Number, String, and Boolean as Objects

Always treat numbers, strings, or booleans as primitive values. Not as objects.

Declaring this types as objects, slows down execution speed, and produces nasty side effects.

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript String Objects</h2>

<p>Never create strings as objects.</p>

<p>Strings and objects cannot be safely compared.</p>

<p id=”demo”></p>

<script>

let x = “John”;        // x is a string

let y = new String(“John”);  // y is an object

document.getElementById(“demo”).innerHTML = (x === y);

</script>

</body>

</html>

Output

JavaScript String Objects

Never create strings as objects.

Strings and objects cannot be safely compared.

false

Avoid Using eval()

The eval() function runs text as code. In almost all cases, it should not be necessary to use it.

It allows the arbitrary code to run, it also represents a security problem.