Let is the new Var





When we learn a programming language, several basic concepts appear, such as declaring variables, and they are so simple that we can start using them without any knowledge of their functioning.



I know what you thought: “Why are you wasting time writing to us about this?”



Because I think it’s worth spending a few minutes to better understand these elements, what is their meaning and how we should use them. This will help you avoid some common mistakes and write code better.



In this article, we will focus on how to store data in JavaScript.



Var



"Once upon a time in a distant galaxy ..." the only option for defining variables in JavaScript was to use the var keyword, and that was enough to manipulate the data in the code. But with the introduction of the ES6 standard, some of the oddities and weaknesses of the old JS became pretty obvious:



  1. Scope: the var keyword allows you to define variables only in the global and local scope (or in the scope of a function). No matter how many nested blocks of code you have, there are only two of these possibilities.
  2. Constants: if you want to define something that will not change during code execution, you can only rely on the common sense of the developers. We can use some useful conventions to clarify the meaning (for example, capital letters), but there is nothing to guarantee that the meaning does not change.
  3. Overriding Variables: You can repeat the declaration of the same variable as many times as you want (in the same scope), and this is a little confusing if you want to keep the variables unique.


Definitions



Before starting with the technical stuff, let's introduce some general definitions:



A variable is a “container” in which reusable data is stored (very trivial).



Identifiers are variable names (also very trivial).



A block is a piece of code separated by a pair of curly braces ( ccskrf ), for example: if, for, function, and. etc.



Scope , determines the visibility of variables within the code. If you have any doubts, ask yourself: “Where is my variable visible in the code?”

NOTE. Please do not confuse the scope with the execution context , which is different.



** Context (or execution context) ** is the environment in which JavaScript code is executed. For simplicity, we can say that the context is the object to which the code belongs, and this is the keyword that refers to it. So ask yourself: “What object does this refer to?”



Now suppose our developer is very passionate about Star Wars (this is good), but is suspicious of new standards such as ES6 (which is bad), although it has been around for some time. Therefore, he prefers to write his code in the old ES5 style, and it will look like this:



console.log("I am a %s", jedi); var jedi = "Ani"; //   jedi    // =>  undefined function useTheForce(comeToTheDarkSide) { var jedi = "Obi-Wan Kenobi"; var jedi = "Anakin Skywalker"; if (comeToTheDarkSide) { var jedi = "Darth Vader"; console.log("I am %s", jedi); // => I am Darth Vader } console.log("I am %s", jedi); //  Darth Vader } useTheForce(true); console.log("I am %s", jedi); // => Ani
      
      





As you can see, there are three blocks of code (including global), but only two scopes. This is because the code in if brackets does not create a scope. The console will issue “I am Darth Vader” twice, and then “I am Ani” globally.



Also note that the same variable is declared twice in a row inside the function, and then again in the if statement. This means that we have the declaration of the same variable in the same scope three times, which throws an exception.



Last but not least, the output of the first log is: we print the value of our variable before defining it. This is completely legal with var and is called "hoisting".



The "climb" assumes that the declared variables and functions are physically moved to the beginning of your code. Technically, there are declarations of variables and functions that are stored in memory at the compilation stage, but remain in the code exactly where you wrote them. The fundamental importance of a lift is that it allows you to use functions before declaring them in your code.



You can read about it here .



In our example, the declaration of the variable "jedi" is placed in memory and initialized to the default value (undefined).



Let



At the moment, our developer understands that ES6 is not so bad, and he decides to give let a chance:



 console.log("I am a %s", jedi); let jedi = "Ani"; //   jedi    // => Uncaught ReferenceError:     "jedi"   function useTheForce(comeToTheDarkSide) { let jedi = "Obi-Wan Kenobi"; let jedi = "Anakin Skywalker"; // => Uncaught SyntaxError:  ''   if (comeToTheDarkSide) { var jedi = "Darth Vader"; console.log("I am %s", jedi); // =>  Darth Vader } console.log("I am %s", jedi); //  Anakim Skywalker } useTheForce(true); console.log("I am %s", jedi); // =>  Ani
      
      





But he soon realizes that he cannot just change the var keyword to let, for this some corrections need to be made:



Rise does not work in the same way: a variable is put into a state called Temporal Dead Zone * * and is not initialized until the definition is evaluated. In our example, it throws an error: reference error.



reassignment is prohibited, the definition of a variable in scope must be unique. When trying to get an error: SyntaxError.



The if statement is a valid block scope, so the jedi declaration inside it is unique.



Now the code should be like this:



 let jedi = "Ani"; console.log("I am a %s", jedi); // print jedi variable before defining it // =>  Ani (  ) : 0 function useTheForce(comeToTheDarkSide) { let jedi = "Obi-Wan Kenobi"; let jedi = "Anakin Skywalker"; if (comeToTheDarkSide) { var jedi = "Darth Vader"; console.log("I am %s", jedi); // =>  Darth Vader } console.log("I am %s", jedi); //  Anakim Skywalker } useTheForce(true); console.log("I am %s", jedi);
      
      





Const



Now that you know everything about let, it will be easy to introduce you to const . In fact, we can say that const is similar to let, but you cannot reassign another value. You also need to know that assignment is only allowed during const declarations.



 function useTheForce(comeToTheDarkSide) { const jedi = "Yoda"; if (true) { jedi = "Darth Yoda"; console.log("I am %s", jedi); // => TypeError: Assignement to constant variable. } } useTheForce(true);
      
      





Suppose in our example, “jedi” is a constant with the value “Yoda”, if we try to change the value inside the if statement, it will give us a TypeError error, and this is understandable because Yoda will never join the dark side.



Conclusion



When it is impossible to express a concept in words in languages, a new concept is introduced to fill the gap. This is correct for English ( link. ), Italian, Esperanto, evocoque (I suppose), etc. This is even more true for programming languages ​​such as JavaScript.



Now you know that you can:





My last tip is to use const as your default choice. When you need to reassign a variable, use ** let ** (as in loops). And use var when ... no, you no longer need var, really



Thanks for your attention.



Quick Javascript Questions



I'm on Twitter and VK



All Articles