Skip to content

Instantly share code, notes, and snippets.

@DevEarley
Last active September 11, 2019 18:02
Show Gist options
  • Save DevEarley/025dbf06ee53d4b8d7e257dd5ba5f5c3 to your computer and use it in GitHub Desktop.
Save DevEarley/025dbf06ee53d4b8d7e257dd5ba5f5c3 to your computer and use it in GitHub Desktop.
First-Class Functions in JavaScript

First-Class Functions in JavaScript

What is a First-Class Citizen?

An entity that supports being passed as an argument, is mutable, can be assigned to a variable or returned from a function.

Functions as arguments

For example:

function sumOperation(values){
	const total = 0;
	values.forEach(x=> total += x);
	return total;
}

function isNegative(value){
	return value<0;
}

function sumIsPositiveCallback(result){
	console.log("success! sum is: ",result);
}


function sumIsNegativeCallback(result){
	console.log("failure! sum is: ",result);
}

function doOperationThenDoCallback(successCallback,failureCallback,operation, hasError,values)
{
	var result = operation(values);
	if(hasError(result)){
		failureCallback(result)
	}
	else{
		successCallback(result);
	}
}

(function(){
	console.clear();
	console.log("Passing Functions as Arguments");
	const goodValues = [1,2,3]
	doOperationThenDoCallback(sumIsPositiveCallback,sumIsNegativeCallback,sumOperation,isNegative,goodValues);

	const badValues = [1,2,-4]
	doOperationThenDoCallback(sumIsPositiveCallback,sumIsNegativeCallback,sumOperation,isNegative,badValues);
})();

Mutating Functions

One use-case for mutating a function is extending a function when you don't have access to the source code. Like a thrid party library that you want to make fit you needs.

function myCurveFunction(x){
	let y  = x * x / 3;
	return y;
}

function thridParty_getVector(curveFunction, x){
	return [x, curveFunction(x)];
}

(function(){
	console.log("Mutating a Function");
	var oldFunction = thridParty_getVector;
	thridParty_getVector = function(curve, values){
		if(typeof(values) === typeof(0)){
			return oldFunction(curve, values);
		}
		if(typeof(values) === typeof([])){
			return values.map(value=>oldFunction(curve, value));
		}		
	}
	
	console.log(thridParty_getVector(myCurveFunction,1));
	console.log(thridParty_getVector(myCurveFunction,[1,2,3]));

})();

See it running here: https://codepen.io/DevEarley/pen/QWLrgrp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment