About Variables

Variables hold values as shown in an earlier example where I assigned the variable Ret the value "prompt('Type the word castle',"");". In this case the value from the user input is aultimatly assigned to the variable Ret. The values are assigned using the assignment opperator, which is the equal sign "=" to obtain their value.

  • Variables are declared using the reserved word var.
  • They are used to save time when coding and updating scripts.
  • They are Code clarifier
  • Variables in JavaScript do not have to declare the type of variable, but must define it.
    • This means that it is not given it a variable type.
    • You can assign any value to any variable, but this leave the door open for major problems is you get careless. ( var our_class "javaScript"; is a string) (var lesson1= 1;is a numeric value).

for example: the variable "results" below is assigned the value of 11 as a result of the arthmatic operation.

  results = 6 + 5;

This example delcares varible "results".

 var results;

Rules for naming Variables:

Variables are Case Sensitive - JavaScript variables case sensate you should be aware that the following variables are different: Candle, CANDLE, candle

Only use valid characters that are allowed to name characters - Variable can only begin with a letter or underscore character. _candle, candle_light, or candle_123 are all valid characters.

Avoid using reserve words - Reserve words are used by JavaScript for a specific purpose, using them will cause major problems.

Always try to us meaningful variables: example( candle_type will contain a value describing a type of candle)

Assigning Variables

Number are declared and assigned numeric values as follow:

var variablename=number; Example:( var number_of_students = 5; var class_cost = 99.99)

document.write(number_of_students); will display 5

document.write(class_cost); will display 99.99

You can display the two variables in the same write statement:

document.write(number_of_students+class_cost); will display 5 99.99 or

document.write("There are " + number_of_students"registered students at a cost of $"+class_cost + "each."); will display There are 5 registered students at a cost of $99.99 each

 
Imsg
Discussion

Blogging

E-mail

 

JAVASCRIPT    -    LESSON 3
J s - variables