Science Library - free educational site

Variables and Arrays (JS)

Best Practice

IndexElementGood PracticeOptionalDo not use
1<script> tag<script defer src="http://...js" >async/deferlanguage; text/javascript; text/ecmascript; charset
2varfunction{ var message = "Hello"; }function{ message = "Hello"; }
3Null typevar name = null;
if(name!=null) { //code }
var name = undefined;
  1. <script> tag
  2. language is deprecated.

    ; text/javascript; text/ecmascript are deprecated, and text/javascript is assumed when declaration is missing.

    async for immediate execution of external scripts without preventing other actions on the page, and defer for execution of external scripts after page is loaded fully.

    charset sets the code specified using the src attribute. Most browsers ignore this value.

  3. Variable declaration in a function
  4. It is possible to create a global variable in a function: message = "Hello";. However, it is better practice is avoid confusion (and ReferenceError in Strict mode) by using a local variable, var message = "Hello";, if a global is not essential.

  5. Testing a variable as an object
  6. The Null type has only one value (null). Unlike the Undefined type, the null value points to an empty object pointer. Hence, it may used for an explicit check: if( name != null) { //execute code }.

    Note that null == undefined returns true, but that does not make them identical. null should be used for an object that is expected but unavailable. Although assumed in declaring a variable, initialising the variable as undefined, var name = undefined;, is bad practice. This is not the case with assigning null to a variable upon declaration.

Variable Name Rules

Unlike the $ symbol in PHP, JavaScript does not use any specific character to start a variable (although $ may start a name if you like).

Variables may include a-z, A-Z, 0-9, $, and _.

No other characters, including spaces and punctuation marks, are permitted in variable names.

Numbers may not be used as the first character of a variable name.

Variable names are case sensitive, and there is no set limit to length.

String Variables

A string variable should be put within single or double quote marks. A backslash will escape the use of an apostrophe within the string. This means the code is output without the backslash but the escaped apostrophe is not considered the closure of the variable name string.

fname = 'Arthur'
lname = "Dent"
problem = 'Arthur\'s problem'
document.write(problem)

Numeric Variables

A numeric variable does not use quotation marks:

<script>
price = 100
salestax = 0.0685
discount = 0.15
cost = price - price*discount + (price - price*discount)*salestax
document.write('The selected item will cost you: €' + cost.toFixed(2))
</script>

Commutation rules (order of execution of mathematical operations) can be controlled by parentheses. In the example, (price - price*discount) is calculated first, then the multiplication with salestax, and finally the addition and subtraction in order left to right.

Notice the use of the + symbol before concatenating the variable to the string. The method toFixed(2) rounds the number result to 2 decimal places.

Arrays

Arrays are a variable type (like strings and numbers) which contain a series of similar data as a list. Arrays consist of key-value pairs.

Single-Dimensional Arrays

An array may be created by simply listing the elements:

dogs = ['alsatian', 'dachshund', 'poodle', 'wolfhound']

farm = ['horse', 'sheep', 'cow', 'pig']

cats= ['tiger', 'lion', 'jaguar', 'cougar']

The tricky thing to remember is that the first element in an array is referred to as '0'. Hence dogs[2] == 'poodle', not dachshund as you might suppose.

To print out 'tiger', document.write(cats[0]).

Multi-Dimensional Arrays

animals = [['alsatian', 'dachshund', 'poodle', 'wolfhound'], ['horse', 'sheep', 'cow', 'pig'], ['tiger', 'lion', 'jaguar', 'cougar']]

To print out 'tiger', document.write(animals[2][0]).

Multi-D arrays may also be written as an array of single-D arrays by name:

dogs = ['alsatian', 'dachshund', 'poodle', 'wolfhound']

farm = ['horse', 'sheep', 'cow', 'pig']

cats= ['tiger', 'lion', 'jaguar', 'cougar']

animals = [dogs, farm, cats]

Content © Andrew Bone. All rights reserved. Created : June 3, 2014 Last updated :March 9, 2016

Latest Item on Science Library:

The most recent article is:

Air Resistance and Terminal Velocity

View this item in the topic:

Mechanics

and many more articles in the subject:

Subject of the Week

Environment

Environmental Science is the most important of all sciences. As the world enters a phase of climate change, unprecedented biodiversity loss, pollution and human population growth, the management of our environment is vital for our futures. Learn about Environmental Science on ScienceLibrary.info.

Environmental Science

Great Scientists

Edward Stone

1936 -

Edward Stone's name is synonymous with space exploration. For more than 50 years he has been a leading scientist behind the NASA unmanned probes to Mars, the giant planets, and the outer reaches of the solar system.

Ed Stone
ZumGuy Network Promotions

Quote of the day...

Mathematics is the language with which God has written the universe.

ZumGuy Internet Promotions

Vitruvian Boy