简体   繁体   中英

Javascript chaining

This might be very basic but I am not able to understand how chaining and return works at the same time like for example

let array = [1, 2, 3]
let newArray = array.map(val => val * 10).map(val => val * 10)
console.log(newArray) // [100, 200, 300]

Here we can keep on adding.map and it will keep returning a new array. It behaves like when chaining stops it knows now that it has to return value but when chaining continues it keeps treating it as object. How does that work and how can I achieve similar functionality in my code.

How does that work and how can I achieve similar functionality in my code.

I'm not sure what you mean. Array objects in JS have map() method which returns always new array modified by callback function that you're passing val => val * 10 .

You can think of this expression as [1,2,3].map(val => val * 10) // same as [10,20,30] , and chaining map method on array will work because you'll get always an Array and you can again use an array prototype method (it works synchronously from left to right)

If you'll try chaining method that doesn't return an array eg [1,2,3].forEach(val => val * 10).map(i => i) , you'll get a TypeError when map will be executed (forEach doesn't return any value, so calling map method on undefined will throw a TypeError). That's how chaining works, you need to use always correct types and be sure that each method is called on correct type (map on Array, toUpperCase on String etc).

Array.prototype.map is a method that is called on an array, applies the given function to each element and returns the modified array . This way, you can call other methods on it. Similar methods are Array.prototype.filter and Array.prototype.reduce . They work in a similar way, as you can chain them as well.

To understand basic chaning lets make a function that removes the first letter of a string, kind of like Array.prototype.shift() ;

// create the strShift function
// it has to be a normal function to access this
const strShift = function(amount = 1){

    // return the output of the function, so that you can 
    // chain another prototypical function
    return this.slice(amount);
}

// add the function to the prototype of String so that its available
// with the dot syntax on all Strings for every future String you 
// create after this point in the code
String.prototype.strShift = strShift;

const myStr = "Hello";
// prints "ello"
console.log(myStr.strShift()) 

JSFiddle Link

With that out of the way, we can look at how chaining and return works at the same time . For that lets make a function that inverts the case of each character in a string.

const strFlipCase = function(){
    // create a temporary variable to then return after the loop.
    const result = [];

    // get an array with each letter
    const strArr = this.split('');

    // loop over the newly created array
    for(let character of strArr){
      // check whether the character is uppercase
      if(character.toUpperCase() === character){
        // character is uppercase so push the lowercase character
        // into the temporary array
        result.push(character.toLowerCase())
      } else {
        // character is lowercase so push the uppercase character
        // into the temporary array
        result.push(character.toUpperCase())
      }
  }
  // temporary array has been filled, return the temporary variable
  // as a string
  return result.join('')
}
String.prototype.strFlipCase = strFlipCase;

const myStr = "Hello";
// prints "hELLO"
console.log(myStr.strFlipCase());

JSFiddle Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM