19
Variables and constants in JS
Variables are like storage containers and are hence used to store data to facilitate a web app to run better.
To declare a variable we use let
keyword as follows:
let name = "Sumit"
(You may see variables being declared using the var
keyword but using let
is newer way and better practice).
- We can also declare multiple variables on a single line. (Try doing this by yourself).
- We can also change the data held in a variable. This, in fact is the primary reason why variables are so useful. Think of it as a bin holding some data, then that data being taken out and thrown and using that same bin to store some new data.
- For instance, we had earlier declared a variable '
name
' which is currently storing 'Sumit'. We can now store any new data in that same variable calledname
like:name = "Paris"
. Now our variable is storing new data called "Paris" instead of the old "Sumit". - What we can't do is declare the same variable twice as that would throw error as shown below:
- A variable name should give an insight into what's the use of the variable. E.g don't say
let recipeName = "London"
😅 - Lowercase and uppercase variables are two different variables as shown below:
- The name must contain only letters, digits, or the symbols $ and _.
- The first character must not be a digit
- There are reserved keywords like
let
,const
etc and these shouldn't be used as variable names
Constants are variables that can't change their values once assigned i.e., after we assign some value to a constant, we can't assign new value or in other words they are constant (hence the name!).
They are declared using the keyword const
as shown in the image below:
If we now try to re-assign a value to a constant, we'll get an error like:
That's it for today folks. This is an ongoing series of articles, so stay tuned for more.
Also, since you're reading till here, I'm assuming you found this to be of value, so please like this article and share it with your friends and as always drop your comments down below.
~ Sumit Saurabh.
19