Variables in JavaScript

Variables in JavaScript

·

2 min read

what is variable?

The word variable means that can vary. variable is a container for storing data Javascript variable can store any data values (e.g., a number, a string,a boolean,etc)

Screenshot 2022-09-10 141300.png

How variable is created?

variable is created using var, let, const keywords

Screenshot 2022-09-10 141704.png

Difference Between var ,let,const?

when to use which keyword for a variable

differencebetweenvariablekeywords.png

Var

when we write looping code like this

vareample.png

varkeyword.png

The end of the code will show “after loop 5”. Even though i variable just declare in looping for. This happen is because in JavaScript, syntax var runs on the function scope. Which means that variable we declare in a function as long as they are still in the scope of the function.

let

To find out about the let syntax, I will make a loop code like in the first case. However, in this code I will use the let i syntax.

let.png

Unlike the var syntax, if the code is executed it will produce an error in the form of “ReferenceError: i is not defined” which indicates that the variable i has not been declared. Even though I declared the variable i in the loop for. This is because the let syntax is a block scope.

Const

Const has the same properties as let only, if we declare a variable with const syntax, we cannot reassign the value of that variable.

const.png

In the first condition (using the let syntax), the final result of variable i is 2. Whereas in the second condition (using the const syntax), it will produce error “TypeError: Assignment to constant variable.” which indicates that variable i cannot be reassigned.

conclusion

The var syntax shows that variables declared with var syntax can be reassigned and can be used in the function scope.

The let syntax indicates redeclaring a variable in the same block is NOT allowed and can only be accessed in a block scope.

The variables declared with the const cannot be reassigned.