Index
Overview


This lab is about "arrow functions" (the newer js function type).

Arrow functions have a nice concise syntax.

Syntax


If the function returns a value, the last line of the function must have a return statement.

(an abbreviated version follows)
(<Function Params>) => {
	<Function Body>
	[return <Return Value>]
}
If the function has only one statement it can be put on one line, and we do not need braces or the return keyword (return is implicit).

If there is exactly one function param, the parentheses around it are optional.

Examples follow.
(<Function Params>) => <Function Body>


Examples


For contrast, each example will first show a "traditional function", and then the same logic in an "Arrow-Function".

This function receives one args. It doubles the arg and returns the result.

//Traditional
function doubleIt(x) {
	return 2 * x;
}

//Arrow-Function
const doubleFct = x => 2 * x;

//call arrow function
const result = doubleFct(100);
prn(result);
//200
This function receives two args. It computes the sum of the args, and returns the result.

//Traditional
function computeSum(a, b) {
	return a + b;
}

//Arrow-Function
const sumFct = (a, b) => a + b;

//call arrow function
const sum = sumFct(10, 5);
prn(sum);
//15
It is sometimes useful to handle an indefinite number of args (effectively a list). We use what js calls the rest parameter syntax.

Note that for a multi-line arrow function we use braces and the return keyword.

Note that we mimic the traditional algorithm here (we'll learn an improvement soon)

//Traditional
function computeSum(...numbers) {
	let sum = 0;
	for (let n of numbers) {
		sum += n;
	}
	return sum;
}

//Arrow-Function
const sumFct = (...numbers) => {
	let sum = 0;
	for (let n of numbers) {
		sum += n;
	}
	return sum;
};

//call arrow function
const sum = sumFct(1, 2, 3);
prn(sum);
//6
We can write a function that receives no args, and returns a value.

//Traditional
function getDefaultWidth() {
	return 10;
}

//Arrow-Function
const getDefaultFct = () => 10;

//call arrow function
const width = getDefaultFct();
prn(width);
//10
We can write a function that receives args, and returns no value.

//Traditional
function printValue(value) {
	console.log(value);
}

//Arrow-Function
const fct = value => console.log(value);

//call arrow function
fct('Hello');
//output: Hello
We can write a function that receives no args, and returns no value.

//Traditional
function printDefaultWidth() {
	console.log("200");
}

//Arrow-Function
const fct = () => console.log("200");

//call arrow function
fct();
//output: 200