sparecycle
sparecycle

Reputation: 2058

Javascript conditoinal returning "undefined"

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.

Upvotes: 0

Views: 64

Answers (3)

Richard Kho
Richard Kho

Reputation: 5286

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.

Upvotes: 1

Cerbrus
Cerbrus

Reputation: 72947

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

Upvotes: 2

Travis J
Travis J

Reputation: 82297

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

Upvotes: 1

Related Questions