You'd be surprised how much the simple things mean until they're not there anymore. In Javascript or just code all together, one of the most common things done by a developer is variable assignment. It goes over many peoples head how vital this is to the coding process.
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.
What is Variable Assignment ?
It's quite simple. You just set your code expression equal to a word that best describes it. This way you can store the information the expression provides all into one word. It's just like a storage box that stores data so that Javascript can keep it in its memory so that we can access it later.
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).
Now how do we write out variable assignment ?
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.
Resources:
Replit
Top comments (0)