-23

I struggle to understand the function below. I didn't know why my script wasn't working until I changed = with === in the if statement, as shown below. Why does === work while = doesn't?

var testTest = function(answer) {
    if (answer === "doggies") {
       return "My favorite animal!";
    } else {
       return "Tested";
    }
};
testTest("doggies")

When I type doggies, it shows me My favorite animal! With anything else, it returns Tested as it should.

However, when I change the === in the if statement with =, the else part doesn't work.

var testTest = function(answer) {
    if (answer = "doggies") {
       return "My favorite animal!";
    } else {
       return "Tested";
    }
};
testTest("elephant")
Yves Gurcan
  • 1,096
  • 1
  • 10
  • 25
Simon
  • 385
  • 4
  • 19
  • 3
    `=` is an assignment operator and `===` is a comparison operator. Now look forward for these both you will find tons of articles. – Dhaval Marthak Jun 18 '15 at 08:41
  • 1
    @AlexG No, this question is different. It is still a bad question, but different. – Ismael Miguel Jun 18 '15 at 08:42
  • 3
    there are actually 3 different `=`, `==`, and `===`. the first is for *assignment*, the other two are for *comparison*. – Claies Jun 18 '15 at 08:42

3 Answers3

5

You need to use == or === for equality checking. = is the assignment operator.

You can read about assignment operators here on MDN.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
3

As a quick reference as you are learning JS:

=   assignment operator
==  equal to
=== equal value and equal type

!=  not equal
!== not equal value or not equal type
GibboK
  • 71,848
  • 143
  • 435
  • 658
0

I assume you know that = is for assignment, after all, you are using assignment already in the first line:

var testTest = function(answer) {

and I don't think you think that this would compare anything here (or do you?).

The question remains though, why does = in if (answer = "doggies") "not work"?

An assignment is an expression. The result of that expression is the value that was assigned. Here, the result of answer = "doggies" is "doggies", i.e. you essentially running if ("doggies").

JavaScript performs type coercion. That means it automatically converts values of one data type to values of a different data type if necessary, according to specific rules.

The condition of an if statement has to resolve to a Boolean value. But here you are using a string value as condition. The String -> Boolean conversion rules are pretty simple:

  • The empty string converts to false.
  • A non-empty string converts to true.

So, after type conversion, the statement is equivalent to if (true), hence it will always execute the first block, never the else block.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143