Subscribe to PHP Freaks RSS

Use 'let' and 'const' instead of 'var'

syndicated from planet-php.net on August 29, 2018

If you are writing javascript code for Node.js, Babel, Typescript or if you can target up-to-date browsers, chances are that your environment supports the let and const keywords.



If this is the case, you should stop using var and use let and const exclusively. Here’s why:



  • var uses something called ‘hoisting’, which can lead to unexpected results.
  • let and const are both block-scoped. Which means you can declare them in for loop or if statement, and they will only be valid for that block. This helps with spotting bugs and makes your code more robust.
  • const prevents variable re-assignment.

Unless you are targetting older environments, there’s no need anymore to use var.



But the reason I’m writing this post is because I often see let used where const is more appropriate.



When to use const



const stands for “constant”. In a lot of sources, I see that interpreted as something that should never change, maybe even something that should be declared as uppercase:



/* Hear ye, Hear ye! I declare a constant! */
const MY_MAGIC_VALUE = 5;


However, const really should be your default for most cases. Take the following examples:



const user = {};
user.firstName = 'Evert';
user.lastName = 'Pot';


When you create an object with const, you can still change it’s contents. const only prevents re-assigning, it doesn’t make the entire object immutable.



const users = [];
users.push(user);


Same for the array. Even though I’m adding something to the array, the identity of the array remains the same. const works.



for(const item of users) {

console.log(user);

}


In the case for the for loop. Every iteration of the loop is a new ‘block scope’, so I am in fact able to re-create a new constant for every iteration.



It’s useful to use const instead of let, because it prevents you from accidentally overwriting variables. So a good rule of thumb is:



  1. Stop using var.
  2. Use const by default, everywhere.
  3. Use let if you must.

When to use

Truncated by Planet PHP, read more at the original (another 4513 bytes)