JavaScript Best Practices
Avoid global variables, avoid new, avoid ==, avoid eval()
Avoid global variables, avoid new, avoid ==, avoid eval()
Share
Avoid Global Variables
Minimize the use of global variables.
This includes all data types, objects, and functions.
Global variables and functions can be overwritten by other scripts.
Use local variables instead, and learn how to use closures.
Always Declare Local Variables
All variables used in a function should be declared as local variables.
Local variables must be declared with the var, the let, or the const keyword, otherwise they will become global variables.
Declarations on Top
It is a good coding practice to put all declarations at the top of each script or function.
This will:
- Give cleaner code
- Provide a single place to look for local variables
- Make it easier to avoid unwanted (implied) global variables
- Reduce the possibility of unwanted re-declarations
Example
Example Code
javascript// 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:
Example
Example Code
javascriptfor (let i = 0; i Initializing variables provides an idea of the intended use (and intended data type).
---
## Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable declared with `var`, it will not lose its value.
The variable `carName` will still have the value "Volvo" after the execution of these statements:
### Example (Not Recommended)javascript var carName = "Volvo";
var carName;
Example Code
htmlYou cannot re-declare a variable declared with `let` or `const`.
### Examplesjavascript let carName = "Volvo";
let carName;
Example Code
html---
## Declare Objects with const
Declaring objects with const will prevent any accidental change of type:
### Examplejavascript let car = {type:"Fiat", model:"500", color:"white"};
car = "Fiat"; // Changes object to string
Example Code
html---
## Declare Arrays with const
Declaring arrays with const will prevent any accidential change of type:
### Examplejavascript let cars = ["Saab", "Volvo", "BMW"];
cars = 3; // Changes array to number
Example Code
html---
## 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()
### Examplejavascript let x1 = ""; // new primitive string
let x2 = 0; // new primitive number
let x3 = false; // new primitive boolean
const x4 = {}; // new object
const x5 = []; // new array object
const x6 = /()/; // new regexp object
const x7 = function(){}; // new function object
Example Code
html---
## Beware of Automatic Type Conversions
JavaScript is loosely typed.
A variable can contain all data types.
A variable can change its data type:
### Examplejavascript let x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number
Example Code
htmlBeware that numbers can accidentally be converted to strings or `NaN` (Not a Number).
When doing mathematical operations, JavaScript can convert numbers to strings:
### Examplejavascript let x = 5 + 7; // x.valueOf() is 12, typeof x is a number
let x = 5 + "7"; // x.valueOf() is 57, typeof x is a string
let x = "5" + 7; // x.valueOf() is 57, typeof x is a string
let x = 5 - 7; // x.valueOf() is -2, typeof x is a number
let x = 5 - "7"; // x.valueOf() is -2, typeof x is a number
let x = "5" - 7; // x.valueOf() is -2, typeof x is a number
let x = 5 - "x"; // x.valueOf() is NaN, typeof x is a number
Example Code
htmlSubtracting a string from a string, does not generate an error but returns `NaN` (Not a Number):
### Examplejavascript "Hello" - "Dolly" // returns NaN
Example Code
html---
## Use === Comparison
The `==` comparison operator always converts (to matching types) before comparison.
The `===` operator forces comparison of values and type:
### Examplejavascript 0 == ""; // true
1 == "1"; // true
1 == true; // true
0 === ""; // false
1 === "1"; // false
1 === true; // false
Example Code
html---
## 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.
### Examplejavascript function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
Example Code
html### Examplejavascript function (a=1, b=1) { /function code/ }
Example Code
htmlRead more about function parameters and arguments at [Function Parameters](js_function_parameters.asp)
---
## End Your Switches with Defaults
Always end your `switch` statements with a `default`. Even if you think there is no need for it.
### Examplejavascript 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"; }
Example Code
html---
## Avoid Number, String, and Boolean as Objects
Always treat numbers, strings, or booleans as primitive values. Not as objects.
Declaring these types as objects, slows down execution speed, and produces nasty side effects:
### Examplejavascript let x = "John";
let y = new String("John");
(x === y) // is false because x is a string and y is an object.
Example Code
htmlOr even worse:
### Examplejavascript let x = new String("John");
let y = new String("John");
(x == y) // is false because you cannot compare objects. ```
Avoid Using eval()
The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it.
Because it allows arbitrary code to be run, it also represents a security problem.
Interactive Code Examples
Example 1
javascript// 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;Example 2
javascriptfor (let i = 0; i < 5; i++)
{Example 3
javascript// Declare and initiate at the beginning
let firstName = "";
let lastName = "";
let price = 0;
let discount = 0;
let fullPrice = 0,
const myArray = [];
const myObject = {};Example (Not Recommended)
javascriptvar carName = "Volvo";
var carName;Examples
javascriptlet carName = "Volvo";
let carName;JS Example 6
javascriptlet car = {type:"Fiat", model:"500", color:"white"};
car = "Fiat"; // Changes object to string