JavaScript Variable

    JavaScript variable

    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.

    1. var x = 50;
    2. var _value=“Jony”;

    Incorrect variables

    This is an incorrect way to declare a variable.

    1. var 123=70;
    2. var *aa=570;

    JavaScript variables examples

    The basic example of a variable.

    1. <script>
    2. var x = 50;
    3. var y = 20;
    4. var z=x+y;
    5. document.write(z);
    6. </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:

    1. <script>
    2. function number(){
    3. var num=50;//local variable
    4. }
    5. </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:

    1. <script>
    2. var number=50 ; // gloabal variable
    3. function num1(){
    4. document.writeln(number);
    5. }
    6. function num2(){
    7. document.writeln(number);
    8. }
    9. num1(); //calling function
    10. num2();
    11. </script>

    Learn More :

    JavaScript Comment and Syntax