0

There are all kinds of examples of functions returning "undefined" but I'm having trouble finding a reason why my JS conditional (which I have reduced to a simple IF...ELSE statement) is returning "undefined" in the console.

var blue = "color";
var green = "color";


if (blue = green) {
    console.log("success");
}
else {
    console.log("fail");
}

Can someone please explain what is undefined? Thanks in advance.

sparecycle
  • 2,038
  • 5
  • 31
  • 58

3 Answers3

2

Your if contains an assignment, not an equality check.

Replace:

blue = green

With:

blue == green

Or preferably:

blue === green

Since both are expected to be strings, you can (and should) use the strict equality check (===), there.

This "triple equals" check if both type and value are equal, compared to only value for the ==:

alert("1 === '1': " + (1 === '1'));
alert("1 == '1': " + (1 == '1'));

Now, if you run that code in a browser's console, the actual code will not return a value, thus, it will output undefined, aside from the console.log() results:

enter image description here

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Never use double equals: http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons – Richard Kho May 26 '15 at 22:21
  • 1
    Never say _"Never"_. If you know what types you're comparing, and you're familiar with JS's type casting, a `==` really isn't that bad. – Cerbrus May 26 '15 at 22:23
  • Really? 2 downvotes? What's so wrong about this answer? – Cerbrus May 26 '15 at 22:27
  • 1
    You and me both @Cerbrus http://i.imgur.com/otKjoWr.png . I wish there were more explanations given at times. – Travis J May 26 '15 at 22:29
1

Your current if-statement is conducting an operation of setting blue to equal green. The single equals sign does not actually check for a truthy value.

In order to run a boolean check here, you need to use a triple equals operator.

if (blue === green)

If you run this in the console, here's how it looks:

enter image description here

Since your if statement doesn't actually return anything (instead, it just logs to the console), you will receive undefined as your output.

Richard Kho
  • 5,086
  • 4
  • 21
  • 35
1

The reason that you see undefined in the console is because that is what the executed code finished with. The last statement executed was the if else clause which has no return value, hence undefined.

A second important aspect to note is that you are doing an assignment inside of your if statement, and as a result of that assignment you are always going to end with if( "color" ) which is going to always be true, and as a result the console.log will always occur.

This results in the console looking like

"success"
undefined

Since someone downvoted this and apparently is not familiar with executing console code

enter image description here

Travis J
  • 81,153
  • 41
  • 202
  • 273