Skip to main content

Equality versus assignment in JavaScript

· 2 min read

This is a very common bug as it basically has to do with the number of = signs.

On reflecting about this this morning, this classic bug might actually give a deeper insight into how life works.

Let's take the premise that how we think about things helps shape our reality.

So, say, if we have a wealth mindset, we will typically do better financially in life than if we had a poverty mindset.

Let's look at this basic code..

let mindset = 'poverty';

if(mindset = 'wealth') {
console.log('You will do well in life financially.');
} else {
console.log('This life might be a struggle financially for you.');

At first glance this might look like it's saying:

  • if you have a wealth mindset, you will do well in life financially
  • otherwise this life might be a struggle financially for you

So because mindset is set to 'poverty', the else (otherwise) clause would be expected to run, and print

This life might be a struggle financially for you.

However, there is that classic aforementioned bug in this code, which is not actually checking if the mindset is wealth or not (equality ===), but instead assigning wealth to the mindset variable (assignment =).

The consequence of an assignment is always truthy. i.e. it will always be true.

This means that whatever the mindset variable is initialised with (or updated to be), when that if statement executes, the output will always be

You will do well in life financially.

One possible conclusion being, that if our conviction is strong enough to always have a wealthy mindset regardless of what financial state we were born into, or what life has been like up this point, we can always shift things to do well financially anyway.

Of course, this example does not only apply to wealth, but anything we put out mind to irrespective of our circumstances.