Variables are blocks for storing data.
3 ways to declare variables
- var
- let
- const
Declaring the javascript variable
Variable is declared when we create the variable. You can declare the javascript variable with let or var keyword.
var name;
or
let name;
After the declaration, the variable has no value it is undefined.
To assign a value to the variable, use the equal sign:
name = “awias butt”
Now it is a variable with type string.
Using var
The var is the oldest keyword to declare a variable in JavaScript. The scope of the var keyword is the global or function scope. It means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function.
Example: Variable ‘number’ is declared globally. So, the scope of the variable ‘number’ is global, and it can be accessible everywhere in the program.
<script>
Var number = 10;
Function call(){
Console.log(number);
}
Call();
Console.log(number);
</script>
Output
10
10
Using let
The let keyword is an improved version of the var keyword. It can’t be accessible outside the particular block or function.
<script>
function call(){
let number = 10;
Console.log(number);
}
Console.log(number);
</script>
Output
10
ReferenceError: number is not defined
Using const
The const keyword has all the properties that are the same as the let keyword, except the user cannot update it. When users declare a const variable, they need to initialize it, otherwise, it returns an error.
Top comments (1)
Thanks 👍🏾.. I'm an very beginner at learning JavaScript