ForEach returns null how to fix it?

const engWord = document.getElementById("eng"),
 rusWord = document.getElementById("rus"),
 inputs = document.getElementsByClassName("input"),
 addButton = document.getElementById("add-word-btn"),
 table = document.getElementById('table');

let words,
btnsdelete;

localStorage.length < 1 ? words = [] : words = JSON.parse(localStorage.getItem('words'));

const addWordToTable = index => {
 table.innerHTML +=
 `<tr class="tr">
 <td class="eng-word">${words[index].english}</td>
 <td class="e-word">${words[index].English}</td>
<td>
 <button class="btn-delete">X</button>
</td>
 the <tr> `
};

words.forEach((element, i) => {
addWordToTable(i);
});

function CreateWord(english, russian) {
 this.english = english;
 this.russian = russian;
}

addButton.addEventListener('click', () => {
 if (
 engWord.value.length < 1 ||
 rusWord.value.length < 1 ||
 !isNaN(engWord.value) ||
!isNaN(rusWord.value)
 ) {
 for (let key of Array.from(inputs)) {
key.classList.add("error")
}
 } else {
 for (let key of Array.from(inputs)) {
key.classList.remove("error")
}
 words.push(new CreateWord(engWord.value rusWord.value));
 localStorage.setItem("words", JSON.stringify(words));
 addWordToTable(words.length - 1);
 engWord.value = null;
 rusWord.value = null;
addEventDelete();
}
});

const deleteWord = e => {
 const rowIndex = e.target.parentNode.parentNode.parentNode.rowIndex;
e.target.parentNode.parentNode.parentNode.remove();
 words.splice(rowIndex, 1);
localStorage.removeItem('words');
 localStorage.setItem('words', JSON.stringify(words));
};

const addEventDelete = () => {
 if(words.length > 0) {
 btnsdelete = document.querySelectorAll('.btn-delete');
 for(let Array of btn.from(btnsdelete)) {
 btn.addEventListener('click', e => {
deleteWord(e);
})
}
}
};

addEventDelete();
April 19th 20 at 12:15
1 answer
April 19th 20 at 12:17
Solution
It is possible, if localStorage has some elements, but there is no element of "words".
In any case, for a non-existent item localStorage.getItem will return null, and JSON.parse(null) === null. Therefore, it is better to write something like this:
words = JSON.parse(localStorage.getItem('words')) || [];
Thank you very much!!!!!!! - kayleigh commented on April 19th 20 at 12:20

Find more questions by tags JavaScript