Bhasim
Bhasim

Reputation: 1

error: var is not defined while it is defined

  1. I want to know, why it says that the third "S is not defined", because S is defind
function startTime() {
  const today = new Date();
  var S = today.getHours();
  var m = today.getMinutes();
  m = checkTime(m);
  document.getElementById('txt').innerHTML = S + ":" + m;
  setTimeout(startTime, 1000);
}

function checkTime(i) {
  if (i < 10) { i = "0" + i };  // add zero in front of numbers < 10
  return i;
}

this S here

var a = S + m
    
if (a === 2215) {console.log("lol"); };

Upvotes: 0

Views: 125

Answers (1)

Saif Ali
Saif Ali

Reputation: 72

var S,m;
function startTime() {
  const today = new Date();
  S = today.getHours();
  m = today.getMinutes();
  m = checkTime(m);
  document.getElementById('txt').innerHTML = S + ":" + m;
  setTimeout(startTime, 1000);
}

function checkTime(i) {
  if (i < 10) { i = "0" + i };  // add zero in front of numbers < 10
  return i;
}

var a = S + m
    
if (a === 2215) {console.log("lol"); };

You forgot to shift "S" to global scope, var has a function scope, if variable is declared with var, can access only it's function scope

Upvotes: 3

Related Questions