Welcome visitors of MIC Computer

Welcome to my blog. With this blog you can post your question about computer and programming for absolutely free (free consultation sponsored by MIC Computer).. Well what are you waiting for just feel free to post your question or share with me about your computer / programming experience

Wednesday, September 14, 2011

Javascript variable

As any other language, javascript is also has variables. Javascript is case sensitive, so the variable name is case sensitive too. So y variable is different with Y. Javascript variable name must begin with letter or underscore.

This is how you declare javascript variable:
Local Variable:
Has to be declare inside a function. Example:
<script type="text/javascript">
function print_hello()
{
var somewordempty;
document.write("empty " + somewordempty + "<br/>");
somewordempty="assign value to empty";
document.write(somewordempty + "<br/>");
var somewordassign ="assigned variable";
document.write(somewordassign + "<br/>");
}
print_hello();
</script>
Global Variable:
Has to be declare outside functions. I hope this example can make you understand. Example:
<script type="text/javascript">
var globalvar=" <br/>should be global";
document.write(globalvar);
function print_hello()
{
var globalvar="<br/>should be local, because although it have the same name but it declares under a function";
document.write(globalvar);
}
print_hello();
document.write(globalvar + " because it outside the function");
</script>
Let's try to call it again and you will get the same value as above. Because global variable is destroy when we close this page.
<script type="text/javascript">
document.write(globalvar);
</script>

No comments: