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 © Renewable-Media.com. All rights reserved. Created : June 3, 2014 Last updated :March 9, 2016

Latest Item on Science Library:

The most recent article is:

Trigonometry

View this item in the topic:

Vectors and Trigonometry

and many more articles in the subject:

Subject of the Week

Mathematics

Mathematics is the most important tool of science. The quest to understand the world and the universe using mathematics is as old as civilisation, and has led to the science and technology of today. Learn about the techniques and history of mathematics on ScienceLibrary.info.

Mathematics

Great Scientists

Frederick Sanger

1918 - 2013

Frederick Sanger is one of three scientists to have been awarded the Nobel Prize twice, in 1958 and 1980, both times for chemistry.

He was a pioneer in the techniques for sequencing proteins, starting with insulin in the 1940s and 1950s. He moved on to peptides, RNA and finally DNA.

Frederick Sanger
IT Forum by Sean Bone

Quote of the day...

The Stone Age also did not come to end because of a shortage of stones.

ZumGuy Internet Promotions

Renewable energy media services