DEV Community

Why you shouldn't reassign values in JavaScript

Zell Liew 🤗 on June 20, 2018

In JavaScript, you can reassign values to variables you declared with let or var. I used to reassign values a lot. But as I got better with JavaSc...
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Even easier to read?

function getHairType (today) {
  return {
    Monday: 'bangs',
    Tuesday: 'braids',
    Wednesday: 'short hair',
    Thursday: 'long hair',
    Friday: 'bright pink hair'
  } [today];
}

@miguelqueiroz - I was thinking the same. Admittedly the function wrapper above is pointless

Collapse
 
miguelqueiroz profile image
Miguel Queiroz

That's my point. But its funny to know your hair is sort of undefined for Saturday or sundays ehe..

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Bad hair days! 😝

Thread Thread
 
zellwk profile image
Zell Liew 🤗

Ooh! You're completely right there. I should have came up with a better example 😅.

Collapse
 
dallgoot profile image
dallgoot
function getHairType (today) {
  switch(today.toLowerCase()){
    case "monday":    return 'bangs';
    case "tuesday":   return 'braids';
    case "wednesday": return 'short hair';
    case "thursday":  return 'long hair';
    case "friday":    return 'bright pink hair';
    default:
        //default value or throw "only workdays allowed for 'today'"
  }
}

or to allow rapid visualisation of constants:

const MONDAY_HAIRTYPE = 'bangs';
// ... const for each day
const DEFAULT_HAIRTYPE = MONDAY_HAIRTYPE; 

let dayHairType = today.toUpperCase()+"_HAIRTYPE"; 
hair = dayHairType in this ? this[dayHairType] : DEFAULT_HAIRTYPE;

no undefined, no function call cost

Collapse
 
shalvah profile image
Shalvah • Edited

Good article @zellwk . Another useful habit to cultivate is not allowing your functions to modify anything that wasn't created within it (or at the least, passed in as an argument). That way you won't have to worry too much about mistakenly reassigning something else.

Collapse
 
zellwk profile image
Zell Liew 🤗

Yup. Pure functions FTW.

Collapse
 
squgeim profile image
Shreya Dahal

This is what I tell people when they argue against using const ("it's not really immutable"). When using const is the default, we naturally think in ways that result in better code.

Most functions have a structure like this:

let var1;
// ... do stuff to settle on the value for var1

let var2;
// ... do stuff to settle on the value for var2

// ... use var1 and var2 to produce the result.

When we are allowed to reassign, these "concerns" easily get intertwined and a clear separation is not visible. It also becomes harder to extract out meaningful function out for reuse.

With no reassignment the code looks more like:

const var1 = condition ? value1 : value2;

const var2 = (() => {
  // Do stuff to settle on a value of var2

  return value2;
})();

There is a clear separation of concern and it is easier to refactor.

Collapse
 
adriannull profile image
adriannull

WTH ? I strongly believe this promotes stupidity amongst programmers. It's verry natural for a function to be able to access global variables, both for read and write operations. It's your job as a programmer to fully understand the function you're trying to change, which variables are local and which are global. Not to mention that you could have naming convensions like "all global variables start with g_". And on top of that, it's a good practice to comment your code, for both you and others. Simply placing a comment like "// here we set value X in global variable Y" makes things crystal clear.

If we would use each variable only once, we would need to work with far more variables and our code would be alot bigger and alot messier. Not to mention we would increase memory size.

A simple example i can think of, often found in my codes, is something like this (pseudocode here, i work mostly in PHP):

var arrData = DATABASE->SomeQuery(1);
do something with arrData, from above query only,
  usually iterating through each row and calculate something,
  put final data in, let s say, variables A, B, C;

arrData = DATABASE->SomeQuery(2);
do something with arrData, from above query only,
  usually iterating through each row and calculate something,
  put final data in, let s say, variables D, E, F;

... and so on

Basically, if i would need 5 different queries, returning large amounts of data, but i only need that data for a verry short amount of time, why on earth would i want to create separate variables to load my memory more than needed ?

Collapse
 
neradev profile image
Moritz Schramm

Optimization can often lead to code that is harder to read, test and maintain. You are right saying that is the task of an programmer to understand the code. But I would not like to work in such code. Moreover in times of huge in-memory-databases, memory is not as expensive as programmers maintaining and extending the code.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Just noticed you may want to rewrite this bit:

I recommend always create variables with the const keyword. This is because variables created with a const keyword cannot be reassigned. You'll get an error if you try to assign a new value to them.

The const keyword creates constants, not variables.

Collapse
 
shalvah profile image
Shalvah • Edited

They're not really "constants" in a strict sense because, even though you can't reassign, you can modify the referenced value (if it's an object). For instance:

const x = {a: 1};

// this will fail
x = {a: 2};

// but this will pass
x.a = 2;
Collapse
 
miguelqueiroz profile image
Miguel Queiroz

I would totally not use a function but instead an object like:

Hair={"monday":"bangs",
"Tuesday":"braids"};
and so on...

return Hair[today];

Collapse
 
esamcoding profile image
esam a gndelee

the real problem is not reassigning values, the real problem is global scoped variables.

javascript is really nasty. it was not chosen because it is the best.