3

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.

4
  • 1
    try let color = null; Commented Dec 16, 2017 at 17:23
  • 1
    @charlietfl that solves the problem, but not really my question of why var and let are different in this case. Commented Dec 16, 2017 at 17:26
  • 4
    I think the linter is wrong to be honest Commented Dec 16, 2017 at 17:29
  • 2
    @charlietfl Me too. I was looking for a polite way to say it. The linter may be confused by the so-many blocks there that assign a value to color. Commented Dec 16, 2017 at 17:33

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.