If you want to store a value, then for this you have to create a variable. This concept is the same in all programming languages (JavaScript, PHP, C, etc.).
A variable is like a box in which you can insert value and by the time your program executes, this value remains in the memory of the computer.
If you want, you can also store it permanently. The way to create variables in each programming language can be different. But there is always a single intention behind creating variables and that is to store the value and perform some operations on it.
JavaScript Data Types
Creating variables in JavaScript is different from common languages. You do not need to define a data type to create variables in JavaScript.
The data type of the JavaScript variable automatically decides on the base of the value that you put in the value variable. Therefore it is considered very easy to create variables in JavaScript. Before you create variables, let’s learn about some rules for creating variables in JavaScript.
Example
1 2 3 |
var pi = 3.14; var person = "Jony Rana"; var answer = 'Yes I am!'; |
Creating JavaScript Variables
Var keyword is used to create variables in JavaScript.
Syntax
1 |
var varName = value; |
Rules for a JavaScript Creating Variable
- The name of the variable must begin with a letter, underscore or $ sign.
- Numbers (1,2,3,4,5,6,7,8,9) can also be used in variable names.
- JavaScript Variables are case sensitive. That is, Age and age will be considered two different variables.
An interesting concept is found in JavaScript. It is optional to add a semicolon after any statement in JavaScript. If you do not add semicolon after a statement, errors are not generated.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<html> <head> <title>JavaScript variables demo</title> </head> <body> <script> // Creating variable var age=25; // Printing variable value document.write("Age is: "+age); </script> </body> </html> |
Types of Variables in JavaScript
JavaScript has two types of variables. These are categorized according to the scope.
JavaScript Local Variables
JavaScript Local variables are those variables whose scope is limited to a function. Such variables are created inside a function and they work only in that function. You cannot use these variables outside the function.
They work only in the block or function in which these variables are created. This is called their scope. If you try to access local variables outside their scope then the undefined variable error is generated.
JavaScript Global Variables
JavaScript Global variables are variables whose scope is in the entire program. Such variables are created at the beginning of the program and you can use them anywhere in the whole program. The scope of such variables is in the whole program.