Variables work like a container for storing data. It also can be changed depending on the condition of a program.
There are four ways to declare variables, they are –
1. Using Var
In this method, we declare a variable with
var symbolic name.
var a = 6; var b = 8; var c = a+b;
In this example, a, b and c are the variables declared with
2. Using Let
Let is also a reference to declare a variable.
let a = 7; let b = 8; let c = a+b;
Same as before, here a, b, and c are the variables. And those values can be changed.
3. Using Const
const sub1 = 3000; const sub2 = 2000; let totalSub = sub1 + sub2;
Here we have declared sub1 and sub2 variables with the
const keyword. So, we can not change the value of that two variables. But after that totalSub is declared with
let and it can be changed.
4. Using Nothing
a = 3; b = 4; c = a+b;
- Global Variable – A global can be created outside the function. So a global variable is having global scope. It also can be defined from anywhere in your program. We also can access it from anywhere.
- Local Variable – We can create a local variable inside a function so it is having a local scope. And, we can not access its parameter outside the function.
- We can’t use space in variables.
- We can start a variable using letters, underscore(_), or a dollar sign($).
- The name of a variable can only contain letters, numbers, underscores, or dollar signs.
- The variable names are case-sensitive.
what is the difference Between var and let?
First of all,
var allows you to redeclare a variable, whereas
let does not permit you to redeclare a variable.
Furthermore, let doesn’t support hoisting, but hoisting occurs in var.
If we declare a variable using
var and do not assign any value to the variable it will return undefined. But, when we declare a variable using
let in a similar way, it will return a reference error.
If you have any queries related to this article, feel free to comment down below.