
Using a JavaScript variable we can store a value in a variable.
JavaScript variable types
There are two types of variables local and global in JavaScript. It is also known as JavaScript variable scope.
- local variable
- global variable.
Remember some variable declaring Point:
- Variable names should contain digits, alphabets and underscore and dollar characters.
- Start a variable with an alphabet.
- Uppercase and Lowercase are different. This means “number” and “NUMBER” are different.
- We can not use keywords as variable names. For example while, for etc.
- Only underscore is allowed. It should not contain a special symbol or blank space.
- Variable names should not be more than 255 characters.
- “var” keyword is used to declare variable names in JavaScript.
Correct variables
This is the correct way to declare a variable.
- var x = 50;
- var _value=“Jony”;
Incorrect variables
This is an incorrect way to declare a variable.
- var 123=70;
- var *aa=570;
JavaScript variables examples
The basic example of a variable.
- <script>
- var x = 50;
- var y = 20;
- var z=x+y;
- document.write(z);
- </script>
examples Output:
70
JavaScript local variable
When we define a variable inside a block or function then it is known as a local variable. We can only access within a block or function only.
.For example:
- <script>
- function number(){
- var num=50;//local variable
- }
- </script>
JavaScript global variable
When we define a variable outside a block or function then it is known as a global variable. We can access it from any function.
For example:
- <script>
- var number=50 ; // gloabal variable
- function num1(){
- document.writeln(number);
- }
- function num2(){
- document.writeln(number);
- }
- num1(); //calling function
- num2();
- </script>
Learn More :