When choosing a variable name, you must first be sure that you do not use any of the JavaScript reserved names Found Here. Another good practice is choosing variable names that are descriptive of what the variable holds. If you have a variable that holds the size of a shoe, then name it “shoe_size” to make your JavaScript more readable.
Finally, JavaScript variable names may not start with a numeral (0-9). These variable names would be illegal: 7lucky, 99bottlesofbeer, and 3zacharm.
A good rule of thumb is to have your variable names start with a lowercase letter (a-z) and use underscores to separate a name with multiple words (i.e. my_var, strong_man, happy_coder, etc).

JavaScript Variable Scope

A variable can be either global or local in JavaScript.
All variables are global unless they are declared in a function.
Variables declared in a function are local to that function.
It is possible for two variables with the same name to exist if one is global and the other is local.
When accessing the variable within the function, you are accessing the local variable.
If the variable is accessed outside the function, the global variable is used.
Always use the var keyword to declare local variables in functions.
Without var, JavaScript will create a global variable.
Variable names are case sensitive (y and Y are two different variables)
Variable names must begin with a letter or the underscore character
Variables in JavaScript are defined by using the var operator (short for variable), followed by the variable name, such as:
var test = "hi";
In this example, the variable test is declared and given an initialization value of “hi” (a string).
You can also define two or more variables using the same var statement:
var test = "hi", test2 = "hola";
Variables using the same var statement don’t have to be of the same type:
var test = "hi", age = 25;
variables in JavaScript do not require initialization:
var test;
A variable can be initialized with a string value, and later on be set to a number value.
var test = "hi";
alert(test);
test = 55;
alert(test);
Code blocks indicates a series of statements that should be executed in sequence.
Code blocks are enclosed between an opening brace ({) and a closing brace (}).
if (test1 == "red") {
   test1 = "blue";
   alert(test1);
}
Example of JavaScript Local and Global Variables:

<SCRIPT LANGUAGE="JavaScript">
<!--
function function_1 ()
{
var x = 5;
document . write ("<br>Inside function_1, x=" + x);
function_2 ();
document . write ("<br>Inside function_1, x=" + x);
}
function function_2 () {
document . write ("<br>Inside function_2, x=" + x);
}
x = 1;
document . write ("<br>Outside, x=" + x);
function_1 ();
document . write ("<br>Outside, x=" + x)
-->
</SCRIPT>

0 comments:

Post a Comment

 
Top
Blogger Template