I'm trying to write some piece of javascript code in a react project. I have a component "expenses" which has been passed some data by props. data is an array of some objects. here is my code: the data:
const EXPENSES = [
{ id: "e1", date: "March 2021 12", description: "New TV", price: "$780" },
{ id: "e2", date: "April 2020 19", description: "basket", price: "$860" },
{ id: "e3", date: "June 2021 08", description: "Laptop", price: "$59" },
];
and inside my expenses component:
const yearsList = props.data.map((item) => item.date.split(" ")[1]);
console.log(yearsList); //it prints ["2021" , "2020" , 2021] as expected
const finalYearsList = (yearsList) => {
var temp = [];
var j = 0;
for (let i = 0; i < yearsList.length; i ) { //this line: Uncaught TypeError: yearsList is undefined
if (temp.includes(yearsList[i])) {
continue;
} else {
temp[j ] = yearsList[i];
}
}
return temp.sort();
};
I want to have all non-repeated years in my finalYearList const but it gives me an error in console that Uncaught TypeError: yearsList is undefined. I'm a bit new to the javascript world. thank you in advance.
CodePudding user response:
You are shadowing the yearsList variable that you declare on line 1 with the parameter yearsList in line 4.
You could change your code in two ways:
- Remove the parameter on line 4, so your function declaration is
const finalYearsList = () => {
...
}
- Pass in
yearsListas a parameter when you call the functionfinalYearsList
const yearsList = props.data.map( ... );
const finalYearsList = (yearsList) => {
...
}
finalYearsList(yearsList);
A recommendation I'd make if you go with option number 2 is to rename either the variable or the parameter and avoid this shadowing altogether, as it causes confusion (as you've seen).
CodePudding user response:
If you want to use your yearsList in the function finalYearsList, you don't have to pass it as an argument. In your current code you are declaring a parameter with the name yearsList and you thereby overwrite the original yearsList.
Your original yearsList is defined in the global scope and therefore accessible inside of every function !
So just use...
const yearsList = props.data.map((item) => item.date.split(" ")[1]);
console.log(yearsList); //it prints ["2021" , "2020" , 2021] as expected
const finalYearsList = () => {
var temp = [];
var j = 0;
for (let i = 0; i < yearsList.length; i ) { //this line: Uncaught TypeError: yearsList is undefined
if (temp.includes(yearsList[i])) {
continue;
} else {
temp[j ] = yearsList[i];
}
}
return temp.sort();
};
...instead.
