Variables are identifiers for the value which means there will one unique variable of that name. JS variables are used as containers to store the value.
You can name these variables and store values in them, to refer to the value use variable name. Before using a variable, you must declare it.
Example Of Declaration of Variables
You can also declare multiple variables on a single line by putting commas in between. When you store a value inside a variable it’s called a variable initialization.
You can do store value inside a variable at the time of declaration or at any other point you want to declare it. As variables are dynamic you can change the variable value at any point in the program.
Example Of Initialization of Variables
You only need to use the ‘var’ keyword at the time of declaration no need to use it after the initialization of a variable. But if you declare a variable it will not lose its value.
JS is an untyped language, which means that you don’t have to assign a data type to every variable. If ‘a’ is being used to store an integer value that the same variable can be used to use string value.
The scope of a variable is a region of the program in which the variable is used. Like if you are declaring the variable outside the function it becomes globally available and any other function can use it, but if you declare it inside the function, I become locally available which means it is only available to that function. We will see more explanation in the following,
JS has two types of scope
- Global variable: A global variable can be defined anywhere in the program.
- Local Variable: A local variable is limited to a function.
It will be only visible within the function it was declared. function parameters are local to that function.
Example Of Global And Local Variable
Rules to write the variable name
- Names can be made up of letters, digits, underscores, and dollar signs.
- The name should begin with a letter
- Names can also begin with a dollar sign ($) or an underscore (_).
- JS is case sensitive so a and A are different.
- Reserved words cannot be used as names.