How to avoid 'cannot read property of undefined' errors?
Update:
- If you use JavaScript according to ECMAScript 2020 or later, see optional chaining.
- TypeScript has added support for optional chaining in version 3.7.
// use it like this
obj?.a?.lot?.of?.properties
Solution for JavaScript before ECMASCript 2020 or TypeScript older than version 3.7:
A quick workaround is using a try/catch helper function with ES6 arrow function:
function getSafe(fn, defaultVal) {
try {
return fn();
} catch (e) {
return defaultVal;
}
}
// use it like this
console.log(getSafe(() => obj.a.lot.of.properties));
// or add an optional default value
console.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));
Unable to fix cannot read properties of undefined
Based on a comment above, indicating that the error is thrown here:
return results.filter((quote) => {
If results
is undefined then you can't "filter" anything on it. What should filteredItems
return in that case? For example, you can perform null checking to return null:
return results?.filter((quote) => {
Or perhaps you could conditionally return an empty array:
return results ? results.filter((quote) => {
//...
}) : [];
React Context. how to avoid Cannot read properties of undefined error before having a value
Your clickedImg
starts out as the empty string:
const [clickedImg, setClickedImg] = useState("");
And in the consumer, you do:
const [slideIndex, setSlideIndex] = useState(clickedImg.id);
So, it takes the value of clickedImg.id
on the first render - which is undefined
, because strings don't have such properties. As a result, both before and after fetching, slideIndex
is undefined
, so after fetching:
albums ? albums[slideIndex].url : "no data"
will evaluate to
albums[undefined].url
But albums[undefined]
doesn't exist, of course.
You need to figure out what slide index you want to be in state when the fetching finishes - perhaps start it at 0?
const [slideIndex, setSlideIndex] = useState(0);
How to prevent Cannot read property example of undefined when trying to check if said property is undefined
Your problem isn't that clicks
is undefined; it's that your data
variable is undefined. Check out this code snippet:
var data;
var playerid = idd.toString();
fs.readFile("data.json", function(err, data){
json = JSON.stringify(data);
data = JSON.parse(json);
})
if(data[playerid].clicks === undefined){ // <-- BOOM
The var data
declares the variable, and it starts off holding the value undefined
. You are populating data
with your JSON.parse
, but that's happening asynchronously in a callback. Therefore the if statement code runs before that data assignment.
You'll want to make sure that you're reading data
after it has been populated by putting your code in the callback or using Promises and awaiting the asynchronous file read.
Here's an example of how you can use an async function (keeping in mind that the caller of this function also has to await it):
async function clickeridoo(idd){
const playerid = idd.toString();
const fileContents = await fs.promises.readFile("data.json");
const data = JSON.parse(fileContents);
// TODO: handle case where `data[playerid]` is undefined
data[playerid].clicks = (data[playerid].clicks || 0) + 1;
await fs.promises.writeFile("data.json", JSON.stringify(data));
return data[playerid].clicks.toString()
}
How can I avoid Cannot read property error when the element isn't exist?
Make your code look something like this:
var element = $(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0];
if(element) {
category = element.outerHTML
}
it's seems that sometimes the element you are searching is missing, so the result is undefined, to avoid this issue, check if found what you queried for
cannot read property 0 of undefined error
To avoid the error, replace
for (var i = 0; i < 5; i++) {
by
for (var i = 0; i < lista_carpetas_ok2.length; i++) {
This might also help to avoid the code to stop at certain folder.
Regarding the error
> Info Cannot read property 'getRange' of null"
This occurs because the spreadsheet hasn't a sheet named fechas
to avoid this error you might add
if(!SpreadsheetApp.open(file).getSheetByName("fechas")) break;
above of
var sms = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("A2").getValue();
if(
Debugging tips:
To verify that the correct values are assigned to
lista_carpetas_ok2
, addconsole.log(JSON.stringify(lista_carpetas_ok2));
just belowlista_carpetas_ok2
declaration so you can review the values assigned to the variable.To have more informative logs when an error occurs, instead of
} catch (e) {
Logger.log(e.toString()); // or console.log(e.message);
}use
} catch (e) {
console.log(e.message, e.stack);
}
Related Topics
Pad a Number With Leading Zeros in JavaScript
JavaScript Implementation of Gzip
How to Pass Command Line Arguments to a Node.Js Program
How to Get the Youtube Video Id from a Url
Regex to Extract All Matches from String Using Regexp.Exec
How to Fetch the Value of a Non-Standard CSS Property via JavaScript
How to Animate a Progressive Drawing of Svg Path
CSS Transitions on New Elements
Open a File with Default Program in Node-Webkit
How to Detect My Browser Version and Operating System Using JavaScript
How to Post Urlencoded Form Data With $Http Without Jquery
Getting JavaScript Object Key List
Fastest Method to Replace All Instances of a Character in a String
JavaScript - Generating Combinations from N Arrays With M Elements
How to Import Variables from JavaScript to SASS or Vice Versa
Resetting the Opacity of a Child Element - Maple Browser (Samsung Tv App)