0
  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"); };
DarkBee
  • 16,592
  • 6
  • 46
  • 58
Bhasim
  • 1
  • 1
  • 2
  • 2
    You create S variable locally inside function startTime(). To use it outside, you should create it globally – Levi D. Apr 15 '22 at 09:06
  • thanks didnt think that could be a problem – Bhasim Apr 15 '22 at 09:08
  • 1
    Some scope discussion here: [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) and here [What's the difference between using "let" and "var"?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) and then there's [hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) – pilchard Apr 15 '22 at 09:08
  • 1
    https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – Teemu Apr 15 '22 at 09:08

1 Answers1

3
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

Saif Ali
  • 72
  • 5