Javascript Variables
What is a variable?
Variable means anything that can change. In JavaScript, variables are used where the variable stores the data value which can be changed later.
In short, variables are used to store value data
How to declare a variable
The JavaScript variable can be declared in three ways which are as follows
- var
- let
- const
Declare a variable with var
In the following example, a, b, and c are variables, which are declared with the var
keyword
Example
Edit it yourselfvar a = 4;
var b = 4;
var c = a + b;
document.write(c);
Declare a variable with let
In the following example, a, b, and c are variables, which are declared with the let
keyword
Example
Edit it yourselflet a = 4;
let b = 4;
let c = a + b;
document.write(c);
Declare a variable with const
In the following example, a, b, and c are variables, which are declared with the const
keyword
Example
Edit it yourselfconst class1 = 6;
const class2 = 6;
let std1 = class1 + class2;
document.write(std1)
In this example, class1, class2, and std1 are variables.
These are constant values and cannot be changed.
The variable std1 is declared with the let keyword.
Variable Scope
What is JavaScript Variable Scope
The scope of a variable is the area of your program in which it is defined There are two types of variables in JavaScript, which are as follows
- Global Variables
- Local Variables
- We will now discuss JavaScript Variables Scope in detail. Which can be seen as follows.
Global Variables
The variables declared from any function are called global variables.
This variable scope can be accessed anywhere in the JavaScript code, even within any function.
Local Variables
Variables declared within a function are called local variables of that function.
They can only be accessed in a function where they have been disclosed but not outside.
- In the next Lecture we will discuss in detail the JavaScript Variable Scope.