This is the second day of my participation in Gwen Challenge

Keep up with the last article, this article mainly introduces several knowledge points of function, such as: what is the function of first-class citizen, pure function

The function is first-class citizen, right?

  • The basic idea of functional programming is to organize code around functions, and naturally, it starts by elevating functions as “first class citizens.”

  • First class citizenship refers to functions having equal status with other data types, such as:

    • Functions can be assigned to variables
    • Functions can be passed as arguments
    • A function can be returned by another function
    • A function can return another function
    • Function can be a parameter
Function greet(name) {return "Hi,I,m" +name} function welcome(user){return function(string){ Return "welcome" +user+ "+string}} var STR = welcome('xiaoming')(' welcome to China ') =" welcome to China"Copy the code

Pure functions

  • Pure function: A function that has no side effects and whose return value is determined only by the input.
  • Side effects: If a function, in addition to returning a value, modifies some other state, or has observable interactions with external functions, etc
// Replace c with d without side effects
var rooms = ["a"."b"."c"]
var newRoomas = rooms.map(function(rm){
  if(rm == "c") {return "d"
}else{
 return rm;
}
})
newRooms =>["a"."b"."d"]
rooms =>["a"."b"."c"]
Copy the code
  • Another example
// Add's impure function definition
var x = 5;
function add( y ){ return y + x }

// How to define a pure function
function addPure( x ){
  return function ( y ) {
     return y + x
  }
}
Copy the code

In the next chapter, let’s take a look at the Currization of functions and see some examples in practice