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"
Examples:
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 a global variable inside the function. So local variables of the 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";
document.write(my_var)
my_function();
</script>

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.
<html>
<head>
<title></title>
<script type="text/javascript">

my_var="Hello World";
document.write(my_var)

</script>
</head>
<body>
<a href="javascript:void(0);" NAME="My Window Name" onClick=window.open("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">
document.write(opener.my_var)
</script>

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";
document.write(typeof(my_var))
Output of above code is string. Similarly based the type of variable, we will get outputs as
string, number,boolean,object etc.
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    Post your comments , suggestion , error , requirements etc here .




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer