JavaScript Variables
Variables are "containers" for storing information:
JavaScript Data Types
var answer1="He is called 'Johnny'";
var answer2='He is called "Johnny"';var pi=3.14;
var x=123;
var y=123e5;
var z=123e-5;
var cars=new Array("Saab","Volvo","BMW");
var person={firstname:"John", lastname:"Doe", id:5566};
Like School Algebra
Remember algebra from school?
x=5
y=6
z=x+y
Do you remember that letters (like x) can be used to hold a value (like 5), and that you can use the information above to calculate the value of z to be 11?
These letters are called variables, and variables can be used to hold values (x=5).
JavaScript Variables
As with algebra, JavaScript variables are used to hold values or expressions.
Variable can have a short names, like x and y, or more descriptive names, like age, sum, or, totalvolume.
JavaScript variables can also be used to hold text values, like: name="John Doe".
Here are the rules for JavaScript variable names:
- Variable names are case sensitive (y and Y are two different variables)
- Variable names must begin with a letter, the $ character, or the underscore character
Declaring (Creating) JavaScript Variables
Creating a variable in JavaScript is most often referred to as "declaring" a variable.
You declare JavaScript variables with the var keyword:
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
However, you can also assign a value to the variable when you declare it:
In the example below we create a variable called carname, assigns the value "Volvo" to it, and put the value inside the HTML paragraph with id="demo":
Example
<p id="demo"></p>
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;
JavaScript Data Types
There are many types of JavaScript variables, but for now, just think of two types: text and numbers.
When you assign a text value to a variable, put double or single quotes around the value.
When you assign a numeric value to a variable, do not put quotes around the value. If you put quotes around a numeric value, it will be treated as text.
One Statement, Many Variables
You can declare many variables in one statement. Just start the statement with var and separate the variables by comma:
var name="Doe", age=30, job="carpenter";
Your declaration can also span multiple lines:
var name="Doe",
age=30,
job="carpenter";
Value = undefined
In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.
The variable carname will have the value undefined after the execution of the following statement:
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not lose its value:.
The value of the variable carname will still have the value "Volvo" after the execution of the following two statements:
var carname="Volvo";
var carname;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
You will learn more about JavaScript operators in a later chapter of this tutorial.
JavaScript Functions
A function can be executed by an event, like clicking a button.
JavaScript Functions
A function is a block of code that executes only when you tell it to execute.
It can be when an event occurs, like when a user clicks a button, or from a call within your script, or from a call within another function.
Functions can be placed both in the <head> and in the <body> section of a document, just make sure that the function exists, when the call is made.
How to Define a Function
Syntax
function functionname()
{
some code
}
The { and the } defines the start and end of the function.
Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.
JavaScript Function Example
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
The function is executed when the user clicks the button.
You will learn more about JavaScript events in the JS Events chapter.
Calling a Function with Arguments
When you call a function, you can pass along some values to it, these values are called argumentsor parameters.
These arguments can be used inside the function.
You can send as many arguments as you like, separated by commas (,)
myFunction(argument1,argument2)
Declare the argument, as variables, when you declare the function:
function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first variable is given the value of the first passed argument etc.
Example
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
The function above will alert "Welcome Harry Potter, the Wizard" when the button is clicked.
The function is flexible, you can call the function using different arguments, and different welcome messages will be given:
Example
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<button onclick="myFunction('Bob','Builder')">Try it</button>
The example above will alert "Welcome Harry Potter, the Wizard" or "Welcome Bob, the Builder" depending on which button is clicked.
Functions With a Return Value
Sometimes you want your function to return a value back to where the call was made.
This is possible by using the return statement.
When using the return statement, the function will stop executing, and return the specified value.
Syntax
function myFunction()
{
var x=5;
return x;
}
The function above will return the value 5.
Note: It is not the entire JavaScript that will stop executing, only the function. JavaScript will continue executing code, where the function-call was made from.
The function-call will be replaced with the returnvalue:
The variable myVar holds the value 5, which is what the function "myFunction()" returns.
You can also use the returnvalue without storing it as a variable:
document.getElementById("demo").innerHTML=myFunction();
The innerHTML of the "demo" element will be 5, which is what the function "myFunction()" returns.
You can make a returnvalue based on arguments passed into the function:
Example
Calculate the product of two numbers, and return the result:
function myFunction(a,b)
{
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);
The innerHTML of the "demo" element will be:
12
function myFunction(a,b)
{
if (a>b)
{
return;
}
x=a+b
}
The function above will exit the function if a>b, and will not calculate the sum of a and b.
Local JavaScript Variables
A variable declared (using var) within a JavaScript function becomes LOCAL and can only be accessed from within that function. (the variable has local scope).
You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
Local variables are deleted as soon as the function is completed.
Global JavaScript Variables
Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it.
The Lifetime of JavaScript Variables
The lifetime JavaScript variables starts when they are declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.
Assigning Values to Undeclared JavaScript Variables
If you assign a value to variable that has not yet been declared, the variable will automatically be declared as a GLOBAL variable.
This statement:
will declare the variable carname as a global variable , even if it is executed inside a function.