153. Advanced Functions

변지영·2022년 1월 21일
0
function first() {
	var greet = 'Hi';
	function second() {
		alert(greet);
	}
	return second;
}

var newFunc = first();
newFunc();

We're going to convert this to advanced functions.

const first = () => {
	const greet = 'Hi';
	const second = () => {
		alert(greet);
	}
	return second;
}

const newFunc = first();
newFunc();

closures

const first = () => {
	const greet = 'Hi';
	const second = () => {
		const name = "bobby";
		alert(greet);
	}
	return second;
}

const newFunc = first();
newFunc();


//Closures - a function ran. the function executed. It's never going to execute again.
// BUT it's going to remember that there're references to those variables.
//so the child scope always has access to the parent scope.

Will first function have access to bobby? No.
Children always have access to their parents scope, but parent scope don't have access to their children.

Currying

//Currying - only accept one parameter at a time.

const multiply = (a, b) => a * b;
const curriedMultiply = (a) => (b) => a * b;
curriedMultiply(3);

const multiply = (a, b) => a * b;
const curriedMultiply = (a) => (b) => a * b;
const multiplyBy5 = curriedMultiply(5);

Compose

const compose = (f, g) => (a) => f(g(a));

const sum = (num) => num + 1;

compose(sum, sum)(5);

f(g(5)) - sum(sum(5)) - sum(6) - 7

Avoiding Side Effects, functional purity

side effect: Inside of the function that we don't really know anything about, if it interacts or reads or writes to external variable, for example, or console logs

var a = 1;
function b(){
	a =2;
}

This is side effects.
Remember, we want to think of functions as its own universe and if it starts affecting the outside world.

By avoid side effects and always returning, we create something that we call deterministic.

determinism

Where anything you put into the function, it returns same thing.

0개의 댓글