Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is !null true when var is null per default

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');
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading