I am trying to catch the element when the value of the input is null but the if statement isn't working.

for (let i = 0; i<esquema.length; i++){
    if (esquema[i].checked){
        console.log(esquema[i].value);
        if (esquema[i].value == null){
            console.log ("Actually null");
        }
    }
}

The output should be

null
Actually null

But instead of that i am getting

null
undefined

Can someone help me with this?

2 Answers

0
Jonas Wilms On

The value of an HTMLElement is either undefined if it is not an <input> (<button>, ...) element, or it is a string. As it is not undefined (as it logs null, and null == undefined would be true), it has to be "null" which would log null but would not be equal to null.

Most consoles do print null and "null" differently though, log both and compare the results to see the difference.

0
Tin Tin On

I have checked your function, it works if the value being received is null. It wouldn't be checking the type of data but just match the value.

var esquema = [
  {
    checked: true,
    value: "None"
  },
  {
    checked: true,
    value: null
  }
];
for (let i = 0; i<esquema.length; i++){
    if (esquema[i].checked){
        console.log(esquema[i].value);
        if (esquema[i].value === null){
            console.log ("Actually null");
        }
    }
}

In your case, I assume that esquema is set of checkboxes and i am sure you wouldn't be able to set a value as "null". If the value is not added to the node, it would be "undefined" but not "null" in any case.