# JavaScript Best Practices

« Previous
Next Chapter »

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

## 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 keyword, otherwise they will become global variables.

| Strict mode does not allow undeclared variables.

## Declarations on Top

It is good coding practice, to put all declarations at the top of each script or function. This makes it easier to avoid unwanted (implied) global variables. It also gives cleaner code, and reduces the possibility of unwanted re-declarations.

var firstName, lastName;
var price, discount, fullPrice;
firstName = "John";
lastName = "Doe";
price = 19.90;
discount = 0.10;
fullPrice = price * 100 / discount;

Variable declarations should always be the first statements in scripts and functions.

This also goes for variables in loops:

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

| Since JavaScript moves the declarations to the top anyway (JavaScript hoisting), it is always a good rule.

## Never Declare Numbers, Strings, or Booleans as Objects

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

Declaring numbers, strings, or booleans as objects, slows down execution speed, and produces nasty side effects:

## Example

var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object.
Try it yourself »

## 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()

## Example

var x1 = {}; // new object
var x2 = ""; // new primitive string
var x3 = 0; // new primitive number
var x4 = false; // new primitive boolean
var x5 = []; // new array object
var x6 = /()/; // new regexp object
var x7 = function(){}; // new function object
Try it Yourself »

## Beware of Automatic Type Conversions

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

JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type:

## Example

var x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number
Try it yourself »

When doing mathematical operations, JavaScript can convert numbers to strings:

## Example

var x = 5 + 7; // x.valueOf() is 12, typeof x is a number
var x = 5 + "7"; // x.valueOf() is 57, typeof x is a string
var x = "5" + 7; // x.valueOf() is 57, typeof x is a string
var x = 5 - 7; // x.valueOf() is -2, typeof x is a number
var x = 5 - "7"; // x.valueOf() is -2, typeof x is a number
var x = "5" - 7; // x.valueOf() is -2, typeof x is a number
var x = 5 - "x"; // x.valueOf() is NaN, typeof x is a number
Try it yourself »

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

## Example

"Hello" - "Dolly" // returns NaN
Try it yourself »

## Use === Comparison

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

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

## Example

0 == ""; // true
1 == "1"; // true
1 == true; // true
0 === ""; // false
1 === "1"; // false
1 === true; // false
Try it yourself »

## 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.

## Example

function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}

Or, even simpler:

function myFunction(x, y) {
y = y || 0;
}
Try it Yourself »

Read more about function parameters and arguments at Function Parameters

## 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.

« Previous
Next Chapter »

### WEB HOSTING

UK Reseller Hosting

### WEB BUILDING

FREE Website BUILDER Free HTML5 Templates

### W3SCHOOLS EXAMS

HTML, CSS, JavaScript, PHP, jQuery, XML, and ASP Certifications

### SHARE THIS PAGE

### Color Picker

### HTML/CSS

HTML Tutorial HTML5 Tutorial CSS Tutorial CSS3 Tutorial Bootstrap Tutorial

### JavaScript

JavaScript Tutorial jQuery Tutorial jQuery Mobile Tutorial AngularJS Tutorial AJAX Tutorial JSON Tutorial

### Graphics

Canvas Tutorial SVG Tutorial Google Maps Tutorial

### Server Side

SQL Tutorial PHP Tutorial ASP Tutorial ASP.NET Tutorial VBScript Tutorial AppML Tutorial

### Web

Web Building Web Statistics Web Certification

### XML

XML Tutorial DTD Tutorial Schema Tutorial XML DOM Tutorial XPath Tutorial XSLT Tutorial XQuery Tutorial XSL-FO Tutorial RSS Tutorial WSDL Tutorial

### HTML/CSS

HTML Tag Reference HTML Event Reference HTML Color Reference CSS 1,2,3 Reference Bootstrap Reference

### JavaScript

JavaScript Reference HTML DOM Reference jQuery Reference jQuery Mobile Reference Google Maps Reference

### Server Side

PHP Reference SQL Reference ASP Reference VBScript Reference Razor Reference ASP.NET Reference

### XML

XML DOM Reference XSLT Reference XSL-FO Reference XPath Reference XQuery Reference Schema Reference RSS Reference SVG Reference

### HTML Charsets

HTML Character Sets HTML ASCII HTML ANSI HTML Windows-1252 HTML ISO-8859-1 HTML Symbols HTML UTF-8

### HTML/CSS

HTML Examples CSS Examples

### Browser Scripting

JavaScript Examples HTML DOM Examples jQuery Examples jQuery Mobile Examples AngularJS Examples AJAX Examples

### Server Scripting

PHP Examples ASP Examples VBScript Examples Razor Examples .NET Examples

### XML Languages

XML Examples DTD Examples XML DOM Examples XSL Examples XSLT Examples XPath Examples XQuery Examples Schema Examples RSS Examples SVG Examples