I am getting the following error on VS Code Debug Console;
"Uncaught TypeError TypeError: months.toSpliced is not a function"
when I run this code;
const months = ["Jan", "Mar", "Apr", "May"];
// Inserting an element at index 1
const months2 = months.toSpliced(1, 0, "Feb");
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]
It is not even my code, I copy-pasted it from here; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSpliced
I came across this error while trying to learn toSpliced() method.
Any help would be highly appreciated. Thank you.
Array.prototype.toSpliced() is relatively new feature of node.js, not part of the ECMAScript standard. Even Chrome has these methods available only since version 110 and node only since version 20.0.0 (you can check your currently installed node version prompting node -v in your terminal).
If you encaunter problems with this, you could try to replace your code with this:
const months = ["Jan", "Mar", "Apr", "May"];
// Inserting an element at index 1
const months2 = months.slice(); // create a copy of the array
months2.splice(1, 0, "Feb");
console.log(months); // ["Jan", "Mar", "Apr", "May"]
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]
The difference between splice method and toSpliced is that splice modify the original array, while toSpliced returns a new array with the specified elements removed, leaving the original array unchanged.
In order to use Array.prototype.toSpliced() your ECMAScript version has to be ES2023, try changing 'lib' inside of your tsconfig.json or jsconfig.json to include ES2023. It should look something like this:
"lib": [
"ES2023",
]
In case you don't have a jsconfig.json you can easily create that using shortcut in VS Code CTRL+SHIFT+P and typing JavaScript: Go to Project Configuration this will automatically suggest to create one. Inside of that configuration file, you need to add the lib option that I mentioned above
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With