'what should i do when" "Array.forEach (<anonymous>)" this is shown in console while i am using the following code in javascript

    [inpTitle, inpBody].forEach(inputField => {
        inputField.addEventListener("blur", () => {
            const updatedTitle = inpTitle.value.trim();
            const updatedBody = inpBody.value.trim();

            this.onNoteEdit(updatedTitle, updatedBody);
        });
    });

this error is being shown in the console too Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')



Solution 1:[1]

You can add an if statement to check if the inputField exists, but there should be other ways to make sure that you don't have an empty input.

[inpTitle, inpBody].forEach(inputField => {
  if(inputField){
    inputField.addEventListener("blur", () => {
        const updatedTitle = inpTitle.value.trim();
        const updatedBody = inpBody.value.trim();

        this.onNoteEdit(updatedTitle, updatedBody);
    });
   }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Elvis