Variables I - Beginner's JS
Imagine a home without plates. After cooking some delicious stewed beans and rice, you'd want to keep it in something you can use without making a mess. Perhaps, you'd like to save some for later. But how can you do that without ✨plates✨ or 🌈storage containers🌈? You would most likely have to either eat it directly from the pot or take some in your hands and eat it right away before it falls out.
A program without variables is somewhat similar. Variables are placeholders or containers used to store data. Generally, we declare variables when we need to capture and use data later in the program. Like a house without plates, if we created a program without variables, we wouldn't be able to keep the data for another instance. Instead, the information would be lost and inaccessible.
Consider the following:
10 * 3;
The code above shows the calculation of 10 times 3. Logically, we know the result of this calculation is 30. But, there's no way we can save the result. Instead, it's just...processed and forgotten.
To avoid this from happening, a programmer would have to create a special container used specifically for storing the data he needs to reference later in his program.
var result = 10 * 3;
Now that we have the result stored in the variable 'result', we can use this information further in our program if we wish.
console.log(result); // Displays: 30
"Come here, Johnny!" 🚶🏽♂️
"Sit, Bruno!" 🐕
"Fetch, boy!" 🐶
"Pass me my sword!" 🤺
All of these are specific commands that are executed by the ones being commanded.
When declaring a variable, we use the keywords
Consider the following:
var myage; let birthyear;
Creating variables are...pretty simple. You can name it anything you want, with a few conditions, of course.
Firstly, you cannot use special characters, spaces, symbols or punctuation. 'Michael's Age', for example, will definitely not work as a variable.
Your variable name must begin with either a letter or an underscore. Definitely avoid using numbers as the first character.
Get familiar with some of the JS reserved words. These words cannot ever be used as variables and they already exist with it's own special functionality. Here's a list of keywords you should look out for.
Besides the few points above, you can go ahead and name your variables whatever you want to name it. Except, for the sake of the other people reviewing your code, please name the variables based on what you're storing inside. 🙂
Have anything else to add? Let me know! And don't be afraid to like this story. You can also ask me questions and I won't hesitate the help! 👍🏾