Skip to content
Advertisement

Why is !null true when var is null per default [closed]

Why is JavaScript executing the code below even though the var is initially declared as null? The condition in the if-query is that the var interval is not null but it is, so actually it should not be executed.

let interval = null;

if (!interval) {
  setInterval(print, 1000);
}

function print() {
  console.log('Hi');
}

Advertisement

Answer

null is one of a few ‘falsy’ values in JavaScript, including NaN, false, 0, “” and undefined. When JavaScript is asked to coerce a value to bool, which if does, the value is checked against falsy values, but is otherwise considered ‘truthy’. Your null was falsy, you used ! to ‘not’ it, making it true.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement