title: JavaScript: Variable undefined inside if else
body: <p>Here I have a simple countdown function that redirects the user after 5 seconds.</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  
  var timer = 5;
  var counter = document.getElementById("countdown");
  
  function countdown(target)
  {
      counter.innerHTML = timer--;
      if (timer &gt;= 0)
      {
          setTimeout(function () {
              countdown();
          }, 1000);
      }
      else
      {
          // Redirect the user
  
          console.log(target); // Outputs "undefined" after 5 seconds
  
          if (!typeof target === "undefined")
          {
              window.location.href = target;
          }
      }
  };
  
  var target = "/account/";
  countdown(target);
  
  &lt;/script&gt;
  </code></pre>
  
  <p>The problem is, when 5 seconds elapse and it's time for the <code>window.location.href</code> to do the redirection, the "target" variable is undefined, I'm not sure why this happens.</p>
  
  <p>I have researched and tried various solutions, even setting the "target" the way "timer" and "counter" are set, but none worked. My goal is to set a different "target" at each function instance.</p>
  
  <p><strong>UPDATE</strong>: Setting <code>countdown();</code> to <code>countdown(target);</code> fixed the "undefined" issue, but the <code>window.location.href</code> object still doesn't redirect to the <code>target</code> variable value, What can be done to fix this?</p>