Try my app Expense Manager @ google play and amazon store.

Saturday, June 9, 2012

Java Script Beginner Tutorial 5 : Java Script Variables

JavaScript variables are used to hold values or expressions. A variable can have a short name e.g x or y etc, or it can have more descriptive name, for example firstname or city. There are some rules for naming JavaScript variables, these are below.

  • Variable names are case sensitive, y and Y are two different variables. (as JavaScript is case-sensitive, so variable names are also case-sensitive.)
  • Variable names must begin with a letter, the $ character, or the underscore character.

JavaScript Variables Declaration :
Creating new variable in JavaScript is most often referred to as "declaring" a variable. Variables are declared in JavaScript using var keyword, e.g var cityname; To assign a value to the variable, we use the  =  sign, e.g cityname="NYC"; However, we can also assign a value to the variable when we declare it, e.g var cityname="NYC";

To assign a text value to a variable, put quotes around the value. While assigning 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. If you redeclare a JavaScript variable, it will not lose its value.

If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables. e.g cityname="NYC"; will declare the variable carname as a global variable if it does not already exist.

Local JavaScript Variables :
A variable declared within a JavaScript function becomes local and can only be accessed within that function. Local variables can be 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. Global variables are deleted only when you close the page.

JavaScript Arithmetic :
You can do arithmetic operations with JavaScript variables ( as we do with algebra ). For example


No comments:

Post a Comment

Follow by Email

Google+ Badge