JavaScript Variables
- Variable names are case sensitive (
y
and Y
are two different variables).
- Variable names must begin with a letter or the underscore character.
Declaring (Creating) JavaScript Variables
You can declare JavaScript variables with the var
statement:
var x; var carname;
You can also assign values to the variables when you declare them:
var x = 5; var carname = "Volvo";
Local and Global JavaScript Variables
- A variable declared within a JavaScript function becomes local and can only be accessed within that function.
(The variable has local scope.)
Local variables are destroyed when you exit the function.
- Variables declared outside a function becomes global, and all scripts and functions on the web page can access it.
Global variables are destroyed when you close the page.
Assigning Values to Undeclared JavaScript Variables
If you assign values to variables that have not yet been declared, the variables will automatically be declared.
The following statements will declare the variables x
and carname
as global variables (if they do not already exist):
x = 5; carname = "Volvo";
JavaScript Arithmetic
As with algebra, you can do arithmetic operations with JavaScript variables:
y = x-5; z = y+5;
Demonstration
The following demonstration shows how the script of HTML and JavaScript is displayed on the Web.
If you want to reach the island with the treasure,
you’ve got to swim with sharks (take a major risk) for a while.
|