Variables

Variables are like containers for storing values. You can place data into these containers and then refer to the data simply by naming the container.

All variables do have names which are unique and these names are called identifiers, identifiers are case sensitive.

There are some rules while declaring a JavaScript variable.

  • A variable name must start with a letter, underscore(_), or a dollar sign($).
  • After the first letter/underscore/dollar, we can use numbers.
  • A variable name can’t contain spaces.
  • Reserved words(e.g., abstract, final, etc.) are not allowed.
  • Variables in JavaScripts are case sensitives.

How to declare a variable in JavaScript?

We can declare a variables in three different ways by using var, let and const keywords. Each keyword is used in some specific conditions.

In these example we use “var” keyword

var demo;

After the declaration, we can use the equal(=) sign to assign value to the demo variable

var demo = 33;

In the above example we use var is the keyword to declare the variable, and the demo is the name of the variable, and the assigned value is 33.

We can declare multiple variables in one line:

var name = "Surya", role = "DSP", salary = 50000;
var name = "Surya",
role = "DSP",
salary = 50000;

What is a scope of a variable ?

Scope is defined as the accessibility/visibility of variables.

Each JavaScript function creates a new scope to the variables.

What are the types of scope in JavaScript ?

There are two types of scopes in JavaScript

1. Local Scope

2. Global Scope

Local Scope:

Local scope is also known as block scope. A block is the code found inside a set of curly braces {}. Inside those curly braces we typically write out the business logic for our functions, statements and so on.

Global Scope:

In global scope, variables are declared outside of blocks or outside the local scope. These variables are called global variables. Because global variables are not bound inside a block, they can be accessed by any code in the program, including code in blocks.

Example of Local and Global:

<!DOCTYPE html>
<html>

<body onload=checkscope();>
    <script type="text/javascript">
        <!--
        var demo = "this is global variablel"; //this is global variable
        function checkscope() {
            var demo = "this is local variable"; // this is local variable
            document.write(demo);
        }
        //
        -->
    </script>
</body>

</html>

Output:

Variables