A function is a reusable block of code that performs a specific task

 


Keywords

 

• first class function (a programming language is said to have first-class functions if function in that language are treated like other variables)


• named functions

• anonymous functions

• function expression

• callback functions <- a function passed as an argument

• higher-order functions

A higher order function takes a function as an argument

or

A higher order function returns a function

 

• arguments vs parameters

// a and b are parameters
function add( a, b ) {

}


// 3 and 4 are arguments
add(3,4)

 

• event handling in JS

• Pure functions

• Impure functions

• currying functions

• call, apply, bind

 


<html>

<head>

<script>

function talkToMeMan() {
    alert("No way Jose");
}


</script>

</head>

<body>

<button onClick="talkToMeMan()">Talk to me</button>

</body>

</html>

Basic functions

Functions group lines of JavaScript together. Instead of re-writing each line you can just call the function.

Functions with arguments

<html>

<head>

<script>

function talkToMeMan( foobarName ) {
    alert("No way " + foobarName);
}


</script>

</head>

<body>

<button onClick="talkToMeMan('James Brown')">Talk to me</button>

</body>

</html>

 


Functions with return values.

<head>
<script>

// This returns the number 11

function doSomething()
{
    var x=5;
    var y=6;

    return (x+y);
}

</script>

</head>

<body>

<button onclick="alert(   doSomething()   )"> click me </button>


</body>






Pure Functions

Always produces the same output for the same inputs.

Does not have any side effects.

 

Impure Functions

Produces different output because external values have changed.

or

Function has a side effect


Currying

Currying in JavaScript transforms a function with multiple arguments into a nested series of functions, each taking a single argument.

 

Advantage

Reusibility, modularity and specialisation .

Big complex functions can be broken down into small, reusable functions with fewer arguments.

 


Call, apply, bind

These methods provide a way to manipulate the this value and to pass arguments to functions.l

function sayHello(message) {
   console.log(`${message} ${this.name}`)
}


const person = {
  name: 'Boris'
}


// How to connect this to the object person

sayHello.call( person, "Hello" )


sayHello.apply( person, ["Hi"])


const greetPerson = sayHello.bind(person)

greetPerson("Greetings")

// Greetings Boris