Tell me how to stop making this JavaScript mistake.
January 30, 2012 5:41 AM   Subscribe

I keep making the same JavaScript mistake, writing = when the rules call for ==. It's because both signs mean "equal," but in different contexts. Any tips for reprogramming myself so I get it right every time?
posted by markcmyers to Computers & Internet (29 answers total) 5 users marked this as a favorite
I tend to use === instead of ==. The greater difference between the two makes me remember it better for some reason.
posted by Magnakai at 5:42 AM on January 30, 2012 [3 favorites]

Usually when I am typing I am thinking in my head for logic stuff so the litany for some of these in my head are.

= -> Is
== -> Really Is (or Is Is)
!= -> Not Is
&& -> and and
|| -> Stupid pipes not and
^ -> shift 6

for some reason it works.
posted by mrgroweler at 5:51 AM on January 30, 2012 [1 favorite]

you and me both. I'm wondering if the language you're using on the back end uses = for comparison. is it possible for you to use something that's consistent on the back end.

Practice makes perfect.
And that === hint. I may start using that.
posted by seanyboy at 5:52 AM on January 30, 2012

You have to train yourself not to read '=' as 'equals' anymore. In programming, it never is. '=' is the assignment operator. In your head, you should read

var x = 3;

as "the variable x is assigned the value 3." Not "the variable x equals 3."

Also, in Javascript, '==' and '===' are NOT exactly equivalent and you should learn the difference rather than picking one or the other for stylistic reasons.
posted by zjacreman at 5:54 AM on January 30, 2012 [7 favorites]

Fundamentally '==' and '===' are the same however there can be a big difference.


JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:

'' == '0' // false
0 == '' // true
0 == '0' // true

false == 'false' // false
false == '0' // true

false == undefined // false
false == null // false
null == undefined // true

' \t\r\n ' == 0 // true

As to learning to use '=' vs '==', zjacreman is completely right.
posted by dyno04 at 6:02 AM on January 30, 2012 [2 favorites]

The standard way to avoid this problem when doing a comparison on a literal is to always reverse the expression. So, a == 3 becomes 3 == a. That way, if you write 3 = a by mistake, it will not compile and you'll get a javscript error. This method breaks down when comparing two variables however.

Alternately, get in the habit of running Lint - it will catch these mistakes for you.
posted by SNACKeR at 6:03 AM on January 30, 2012 [2 favorites]

It might help to imagine that the assignment is using the old command 'let', as in

let a = 3

Don't type it, but let that be your internal speech for when you are assigning.
posted by gjc at 6:13 AM on January 30, 2012

Similar to other answers, I always read/say "=" to myself as "is" and "==" as "equals."

(Not a programmer, but I work with them.)
posted by teditrix at 6:19 AM on January 30, 2012

In school we were taught to pronounce the assignment operator "=" as "gets". So


means "x gets [the value] 3". Gets bears even less resemblance to equals than "is" so I find it works pretty darn well for me.
posted by telegraph at 6:24 AM on January 30, 2012 [3 favorites]

I assure you this problem will disappear with time. Focus on programming, not the fact you can't program as well as you'd like yet.
posted by michaelh at 6:31 AM on January 30, 2012

This is one of the simpler syntactical bugs to figure out as you're debugging - I'd rather have this bug in my code as I'm unit testing than a more obscure one! Eventually you'll be making the mistake out of absentmindedness more than lack of understanding. The tendency to do this will decrease over time as michaelh said.
posted by Currer Belfry at 6:37 AM on January 30, 2012

= is the 'assignment operator', while == is the 'equality operator'. So 'gets' would be appropriate for the former, as would 'becomes', 'is assigned', or 'means'. Only == should be read as 'equals'.
posted by LogicalDash at 6:43 AM on January 30, 2012

Yeah, I think reading the single equals sign in your head as "is assigned the value" is the best route. If it helps, the fact that the assignment operator and the equivalence operator look so similar was a big focal point for criticism of C (much of whose syntax, including this bit, has been appropriated by other languages such as JS), because other languages of the time used different and easily distinguished operators for those two actions (":=" for assignment and "=" for equality in ALGOL, for example).
posted by invitapriore at 6:43 AM on January 30, 2012

Any tips for reprogramming myself so I get it right every time?

Switch to a value that will complain when you use an assignment as a truth value for a while - C# does this, for example. After a the first 1000 compiler errors you will have figured it out.
posted by Dr Dracator at 6:48 AM on January 30, 2012

I'd advise against reading anything in your code as 'is' without an auxiliary verb. 'Is', used as a verb, is rather ambiguous in ordinary English: are the items being compared identical in all respects? Usually not, so to what purpose are they interchangeable? Sometimes they're not interchangeable at all, and bear more of a symbolic relationship--okay, so which is the symbol and which is the referent, and for that matter, who recognizes that relationship?

When you bring concerns about data typing into it, 'is' acquires a whole new dimension of terribleness. Do Not Engage.
posted by LogicalDash at 6:50 AM on January 30, 2012 [1 favorite]

Dr Dracator brings up a good point, and one way you can get Javascript to reliably yell at you for mixing the two up in an if statement is to switch the two terms that you are comparing:
if (5 = j) {
    alert("This will throw a ReferenceError if executed.");
Since you obviously can't assign a value to a primitive number, this won't just silently fail the way the usual case might. This assumes that you're working with a good debugging environment with a console, such as Firebug or Chrome's developer tools.
posted by invitapriore at 6:55 AM on January 30, 2012

try switching the order around:
If you forget the second equals sign, it will yell at you and refuse to continue (as opposed to silently returning true and overwriting your lovely variable.
posted by Freen at 6:58 AM on January 30, 2012 [1 favorite]

damn you invitapriore! But yes, that's exactly right.
posted by Freen at 7:02 AM on January 30, 2012

greater than or equal to: >=
less than or equal to: <=
not equal to: !=
and: &&
or: ||
therefore equal to will also have 2 characters: ==
(don't mind the <,>,!. those are unremarkable).
posted by zengargoyle at 7:17 AM on January 30, 2012

In the languages and IDEs that I use, I never have to think about this because my syntax highlighting gets all red and annoyed at me when I get it wrong. I still do this maybe one out of fifty times, and I've been programming for like twenty years. Offload it from your brain--the computer should take care of this for you.
posted by zeek321 at 7:50 AM on January 30, 2012 [1 favorite]

In addition to what zeek321 said, there are 'static code analysis' tools that will usually pick up these kinds of mistakes. I haven't used any for javascript but JSLint looks alright.
posted by Green With You at 7:56 AM on January 30, 2012

Oops, didn't see SNACKer's post for a similar tool.
posted by Green With You at 7:56 AM on January 30, 2012

(And if not in the code analysis tools, Javascript isn't compiled, but for compiled languages a modern compiler should warn you about this stuff. I don't know how many do, though.)
posted by zeek321 at 8:02 AM on January 30, 2012

Use JSLint. It will carp at you about best practices.

Read JavaScript: The Good Parts.

Discipline in coding is a habit. Keep running linting tools and eventually it will become a habit and then you're golden.

Me, I'm always trying for = vs. === which is much easier to distinguish.
posted by artlung at 8:06 AM on January 30, 2012

Agreed that some IDEs (Aptana, for example) will warn you if you try to pull something like that past it.

A suggestion that will require more effort on your part: take the time to learn a compiler-based language like C#. The strict syntax rules will whip you into shape pretty fast, because at best you'll get yelled at, and worst you'll break the build:

int MyFunction(bool myValue)
 return 1;

void CallMyFunction()
 string abc = "abc";
 string def = "def";
 MyFunction(abc = def);

As I said, it's an effort, but you're only helping yourself on your resume.
posted by spamguy at 10:24 AM on January 30, 2012

(Clarification: the code will fail because abc is being set to def instead of compared against it. The result is a string, but MyFunction() expects a boolean argument.)
posted by spamguy at 10:26 AM on January 30, 2012

Any tips for reprogramming myself so I get it right every time?

1. No one gets it right every time. Hence the need for linters and compile time warnings. I've been programming for 20 years and I still make this mistake (although not often).

2. Pay attention: focus when you're programming. Think about every argument, every operator, every function call, every line. It's not like typing a paragraph. You can't form some abstract idea in your head and then let your fingers pound it out while you move on to the next thought. You must concentrate and pay attention to the details.
posted by sbutler at 11:26 AM on January 30, 2012

Pronouncing each differently in your head like other previously mentioned works for me. I read a statement like if (x == 5) as, "if x shows equality to 5..." which eliminates most of the slip-ups. sbutler has it nailed though.
posted by EsotericAlgorithm at 2:52 PM on January 30, 2012

If you write your equality tests as "yoda conditions" (5 == var instead of var == 5), most compilers/interpreters will puke up an error when you accidentally sub in "=" for "==" (since 5 = var doesn't make any sense). I don't personally use it but I think it works in Javascript.
posted by purplecrackers at 4:56 PM on January 30, 2012

« Older How can I check over the network whether a Word...   |   Great CD Audiobooks of the Western World Newer »
This thread is closed to new comments.