Variables in JS

Variables in JS

What are Variables?

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by calling the container. Javascript includes variables that hold the data value and can be changed on runtime as javascript is a dynamic language.

Declaration of variables :-

  • In JS, users can declare a variable using 3 keywords that are var, let, and const. JavaScript will automatically determine the type of the variable according to the value passed.

Javascript Identifiers

All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum).

There is a general rules for constructing names for variables (unique identifiers) are :-
  • Names can contain letters, digits, underscores(_), or dollar signs ($).
  • Names must begin with a letter, $ or _ .
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (like JavaScript keywords) cannot be used as names

- VAR

  • It can be updated and re-declared into the scope.
  • The scope of a var variable is functional scope.

- LET

  • It can be updated but cannot be re-declared into the scope.
  • The scope of a let variable is block scope.

- CONST

  • It cannot be updated or re-declared into the scope.
  • The scope of a const variable is block scope.

Scope in JS

Local Scope Variables

  • Any variable that is declared inside a function is said to have Local Scope.
  • You can access a local variable within a function.
  • You can not access it outside the function.

Scope.jpg

Global Scope Variables

  • Any variable declared outside of a function is said to have Global Scope.
  • A variable that can be accessed anywhere in the program is known as a variable with global scope.
  • It can be defined using any of the three keywords let, const, and var.

Scope.jpg