Variables in JavaScript (var/let/const)



 want to know about JavaScript follow the link

Variables are simply the name of the storage location. There are two ways we define variables more precisely they are known as the scope of the variable. Scope determines the accessibility (visibility) of these variables. they are:- local variable and global variable.

When variables are defined inside a function then they cannot be used outside of it, these types of variables are called local variables, and when variables are declared outside the function then we can use them anywhere these are global variables.

Rules for creating variables:-

  • The variable name cannot start with a number.
  • The variable name cannot be a reserved keyword.
  • The variable name can start with letters.
  • The Variable name can start with an underscore( _ ).
  • The variable name can start with $.

There are three parts for Variables to use in the program.

  1. Variable Declaration
  2. Variable Definition/ Assigning values.
  3. Variable Call/use

Rules for declaring variables

There are three keywords that are used to declare variables. They are:-

  1. var
  2. let
  3. const

Let’s discuss them briefly:

while using var we can change the value assign new values to it. It is a function-scoped variable which means we could use it inside a function. We could also use var globally. Let’s see a simple example:-



var in JavaScript

let is used to declare or redeclare a variable when we want to use it inside any block (if / for / while / etc…). Let’s see a simple example:-



When we want the value of a variable to be fixed then we use const as we cannot change the value of const once it gets assigned. Let’s see a simple example:-



JavaScript const

Note:- JavaScript const variables must be assigned a value when they are declaredelse they’ll show an error.

Rules for Variable Definition/ Assigning values.

For definition/ assigning values to the variable, we need to give a keyword (one of the above three (let/const/var)) then write the name of the variable according to the protocols (explained above).

After we have declared the variable and assigned the values, we are now good to go for the Variable Call/use wherever it is needed. which means we can now use the variable to either modify or print it.

Get to know about JavaScript registration form validation then Click here

You Might Also Like

0 comments