Variables let code harmonize and work together beautifully. Makes for much cleaner code. If you're a beginner, prepare to use variable assignment like it's your best friend. It'll make your life a hundred times easier.
Why do we need to access it you may ask ? Well lets look at an example
- We need to access the data with a simple variable so that we can do things to it like in this example remove it. Here we are selecting the main through its id and assigning it to the word 'main'. Now in the second line we can use the word 'main' to remove it from html instead of writing out the whole
document.getElementById("main"). This will be extra extra handy for when you have to do multiple things to that variable (see below for advanced example).
The two recommended methods to assign a variable are 'let' or 'const'. Followed by the name of the variable you choose and the assignment operator which is an equal sign (=). Followed then, by your expression.
Let is used to assign a variable that can be reassigned. If you're doing a long code where you would need to change the value of a variable, let allows that.
Const is used when you are certain of the value for that variable because it cannot be reassigned. If you're doing a long code and don't want to mess yourself up by accidentally reusing the same variable name for a different value, const is the way to go.
In the example above, we used let on the variable y and const on the variable x. When we tried to reassign y to a different string, it worked and the new value popped right below it. However when we tried to reassign the x, we got an error. This is because const is permanent, let is not.
More advanced example of why variables are amazing
Without the variable assignment of form, newComment and li, we would get the longest lines of code that are much more prone to errors and bugs. Because we stored those expressions into variables we get a much cleaner code that is also easier for other coders to read. Now we can give form a submit event listener, create a list and through that list give newComment text content to make a successful comment section for people to submit things into.