Declaring variables in JavaScript
Defining variables in JavaScript is pretty simple. Let’s say you want to create your pet’s name as a variable.
let myPetName = 'cujo';
P.S. I don’t really have a dog. So, excuse me if the name doesn’t really gel well with the real time pet names :)
Let’s look at the four parts of the syntax:
- let is a keyword that is used to declare variables.
- myPetName is the variable name here. “cujo” is the value, which is assigned to the variable. Every value has a data type. Here, in this example, it is string.
- ; (semicolon) is to terminate as well as execute the statement.
If you are familiar with other programming languages, you must be wondering that why aren’t we explicitly stating the datatype. In JavaScript, it’s dynamic. This means that when you assign the value to a variable, the value itself decides the data type. In the example above, the name is a string, hence the data type will automatically be string.
Under-the-hood mechanism
Let’s check under the hood and understand what really happens when we define a variable.
‘cujo’ is stored in a memory location on your computer and the address of that location is stored in your variable name. It’s important to know that it is the address that is used every time we reference a variable and not the actual value.
So, how do we retrieve the value back from the variable. Let’s use debugging so that you can print the variable value. By calling alert(myDogsName); we get the address and then the value corresponding to the address, which in this case is ‘cujo’.