Declaring Variables - "var" Statements

This section provides descriptions on variables and a tutorial example on how to declare variables with 'var' statements.

What are variables? Variables are symbolic names that refer to values stored in the memory.

Variable names must be sequences of alphanumeric characters and underscore (_). But the first character can not be a numeric character. (_5star) is a valid variable name. But (5star) is not an invalid variable name.

Variable can be used without declaration. But it is strongly recommended that all variables are declared with "var" statements in the following syntax formats:

var var_name_1;
var var_name_1 = value_1;
var var_name_1, var_name_2, var_name_3, ...; 
var var_name_1 = value_1, var_name_1 = value_1, ...;

If a variable is declared without initial value, it contains the "undefined" value.

Here is a JavaScript tutorial example that shows you how to declare variables with "var" statements:

<html>
<!-- Variables.html
   Copyright (c) 2002 HerongYang.com. All Rights Reserved.
-->
<head><title>Variables</title></head>
<body>
<pre>
<script type="text/javascript">
   var site_url = 'herongyang.com';
   var site_rank = 9;
   var site_content;
   
   site_title = "Herong's Tutorial Examples"; // should be declared first

   document.write(site_url);
   document.write('\n');
   document.write(site_title);
   document.write('\n');
   document.write(site_rank);
   document.write('\n');
   document.write(site_content);
   document.write('\n');
</script>
</pre>
</body>
</html>

The output of this sample JavaScript is:

herongyang.com
Herong's Tutorial Examples
9
undefined

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

Data Types, Variables and Expressions

 Primitive Data Types - Numbers, Strings, and Booleans

 Numeric Value Literals

 String Literals

Declaring Variables - "var" Statements

 Operators and Expressions

 Operators and Expressions - Examples

 Flow Control Statements

 Creating, Accessing, and Manipulating Arrays

 Defining and Calling Functions

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 AJAX (Asynchronous JavaScript And XML)

 References

 Full Version in PDF/EPUB