I am storing an array of objects in localStorage, retriving it each time, attachibg the new object and again storing.
the code works fine, only if there is already an entry in localStorage Following is the code:
var companies=; companies=JSON.parse(localStorage.getItem("companies")); //IMP line companies.push(company); localStorage.setItem("companies", JSON.stringify(companies));
This works fine, when I comment the 'IMP line' for first time, so that a record is inserted with single record. once the local storage contains a record with key "companies" everything goes fine.
please suggest a condition that can be checked while inserting the array first time. Thank You.
You need to check:
var strCompanies = localStorage.getItem("companies") var companies = strCompanies ? JSON.parse(strCompanies) : ;