DEV Community

ycorredius
ycorredius

Posted on

Variables in JS

JavaScript a wonderful programming that has a few unique twists to it. That especially is true when it comes to variables. There are 3 ways you can declare variable in JavaScript, using the keywords var, let, and const. Var is a variable declaration that is not recommended since var is usually hoisted in a function and yields unexpected result. Let, is the recommended alternative to var simply because the value is easily reassigned and reused through a program. In addition, is provides block level scoping that is valuable when you only need to make temporary variables with a specific context. Like let, const, is used under specific context. The main difference is that const doesn’t not allow for reassigning of name space saving. The important distinction to be made is that you are not allowed to reassign the value of const.
There is another trick neat trick that JavaScript has that is truly tricking, hoisting. Hoisting is basically how JavaScript loaded. On of the first things that is done when a JavaScript file is loaded is to load all variable declarations behind the scenes. This is an important distinction because most other programing languages load the file from the top down. So, if you use a variable before it is declared the program will not compile correctly and will result is an error. Because JavaScript hoists variables if the variable is declared it does not matter when it is called. One caveat is that it only hoist declarations and not initialization. This is where a lot of confusion comes in. Many times, people expected to data to be hoisted along with the declarations, so time is wasted on a problem without knowing the origin. It is important to understand hoisting so that you may be able to trace errors to the proper origins when those type issues arise

Top comments (0)