0
     for(const id of this.extraRooms)
            {
              let doesRoomExist = document.getElementById('newRoomAddress' + newRoomId);
              //if(typeof(doesRoomExist) !== "null")              
               if(typeof(doesRoomExist) !== "undefined")
              {
                  const newRoomLabel = document.getElementById('newRoomAddress' + newRoomId).value        
             {

Probably a simple fix but if doesRoomExist is NULL it is still going inside the if statement...

let doesRoomExist = document.getElementById('newRoomAddress' + newRoomId);

will show doesRoomExist as NULL when stepping through the code in VS code, but show as undefined if used in developer tools...why is it going inside the if?

any help please?

John
  • 3,965
  • 21
  • 77
  • 163
  • 2
    Run `typeof null` in a Javascript debugger to understand your issue. All you need to do is `if(doesRoomExist) {...}` - research Javascript truthiness. – Andy Ray Aug 29 '23 at 02:12
  • Because `typoeof something` will never be `"null"` use `if (doesRoomExist !== null)` or simply `if (doesRoomExist)` instead – derpirscher Aug 29 '23 at 02:19

2 Answers2

2

You should check the value of doesRoomExist directly not its type, you can either check if (doesRoomExist !== null) or just doing if (doesRoomExist) will be enough;

if(doesRoomExist !== null)
    const newRoomLabel = document.getElementById('newRoomAddress' + newRoomId).value
Abdel
  • 404
  • 2
  • 8
0

Just use if (doesRoomExist) { /*...*/ }.

for (const id of [1, 2, 3, 4, 5]) {
  const doesExist = document.getElementById('item' + id);
  if (doesExist) {
    const newLabel = document.getElementById('item' + id).value;
    console.log(newLabel);
  }
}
<input id="item1" value="value1">
<input id="item2" value="value2">
<input id="item4" value="value4">
<input id="item5" value="value5">
msrumon
  • 1,250
  • 1
  • 10
  • 27