JavaScript Lesson 4: Variables in JavaScript

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone

<Previous Lesson> [Table of Contents] <Next Lesson>

4.1 What is a Variable in JavaScript?

A variable is something that holds values or information. The values can be numbers (numeric values), text (strings) or some other kinds of information such as dates, boolean values(true/false) and more. These values can vary from time to time, that is why the name variable. It is similar to the post boxes in the post office, the contents of the post boxes can change but the post boxes still have the same name or label. In order to identify the variables, we have to name them. There are a few rules regarding variable names in JavaScript, as shown below:



There are no hard and fast rules that you must obey in choosing a variable name, but it is best that you choose a name that is meaningful as it makes debugging your program easier.For example, you can use Tel_No for telephone number, which is better than just using a variable x.

4.2 Assigning Values to Variables

After you have created a variable, you can assign a value to it. The value can be in the form of number( numeric value), text (String) or boolean (true or false).

The basic  structure of value assignment in JavaScript is
var variable_name= value

Example 4.2(a): Assigning a numeric value

var mark = 20
var sell_price=100
var age = 40
var height = 180
var temp = 30

Example 4.2(b) Assigning a String

var First_Name="George"
var car_model = " Laser 100"
var Company_Name = ' Ultra Mobile LLC '

Note: The string must be enclosed in quotation marks(either double or single)

Example 4.2(c) Assigning a Boolean value

var paid = true
var alive = false
var positive = true

4.3 Application

Let’s apply what have learned about values assignment in the following example:

Example 4.3(a)

<script language="JavaScript">
var Author_Name  =  "John Brandon",
 Author_ID  =  "A1234",
 ISBN  =  "0-7789-0234-6",
 Royalty  =  100000;

document.writeln("Author Name:"+Author_Name+"<BR>");
document.writeln(" Author ID:"+Author_ID+"<BR>");
document.writeln("ISBN:"+ISBN+"<BR>");
document.writeln("Royalty Payment: $"+Royalty);
</script>

Click Example4.3(a) to view the output.



<Previous Lesson> [Table of Contents] <Next Lesson>

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone