JavaScript tutorial-variables and datatypes


JavaScript variables and data types

-Variable
Variable is what the program used to store any values in computer’s memory.

-Data type
Data types of variables tell the computer to store different types of values such as number, text, true/false…They also inform the computer to reserve the different memory’s spaces for those variables. JavaScript recognizes the following types of data:
· Numerical values such as 1,2,3,23.5.56.333
· Logical values such as true or false
· Strings/Textural values, such as "Hello"
· null value which means nothing

-Naming variables
The names of variables must conform to the following rules:
· They must start with a letter or underscore ("_")
Subsequent characters can also be digits (0-9) or letters (A-Z and/or a-z).
Note: JavaScript is case-sensitive. This means that the variables named myname and Myname are different.

-Declaring variables
Variables can be declared using var keyword. Variables declared with var keyword can accept any value such as text, number, true/false or null. JavaScript understand variables in two levels:
-Local level: variables that are declared in function are called local variables and can only be accessed in that function.
Example:
<HTML>
<HEAD>
<SCRIPT>

<!--
function sum(){
var a=10;
var b=20;
 return(a+b);
}
document.write(“Total=” +sum());
-->
</SCRIPT>
</HEAD>
<BODY bgcolor=”green”>
</BODY>
</HTML>

-Global level: variables declared out of a function in <Script> and </Script> section are treated as global variables and can be accessed anywhere in the page.
Example:
<HTML>
<HEAD>
<SCRIPT>
<!—
var a;
var b;
function sum(){
 a=10;
 b=20;
 return(a+b);
}
document.write(“Total=” +sum());
-->
</SCRIPT>
</HEAD>
<BODY bgcolor=”green”>
</BODY>
</HTML>




Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.