Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

368
Views
Why this code gives me "Uncaught TypeError: Cannot read properties of null (reading 'push')" error?

In this code I am getting error as Uncaught TypeError: Cannot read properties of null (reading 'push')

console.log("HI");
let addbtn = document.getElementById("addbtn");
addbtn.addEventListener("click", function (e) {
  let addtxt = document.getElementById("addtxt");
  let notes = localStorage.getItem("notes");
  if (notes == null) {
    notesObj = [];
  } else {
    notesObj = JSON.parse(notes);
  }

  notesObj.push(addtxt.value);
  //getting error at this point. Don't know why
  localStorage.setItem("notes", JSON.stringify(notesObj));
  addtxt = "";
  console.log(notesObj);
});
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

checkout this I hope it will fix your problem

let addbtn = document.getElementById("addbtn");
console.log('addbtn ', addbtn);

addbtn?.addEventListener("click", function (e) {
  let addtxt = document.getElementById("addtxt");
  let notes = localStorage.getItem("notes");

  notesObj = JSON.parse(notes ?? '[]');

  console.log('addtxt.value ', addtxt?.value);

  notesObj.push(addtxt.value);
  //getting error at this point. Don't know why
  localStorage.setItem("notes", JSON.stringify(notesObj));
  addtxt = "";
  console.log(notesObj);
});
about 4 years ago · Juan Pablo Isaza Report

0

The issue is that you have the string 'null' in your local storage.

Yes you compare with null, but notes is still JSON at this point, and apparently it can be null encoded as JSON. So you'd also need to check for 'null' as string.

Or, easier: Replace the whole if with something like this:

const notesObj = (notes && JSON.parse(notes)) ?? []

If you want to be also resilient against invalid JSON in local storage, you can use this:

let notesObj
try {
  notesObj = JSON.stringify(notes) ?? []
} catch(e) {} 
about 4 years ago · Juan Pablo Isaza Report

0

to fix this issue use localstorage.clear() in the console. that's it.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!