Variables
Variables are containers that you can store values in. You start by declaring a variable with the var
keyword, followed by any name you want to call it:
var myVariable;
Note: A semicolon at the end of a line indicates where a statement ends; it is only absolutely required when you need to separate statements on a single line. However, some people believe that it is a good practice to put them in at the end of each statement. There are other rules for when you should and shouldn't use them — see Your Guide to Semicolons in JavaScript for more details.
Note: You can name a variable nearly anything, but there are some name restrictions (see this article on variable naming rules). If you are unsure, you can check your variable name to see if it is valid.
Note: JavaScript is case sensitive — myVariable
is a different variable to myvariable
. If you are getting problems in your code, check the casing!
After declaring a variable, you can give it a value:
myVariable = 'Bob';
You can do both these operations on the same line if you wish:
var myVariable = 'Bob';
You can retrieve the value by just calling the variable by name:
myVariable;
After giving a variable a value, you can later choose to change it:
var myVariable = 'Bob';
myVariable = 'Steve';
Correct JavaScript variables
- var x = 10;
- var _value="sonoo";
Incorrect JavaScript variables
- var 123=30;
- var *aa=320;
Example of JavaScript variable
Let’s see a simple example of JavaScript variable.
- <script>
- var x = 10;
- var y = 20;
- var z=x+y;
- document.write(z);
- </script>
Output:
30