Pete
Pete

Reputation: 3451

Why is let not the same as var in this case in JavaScript

I recently saw a post saying never use var in JavaScript (ECMAScript6). Always use const or let instead. I have the following code snippet from the YouTube API docs that uses var.

function changeBorderColor(playerStatus) {
    var color;
    if (playerStatus == -1) {
        color = "#37474F"; // unstarted = gray
    } else if (playerStatus == 0) {
        color = "#FFFF00"; // ended = yellow
    } else if (playerStatus == 1) {
        color = "#33691E"; // playing = green
    } else if (playerStatus == 2) {
        color = "#DD2C00"; // paused = red
    } else if (playerStatus == 3) {
        color = "#AA00FF"; // buffering = purple
    } else if (playerStatus == 5) {
        color = "#FF6DOO"; // video cued = orange
    }
    if (color) {
        document.getElementById('existing-iframe-example').style.borderColor = color;
    }
}

When I change var color to let color, my linter suggests that the line near the bottom (if (color)) will always evaluate to true. That is "condition is always true". I'm having trouble understanding what let causes the behavior and var does not.

Upvotes: 3

Views: 93

Answers (1)

jfriend00
jfriend00

Reputation: 707198

The linter is just wrong.

The last if (color) is not affected at all by whether you use let color or var color. It's only affected by whether any of the if tests for playerStatus hit their conditions.

As others have said, you can probably work around the linter bug by assigning a default value to color as in let color = null; and that will likely avoid the confusion the linter got itself in.

Upvotes: 2

Related Questions