To reassign a variable, you need to first declare a variable with let. Then, you assign another variable to it somewhere else in your code. This process is also called reassignment.
let name = 'Zell'name = 'Vincy'Why you should not reassign
There are two reasons:
- Reassignments create complicated code
- You might change external state accidentally
Reassignments create complicated code
When you create a variable with let, you tell your brain that the variable is going to change later. It needs to keep track of potential changes down the road (which can be taxing).
Imagine a colleague of yours changes her hairstyle everyday. Letโs say she comes in with bangs on Monday; braids on Tuesday; short hair on Wednesday; a waist-length, bright-pink wig on Thursday; and a shaved head on Fridayโฆ
Creating and tracking changes with let is similar (but less extreme) compared to tracking your colleagueโs hair over the days. Itโs tiring. Itโs taxing.
This is the first reason why you should not reassign. For examples, check the โwhat to do insteadโ section. Youโll see why code that requires reassignments are more complicated than code that donโt use reassignments.
You might change external state accidentally
How do you reassign a value to a variable? You write variableName, followed by =, followed by your new value:
variableName = 'new value'This seems okay at first glance, but it isnโt.
How do you know if your variable is scoped locally to the function youโre in, in this line of code, without checking anywhere else? How can you know for certain that you didnโt change the external state accidentally?
let name = 'Zell'
function changeName() { name = 'Vincy'}
// External state changed. `name` is now 'Vincy'.changeName()If your code is somewhat complicated (and your code will be, trust me on this), you cannot guarantee you did not change the external state. This is especially true if your code is messy.
This is the second reason why you should not reassign variables.
What to do instead of reassignments
You should always declare variables with const. When you declare variables with const, youโll see the const keyword. It is a good indicator that the variable is created in the current scope; it will never change the external state.
const newVariable = 'some value'If you need a if/else statement to determine what value your variable should take, consider using a ternary operator instead of an if/else statement.
const toy = gender === 'boy' ? 'toy car' : 'doll'If you need three or more if statements, consider writing a function that uses an early return. This makes your code more declarative as a result.
function getGift(score) { if (score === 100) return 'Xbox' if (score > 75) return 'new phone' if (score > 50) return 'meal' return null}
const gift = getGift(70)Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson