Be careful of accidentally substituting similarly named variables from an outer scope

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dumb-mistakes-and-gotchas category.

Last Updated: 2024-11-21

I was getting the wrong output on a slider input powered by the following code:

function animateSliderTo(el, val, cssColorHex) {
  el.value = val

  const cssTemplate = (initialValue, valueToAdd) => {
     // Hint: The error is on the following line
    const newValue = initialValue + val

    return '-webkit-gradient(
        linear, left top, right top,
        color-stop(${newValue}, ${cssColorHex}),
        color-stop(${newValue}, white)
      )'
  }

  el.css("background-image", cssTemplate("0.", val * 2));
}

animateSliderTo($sliderEl, 98, "#ccc")

The issue was that I used val (the parameter in the outer functino) instead of valueToAdd (tthe one from the inner function) in calculating newValue. This meant my updated version val * 2 on the line that applied the cssTemplate was never used.

Lessons

Always watch out you don't accidentally substitute similarly named variables from an outer scope. The compiler won't complain because the variable is present (it just happens to be the wrong one)