In the simple test code below I push
the number 10 into an array and then splice
'hello world' into the array on the 2nd index. It works as expected.
"use strict";
let myArray = [1, 2, 3, 4, 5];
myArray.push(10);
myArray.splice(2, 0, 'hello world');
console.log(myArray);
However is it possible to do this on one line? I tried chaining in the example below and it throws an error. I can't find anyone talking about this online.
"use strict";
let myArray = [1, 2, 3, 4, 5];
myArray.push(10).splice(2, 0, 'hello world');
console.log(myArray);
Yes, it is possible to do it in one line.
"use strict";
let myArray = [1, 2, 3, 4, 5];
myArray.push(10); myArray.splice(2, 0, 'hello world');
console.log(myArray);
But why do you want to do that in one line? If your concern is readability I would stick with two lines. If you want it more functional, then use a functional library
edit
I agree with what every one else said about chainability. I'm just trying to make another point
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