Monday, August 27, 2012

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};

Try it yourself »


Do You Remember Algebra From School?

Do you remember algebra from school? x=5, y=6, z=x+y

Do you remember that a letter (like x) could be used to hold a value (like 5), and that you could 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) or expressions (z=x+y).

lampThink of variables as names or labels given to values.


JavaScript Variables

As with algebra, JavaScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.

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
lampBoth JavaScript statements and JavaScript variables are case-sensitive.


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:

var carname;

After the declaration shown above, the variable is empty (it has no value yet).

To assign a value to the variable, use the equal (=) sign:

carname="Volvo";

However, you can also assign a value to the variable when you declare it:

var carname="Volvo";

After the execution of the statement above, the carname will hold the value Volvo.

Example

var carname="Volvo";
document.getElementById("myP").innerHTML=carname;

Try it yourself »


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).

Re-Declaring JavaScript Values

If you re-declare a JavaScript variable, it will not lose its value.

Local JavaScript Variables

A variable declared within a JavaScript function becomes LOCAL and can only be accessed 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.

You will learn more about functions in a later chapter of this tutorial.

Global JavaScript Variables

Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it.

Global variables are deleted 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 as global variables.

This statement:

carname="Volvo";

will declare the variable carname as a global variable (if it does not already exist).

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:

Example

y=5;
x=y+2;

Try it yourself »
You will learn more about the operators that can be used in a later chapter of this tutorial.

JavaScript Comments


JavaScript comments can be used to make the code more readable.

JavaScript Comments

Comments will not be executed by JavaScript.

Comments can be added to explain the JavaScript, or to make the code more readable.
Single line comments start with //.

The following example uses single line comments to explain the code:

Example

// Write to a heading:
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
// Write to a paragraph:
document.getElementById("myP").innerHTML="This is my first paragraph.";

Try it yourself »


JavaScript Multi-Line Comments

Multi line comments start with /* and end with */.
The following example uses a multi line comment to explain the code:

Example

/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";

Try it yourself »


Using Comments to Prevent Execution

In the following example the comment is used to prevent the execution of one of the codelines (can be suitable for debugging):

Example

//document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";

Try it yourself »

In the following example the comment is used to prevent the execution of a code block (can be suitable for debugging):

Example

/*
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
*/

Try it yourself »


Using Comments at the End of a Line

In the following example the comment is placed at the end of a code line:

Example

var x=5; // declare a variable and assign a value to it
x=x+2; // Add 2 to the variable x

Try it yourself »

JavaScript Statements


JavaScript is a sequence of statements to be executed by the browser.

JavaScript Statements

JavaScript statements are "commands" to the browser. The purpose of the statements is to tell the browser what to do.

This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML elemen with id="demo":

document.getElementById("demo").innerHTML="Hello Dolly";


Semicolon ;

Semicolon separates JavaScript statements.

Normally you add a semicolon at the end of each executable statement.

Using semicolons also makes it possible to write many statements on one line.

lampEnding statements with semicolon is optional in JavaScript. You might see examples without semicolons.


JavaScript Code

JavaScript code (or just JavaScript) is a sequence of JavaScript statements.

Each statement is executed by the browser in the sequence they are written.

This example will manipulate two HTML elements:

Example

document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";

Try it yourself »


JavaScript Code Blocks

JavaScript statements can be grouped together in blocks.

Blocks start with a left curly bracket, and end with a right curly bracket.

The purpose of a block is to make the sequence of statements execute together.

An good example of statements grouped together in blocks, are JavaScript functions.

This example will run a function that will manipulate two HTML elements:

Example

function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}

Try it yourself »

You will learn more about functions in later chapters.

JavaScript is Case Sensitive

JavaScript is case sensitive.

Watch your capitalization closely when you write JavaScript statements:

getElementById is not the same as getElementbyID.

JavaScript Working


A JavaScript can be put in the <body> and in the <head> section of an HTML page.

JavaScript in <body>

The example below manipulate the content of an existing <p> element when the page loads:

Example

<!DOCTYPE html>
<html>
<body><h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>

</body>
</html>

Try it yourself »

lampThe JavaScript is placed at the bottom of the page to make sure it is executed after the <p> element is created.


JavaScript Functions and Events

The JavaScript statement in the example above, is executed when the page loads, but that is not always what we want.

Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. Then we can write the script inside a function, and call the function when the event occurs.

You will learn more about JavaScript functions and events in later chapters.

A JavaScript Function in <head>

The example below calls a function in the <head> section when a button is clicked:

Example

<!DOCTYPE html>
<html><head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>

</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>

Try it yourself »


A JavaScript Function in <body>

This example also calls a function when a button is clicked, but the function is in the <body>:

Example

<!DOCTYPE html>
<html>
<body><h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>

</body>
</html>

Try it yourself »


Scripts in <head> and <body>

You can place an unlimited number of scripts in your document, and you can have scripts in both the <body> and the <head> section at the same time.

It is a common practice to put functions in the <head> section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

Using an External JavaScript

Scripts can also be placed in external files. External files often contain code to be used by several different web pages.

External JavaScript files have the file extension .js.
To use an external script, point to the .js file in the "src" attribute of the <script> tag:

Example

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

Try it yourself »

You can place the script in the <head> or <body> as you like. The script will behave as it was located exactly where you put the <script> tag in the document.

lampExternal scripts cannot contain <script> tags.