advanced
   

SocialTwist Tell-a-Friend

Introduction Syntax Placement Variables Operators Popup Boxes If Else Statement Switch Case while Loop for Loop break continue Function Array DOM Events Date String Form Validation

JavaScript : Variables

A variable's purpose is to store information so that it can be used later. It is ideal to name a variable something that is logical, so that you'll remember what you are using it for. For example, if you were writing a program to calculate the speed, it could be confusing if you called your variables inputOne, inputTwo, result because you may forget which one is the distance, which one is the time, and which one is the speed. A more logical approach would be to name them just that: distance, time, speed.

Naming Conventions: Basic Rules

  • Variable names are case sensitive (myVal and MyVal are two different variables
    in Javascript)

  • They must start with a letter or underscore ("_")
  • Subsequent characters can also be digits (0-9) or letters (A-Z and/or a-z).
  • We cannot use reserved word as a variable name
  • Variable name cannot contain space character
How to Create Variable To declare a new variable called age using var keyword
Example:
var age ;
Intializing the Variable
var age=30 ;
var name="Abhishek" ;

If I declare a variable in one statement and later want to assign a value to it,the
sequence of statement is :

 var age ;
 age=30 ;
Datatype In JavaScript


TypeExampleDescription
String"Abhishek"A series of characters inside quote marks
Number7.9Any number not inside quote marks
BooleantrueA logical true or false
NULLnullCompletely devoid of any value
Objectarrays A software "thing" that is defined by its properties and method
Function sqr A function defintion

Example
<html>
<head>
<title>Variable Example</title>
</head>
<body>
<script type="text/javascript">
var FirstName;
FirstName="Abhishek";
document.write(FirstName);
document.write("<br />");
var LastName="Sinha";
document.write(FirstName+" "+LastName);
</script>
<p> I am from B.H.U</p>
</body>
</html> 
Output
Abhishek
Abhishek Sinha

I am from B.H.U
Scope of Variable

Global Variable
When you declare a variable by assignment outside of a function, it is called a global variable, because it is available everywhere in the current document


Local Variable
When you declare a variable within a function, it is called a local variable, because it is available only within the function.


Previous            Next
Contact Us
Your Ad Here