JavaScript variables

JavaScript variables are case sensitive. To check the variables we can use different functions like typeof, parseInt, parseFloat etc.

Basic requirements of declaring a variable.

  • Our JavaScript variables are case sensitive, so we can use lower or upper case letters
  • We can use digits from 0 to 9
  • We can use underscore _ and ampersand & in our variable
  • Space and punctuation characters are not allowed
  • First character of the variable has to be underscore or alphabet
  • No reserve words or keywords to be used as variable.

Declaring a JavaScript variable.

We can simply assign the value to the variable like this
my_var="Hello World"
Or we can exclusively declare and assign the value by using var
var my_var="Hello World"
var 2my_var='test' // Wrong , variable can't start with 2
var for='test' // Wrong, for is a reserve word 

Local & global variable

This is a good practice to use var to declare a variable. Any variable we declare in our main script will be available as global variable inside the function. So local variables of same name inside a function must be declared if they are to be used separately. Here is an example of variables used inside and outside the function.
<script type="text/javascript">

function my_function(){
var my_var=" New value "
document.write("Inside function " + my_var)

my_var="Hello World";

Accessing variables of Parent window

We can read the variables of parent window and display ( or use ) in child window after opening. Here is the code for parent window.
<script type="text/javascript">

my_var="Hello World";

<a href="javascript:void(0);" NAME="My Window Name""variable2.htm","rating","width=550,height=170,left=150,
top=200,toolbar=1,status=1");>Click here to open the child window</a> </body> </html>

Now the child window code ( variable2.htm)

<script type="text/javascript">

typeof: Checking the type of variable

We can print the type of variable by using typeof function. Here is an example.
my_var="Hello World";
Output of above code is string. Similarly based the type of variable, we will get outputs as
string, number,boolean,object etc.
Your Rating

Post Comment This is for short comments only. Use the forum for more discussions.

HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 All rights reserved worldwide Privacy Policy Disclaimer