Variables are essential for data storing in memory and utilising as per requirement. Variable is a container. In this container we can store data.
var is the identifier and fruit_name is the reference name. It is a statement, so ends with a semicolon.
Note: We can use any name for variable declaration but the condition is it should not contain space and special characters. However, we can use – and _ in the variable name.
Following variable declaration is not valid.
var fruit name; ————>Invalid(Because it has space in the name)
Getting back to the example, ” var fruit_name; ” what exactly is happening here!! At the backend, a memory is allocated whose reference name is ‘fruit_name’.
Note: The above variable declaration var fruit_name is an empty variable because it does not hold any data.
How can we store data inside a variable declaration?
To store data inside a declared variable we use assignment operator “=”
In the above example, we have first declared the variable using the identifier ‘var’ and then in the second line we have assigned string value ‘Orange’ to the declared variable.
The above line of codes can also be written in a single line as below.
If we can define a variable and assign value to it in one sentence then why should we go for declaring empty variable first and then assigning value?
The reason is, in real project environment is some cases, we may need to define empty variable first and later on data from other source might be assigned to it.
But for now remember both ways of declaring variable.