44 views

Lesson 3. Variables in javascript

Variables

Variables are memory locations that are given names and can be assigned values. We use variables to store data in memory for later use.

Variable names
Once a value is stored in a variable it can be accessed using the variable name. A variable name can consist of alphanumeric characters and the underscore. It cannot begin with a numeral, though. Note that variable names are case sensitive and first_name is not the same as FIRST_name.

Valid variable names
      first_name
      name2
      _car
      Average
Invalid variable names
      100_numbers      (name starts with a numeral)
      rate%_of_inflation      (non legal character)

Declaring JavaScript Variables
Creating variables in JavaScript is most often referred to as “declaring” variables.

You can declare JavaScript variables with the var statement:

var x;
var product_name;

After the declaration shown above, the variables has no values, but you can assign values to the variables while you declare them:

var x=5;
var product_name=”Dell computer”;

Note: When you assign a text value to a variable, you use quotes around the value.

Assigning Values to JavaScript Variables
You assign values to JavaScript variables with assignment statements:

x=5;
product_name=”Dell computer”;

The variable name is on the left side of the = sign, and the value you want to assign to the variable is on the right.

After the execution of the statements above, the variable x will hold the value 5, and product_name will hold the value Dell computer.

Assigning Values to Undeclared Variables
If you assign values to variables that has not yet been declared, the variables will automatically be declared.

These statements:

x=5;
carname=”Volvo”;

are same as:

var x=5;
var carname=”Volvo”;

Post a Comment

You must be logged in to post a comment.