Variables.Js

Variables.Js

·

2 min read

Variables Explained for Beginners.

<Script> Hello World!</Script>

What is a Variable

Let's first start with what is a variable. Mdn says a Variable is a reference name for a value. In civilian lingo, a variable is a way to save data to be used later.

Declaring Variables

When creating a variable good practice is to declare the variable. To declare the variable use one of the three:

var

let

const

Now let's dive into this. When declaring a variable you have to decide whether the value of your variable will change or stay the same. If you intend to change the value you have two options to choose from. You can either declare with [var] or declare with [let]. Say you are using a [for loop] method for the length of an array and would like to increment by 1 each time you go through the function. [var] or [let] will be your tools. Now with that being said the best out of both of those will be [let]. Choosing [var] can cause some future issues with your code and make it very hard to debug. Using [let] is the safest way to code a changing value.

If you are creating a variable with a value that you wish to stay the same throughout your code then [const] is what you will use to declare your variable. The value of your variable can not be changed.

Naming Variables

When naming your variables I suggest that you name them something short and easy to follow in your code. If your variable is a selector for the nav then keep it short and short and name it [const navBar]. Naming it something long and nondescriptive can make it confusing when you go over your code and decide to change things around or debug.

Assigning Variables a Value

When assigning a variable a value there is only one appropriate operator. If you guessed the assignment operator [=] you are correct!

[const navBar = document.querySelector('.nav')]

[let weeklyEarnings = dailyEarning * 5]

The only way a variable can know its value is by using the assignment operator. To the left of the operator, we declare and name our variable. On the right of the assignment operator, we have the value. Now [navBar] knows its value and also [weeklyEarnings].

Conclusion

Remember to name your variable something descriptive and short, declare your variable using [const] or [let], and use your assignment operator and you will be golden.

Resources:

https://developer.mozilla.org/en-US/docs/Glossary/Variable