About array methods. are all them chainable?

Hello :
i’m working on the credit card number validator, and as i work with my arrays i tried to chain a couple of methods, but i get a syntax error when i chain them.
now when i dont chain them it works fine. are all array mathds chainable ?

"const validateCred = (arr) => {
let digits = arr.map((el) => el)


this above works. but… if i try …
digits.pop().reverse() it throws an error.


returns the item that was taken from the array, so for example:


would return


i agree but …
digits.pop().reverse() throws a typeError
and digits.reverse().pop() does not reverse the array. it just executes the pop.
i have to create different lines for each one,

It should.

However, like I said, pop() only returns the popped item. It does not return the array.

Hi @prodigos
maybe a few consoles help you to understand the difference between the chaining you have done in your second version and the separate steps in your first. The key is to understand that when you chain the methods you are working with the returned value of the previous method rather than the mutated array as was already pointed out before.

const validateCred = (arr) => {
let digits = arr.map((el) => el)
const returnedVal = digits.pop();
console.log(`digits: ${digits}, returnedVal: ${returnedVal}`); // "digits: 1,2,3,4, returnedVal: 5"
console.log(`digits reversed: ${digits}`); // digits reversed: 4,3,2,1


If you reverse the array first, you can achieve the same result with .shift() rather than .pop():

const validateCredChained = (arr) => {
let digits = arr.map((el) => el)
console.log(digits); // [4, 3, 2, 1]


If you use .pop() prior to .reverse() in the chain you reverse the single number returned from the .pop() method, which leads to the type error.

const validateCredChained2 = (arr) => {
let digits = arr.map((el) => el);
// returns 5 (typeof number) --> reverses the number rather than the array
console.log(digits); // type error


But in each of these variants the chained methods are executed.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.