Home > database >  Why is !null true when var is null per default
Why is !null true when var is null per default

Time:08-08

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

CodePudding user response:

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.

CodePudding user response:

Javascript has a concept called Type Coercion.

Type coercion is the process of converting value from one type to another (such as string to number, object to boolean, and so on). Any type, be it primitive or an object, is a valid subject for type coercion. https://www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/

In this case, null is coerced to false and then negated(true). That's why setInterval() is being executed.

The if statement has implicit coercion (automatic coercion) for some types: Objects, string, numbers and so on.

If you're not sure what the if statement will coerce to, you could try explicit coercion. For example, execute this in console Boolean(null).

CodePudding user response:

!null is true

console.log(!null)

Your code is equivalent of:

let interval = null ;
const value = !inteval;

if(value) {
setInterval(print,1000);
}

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

As value (!null) is true, the code in if block runs

The condition in the if-query is that the var interval is not null

It doesn't work like that, from you description the code should look like this:

let interval = null;
if (interval !== null) {
  //..
}

CodePudding user response:

To not execute you would do

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

meaning if condition is falsy, which it does (interval = null = falsy), it won't execute.

  • Related