Functions: Writing and Converting JS Functions to Arrow Functions

Loading

Functions: jonas schmedtmann (Udemy):
"like a variable but for chunks of code"
"..can receive data or return data back..I like to think of them as machines..like a food processor"
"functions produce values"
"...receive input data, transform data and output data.."
(This means they can have a variable assigned to that value so used in some way, like being logged out.
NB: A parameter is the  memory "placeholder" - like a variable name.
An Argument is the value that goes into that memory space as a parameter.
x = 1 (parameter = argument)
This expression function below has the result value of the function stoerd in "calcAge2". The function and it's year argument can then be assigned as a variable age2 so the result of the return value calc is accessible to be logged to console.
Function expression - "functions produce values"
The function is written but does not have a variable assigned to it until after when the constant age1 = calcAge1(birthyear parameter) is defined in terms of the function being called with it's "1990" parameter so there is a final result value existing in a named memory space to be logged out by console.log(age1)
function calcAge1(birthYear) {   return 2020 - birthYear; } const age1 = calcAge1(1990); console.log(age1);

// 30

 

Function declaration:
The function is "expressed" and it's logic is written as before above (hence expression) but then it is named by the const  variable "calcAge2" being assigned to it at the beginning so it has a name - a memory space - for it and it's internal code to be invoked from later by calcAge2().
The return keyword captures the result of the calculation in that calcAge2 memory space, but we can't access it until a variable, age1 is defined as the mem space for that return result when the function is run by calling it AND so it's result. Then the result of age1 can be displayed as the result value of the internal calculation. If you try to console just the function name, the console will display details of the function type itself, not it's result values.
const calcAge2 = function (birthYear) {   return 2020 - birthYear; }; const age2 = calcAge2(1990); console.log(age2);

// 30

 

Confused yet?? Probably.

 

It's because there are complex encapsulation levels going on here.

 

The calculation result is stored in the return keyword, which is stored in the function name calcAge2, which can take an external parameter stored in (birthYear), which came in the form of a number value (1990), set by a human as input data, so becomes an alias for (birthYear) inside the function calculation that works out that calculation = 2020 - 1990 = 30, which can then finally be logged out as useable data by the console.log(age2) function, where age2 has become the alias for the final result!  (See why JS is regarded as difficult to learn by many?) Following this process takes time and practise to understand what exactly is going on in JS code (or most languages for that matter).

 

// A MAIN difference to realise is that a declaration is HOISTED but an expression is NOT ! IF the TTBottom order of the expression is reversed it errors!
Declaration:
function calcAge1(birthYear) {   return 2020 - birthYear; } const age1 = calcAge1(1990); console.log(age1);

// 30

Expression:

const age2 = calcAge2(1990); const calcAge2 = function (birthYear) {   return 2020 - birthYear; }; console.log(age2);

// script.js:73 Uncaught ReferenceError: Cannot access 'calcAge2' before initialization at script.js:73:14

This function DOES receive and return data from outside itself when "called" or "run" or "invoked" or "executed":
Fruit Processor:
function fruitProcessor(apples, oranges) { const juice = `Juice with ${apples} apples and ${oranges} oranges.`; return juice; } const appleJuice = fruitProcessor(5, 0); console.log(appleJuice); const appleOrangeJuice = fruitProcessor(2, 4); console.log(appleOrangeJuice);

// Juice with 5 apples and 0 oranges.

// Juice with 2 apples and 4 oranges.

Function Declarations vs. Expressions
function calcAge1(birthYear) { return 2020 - birthYear; } const age1 = calcAge1(1990); console.log(age1);

 

Jonas' simple Arrow func expression conversion example:

function calcAge1(birthYear) { return 2020 - birthYear; } const age1 = calcAge1(1990); console.log(age1);

// 30

 

A bit of JS shorthand goes on here for same result!:

const calcAge = birthYear => 2022 - birthYear console.log(calcAge(1964))

// 58

 

So, how to do it in steps from original function logic?

1: Wite your require logic result (e.g. calculting an age from a given year of birth (1964) up to the current year  2022 )

birthYear => 2022 - birthYear
2: As the return keyword is implicit in an Arrow func, it's not required, but a variable name placeholder for the calculation IS:
const calcAge = birthYear => 2022 - birthYear
That's IT! The simplest of Arrow functions - just need to invoke it with a parameter year and log out the result now:
console.log(calcAge(1964))
// 58
Note that Arrow functions are not hoisted (moved above their variable defs on script load), similar to function expressions, though declarations ARE hoisted.
Kyle's Cook's Arrow conversion example - the initial function declaration:
function sum(a, b) { return a + b; } console.log(sum(1, 2));

// 3

Process: you dont use func keyword but use a variable name:
1: "function sum" becomes "let sumArrow": 
2: let sumArrow = (a,b)
3: put => between () and {}:
let sumArrow = (a,b) => {}
e.g Do logic for func with required args (maths etc) - a simple calculation eg. x = a + b, but then sub the = for an arrow => to get x => (a+b)
4: put same original function code in {}
let sumArrow = (a,b) => {return a + b;}
5: change func names when calling new func: sum(1,2) becomes sumArrow(1,2)
let sumArrow = (a, b) => {   return a + b; }; console.log(sumArrow(1, 2));

//  3

 

Here's some practise writing standard functions:

https://www.teaching-materials.org/javascript/exercises/functions

e.g:

function celsiusToFahrenheit(celsius) {
  fahrenheit = celsius * 1.8 + 32;
  console.log(`${fahrenheit} F is ${celsius} C`);
}
celsiusToFahrenheit(0);
function fahrenheitToCelsius(fahrenheit) {
    celsius = (fahrenheit - 32) / 1.8
    console.log(`${celsius} C is ${fahrenheit} F`);
}
fahrenheitToCelsius(0)