Previous | Home | Next |
A JavaScript variable is simply a name of storage location or identifier, associated with a value. The variable can be seen as storing, or holding the value, and also a variable contains a value, such as "hello" or 5.
There are two types of variables used in JavaScript :
- local variable
- global variable.
Some rules which can be declare in JavaScript variable ( it is called identifiers ).
- x and X are different variables in Javascript so javaScript variables are case sensitive,
- Name start with a letter (a to z or A to Z), and underscore( _ ), or dollar( $ ) sign.
- After first letter we can also use digits (0 to 9), (for example value1)
" Before you use a variable in a your JavaScript program you have to must use var keyword to declare Variable "
Example
<html> <body> <script> var x = 50; var y = "prasant"; var z=x+y; document.write(z); </script> </body> </html>
Output
Local variables : Variables that exist only inside a function are called Local variables. They have no presence outside the function. The values of such Local variables cannot be changed by the main code or other functions.
Example :
<html> <head> <script> function abc() { var a= 200;//local variable var b= 300;//local variable var c= 400;//local variable var x = a+b+c; document.write(x); } abc();//calling JavaScript function </script> <head> <html>
Output :
Global Variables : A global variable has global scope which means it is defined everywhere in your JavaScript code, Their values can be changed anytime in the code and even by other functions.
Example :
<html> <head> <script> var x=200;//gloabal variable var y=400;//gloabal variable var z=500;//gloabal variable var w= x+y+z; function a() { document.writeln(x); } function b() { document.writeln(y); } function c() { document.writeln(z); } function d() { document.write("<br>sum of numbers is:"+w); } a();//calling JavaScript function b(); c(); d(); </script> <head> <html>
Output :
200 400 500 sum of numbers is:1100
Previous | Home | Next |