Var, Let in Const - Kakšna je razlika?

Z ES2015 (ES6) je izšlo veliko bleščečih novih funkcij. In zdaj, ko je leto 2020, se domneva, da se je veliko razvijalcev JavaScript spoznalo in začelo uporabljati te funkcije.

Čeprav je ta domneva delno resnična, je vseeno mogoče, da nekatere od teh funkcij nekaterim razvijalcem ostanejo skrivnost.

Ena od funkcij, ki je prišla z ES6, je dodajanje letin const, ki se lahko uporablja za deklariranje spremenljivk. Vprašanje je, v čem se razlikujejo od dobrih, varki smo jih uporabljali? Če vam tega še vedno ni jasno, potem je ta članek za vas.

V tem članku bomo razpravljali var, letin const  glede na njihovo področje uporabe, uporabe in dvigovanje. Med branjem si oglejte razlike med njimi, na katere bom opozoril.

Var

Pred prihodom ES6 so varvladale izjave. Kljub temu obstajajo težave, povezane s spremenljivkami, prijavljenimi z var. Zato so bili potrebni novi načini razglasitve spremenljivk. Najprej spoznajmo varveč, preden bomo razpravljali o teh vprašanjih.

Obseg var

Obseg v bistvu pomeni, kje so te spremenljivke na voljo za uporabo. vardeklaracije so globalno ali delujejo / lokalno.

Obseg je splošen, kadar je varspremenljivka deklarirana zunaj funkcije. To pomeni, da je katera koli spremenljivka, ki je deklarirana varzunaj funkcijskega bloka, na voljo za uporabo v celotnem oknu.

varje obseg funkcije, ko je prijavljen znotraj funkcije. To pomeni, da je na voljo in je dostopen samo znotraj te funkcije.

Za nadaljnje razumevanje si oglejte spodnji primer.

 var greeter = "hey hi"; function newFunction() { var hello = "hello"; } 

Tu greeterje globalno obseg, ker obstaja zunaj funkcije, medtem ko helloje funkcija obsega. Do spremenljivke torej ne moremo dostopati hellozunaj funkcije. Torej, če to storimo:

 var tester = "hey hi"; function newFunction() { var hello = "hello"; } console.log(hello); // error: hello is not defined 

Dobili bomo napako, ki je posledica tega, da helloni na voljo zunaj funkcije.

spremenljivke var je mogoče ponovno deklarirati in posodobiti

To pomeni, da lahko to storimo v istem obsegu in ne dobimo napake.

 var greeter = "hey hi"; var greeter = "say Hello instead"; 

in to tudi

 var greeter = "hey hi"; greeter = "say Hello instead"; 

Dvigovanje var

Dvigovanje je mehanizem JavaScript, kjer se spremenljivke in izjave funkcij pred izvajanjem kode premaknejo na vrh njihovega obsega. To pomeni, da če to storimo:

 console.log (greeter); var greeter = "say hello" 

razlaga se tako:

 var greeter; console.log(greeter); // greeter is undefined greeter = "say hello" 

Torej so varspremenljivke dvignjene na vrh njihovega obsega in inicializirane z vrednostjo undefined.

Težava z var

Obstaja slabost   var. Za razlago bom uporabil spodnji primer:

 var greeter = "hey hi"; var times = 4; if (times > 3) { var greeter = "say Hello instead"; } console.log(greeter) // "say Hello instead" 

Torej, ker times > 3vrne true, greeterje na novo definirano na "say Hello instead". Čeprav to ni problem, če želite zavestno greeterna novo določiti, postane problem, ko se ne zavedate, da je bila spremenljivka greeterže definirana.

Če ste uporabili greeterdruge dele kode, boste morda presenečeni nad izhodom, ki ga boste dobili. To bo verjetno povzročilo veliko napak v vaši kodi. Zato letin constso nujni.

Pustiti

letje zdaj raje za deklaracijo spremenljivke. To ni presenečenje, saj gre za izboljšanje vardeklaracij. Reši tudi težavo s vartem, kar smo pravkar zajeli. Poglejmo, zakaj je temu tako.

let je obseg bloka

Blok je del kode, ki ga omejuje {}. Blok živi v skodranih oklepajih. Vse, kar je znotraj zavitih oklepajev, je blok.

Torej je spremenljivka, deklarirana v bloku z let  , na voljo samo za uporabo v tem bloku. Naj to pojasnim s primerom:

 let greeting = "say Hi"; let times = 4; if (times > 3) { let hello = "say Hello instead"; console.log(hello);// "say Hello instead" } console.log(hello) // hello is not defined 

We see that using hello outside its block (the curly braces where it was defined) returns an error. This is because let variables are block scoped .

let can be updated but not re-declared.

Just like var,  a variable declared with let can be updated within its scope. Unlike var, a let variable cannot be re-declared within its scope. So while this will work:

 let greeting = "say Hi"; greeting = "say Hello instead"; 

this will return an error:

 let greeting = "say Hi"; let greeting = "say Hello instead"; // error: Identifier 'greeting' has already been declared 

However, if the same variable is defined in different scopes, there will be no error:

 let greeting = "say Hi"; if (true) { let greeting = "say Hello instead"; console.log(greeting); // "say Hello instead" } console.log(greeting); // "say Hi" 

Why is there no error? This is because both instances are treated as different variables since they have different scopes.

This fact makes let a better choice than var. When using let, you don't have to bother if you have used a name for a variable before as a variable exists only within its scope.

Also, since a variable cannot be declared more than once within a scope, then the problem discussed earlier that occurs with var does not happen.

Hoisting of let

Just like  var, let declarations are hoisted to the top. Unlike var which is initialized as undefined, the let keyword is not initialized. So if you try to use a let variable before declaration, you'll get a Reference Error.

Const

Variables declared with the const maintain constant values. const declarations share some similarities with let declarations.

const declarations are block scoped

Like let declarations, const declarations can only be accessed within the block they were declared.

const cannot be updated or re-declared

This means that the value of a variable declared with const remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const, we can neither do this:

 const greeting = "say Hi"; greeting = "say Hello instead";// error: Assignment to constant variable. 

nor this:

 const greeting = "say Hi"; const greeting = "say Hello instead";// error: Identifier 'greeting' has already been declared 

Every const declaration, therefore, must be initialized at the time of declaration.

This behavior is somehow different when it comes to objects declared with const. While a const object cannot be updated, the properties of this objects can be updated. Therefore, if we declare a const object as this:

 const greeting = { message: "say Hi", times: 4 } 

while we cannot do this:

 const greeting = { words: "Hello", number: "five" } // error: Assignment to constant variable. 

we can do this:

 greeting.message = "say Hello instead"; 

This will update the value of greeting.message without returning errors.

Hoisting of const

Just like let, const declarations are hoisted to the top but are not initialized.

So just in case you missed the differences, here they are:

  • var declarations are globally scoped or function scoped while let and const are block scoped.
  • var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.
  • They are all hoisted to the top of their scope. But while var variables are initialized with undefined, let and const variables are not initialized.
  • Čeprav je varin letga je mogoče deklarirati, ne da bi ga bilo treba inicializirati, ga constje treba med deklaracijo inicializirati.

Imate kakšno vprašanje ali dodatke? Prosim obvestite me.

Hvala za branje :)