Functions Module #18 Flashcards
How are multiple values from passed parameters returned?
To return multiple values, you can return an object, or an array, like this:
function getData( ) { return ["Flavio", 37] }
let [name, age] = getData( )
How are arrow functions different from “regular” functions?
function getData() { //... }
to
() => { //... }
But.. notice that we don’t have a name here.
Arrow functions are anonymous. We must assign them to a variable.
How are “regular” functions assigned to variables?
When we do so, we can remove the name from the function:
let getData = function( ) { //... }
and invoke the function using the variable name:
let getData = function( ) { //... } getData()
How are arrow functions assigned to variables?
let getData = ( ) => { //... } getData( )
If the function body contains just a single statement, you can omit the curly braces and write all on a single line:
How is data returned in an arrow function?
Arrow functions allow you to have an implicit return: values are returned without having to use the return keyword.
It works when there is a one-line statement in the function body:
const getData = ( ) => ‘test’
getData( ) //’test’
How are default values defined in parameters?
Like with regular functions, we can have default values for parameters, in case they are not passed:
const getData = (color = 'black', age = 2) => { //do something }
and we can only return one value.
Review how functions get nested inside each other and why.
This is very useful because we can create encapsulated code that is limited in its scope by the outer function it’s defined in.
We could have 2 functions define a function with the same name, inside them:
const bark = ( ) => { const dosomethingelse = ( ) => { //some code here } dosomethingelse( ) return "test" }
const sleep = ( ) => { const dosomethingelse = ( ) => { //some code here } dosomethingelse( ) return "test" }
Define recursion.
A function that is "invoked" within itself. Example: function doSomething( ){ console.log('I was called.") doSomething( ) }
How would you write a factorial function
function factorial(n) { return n >= 1 ? n * factorial(n - 1) : 1 }
factorial(1) //1
factorial(2) //2
factorial(3) //6
factorial(4) //24
We can also use an arrow function if we prefer:
const factorial = (n) => { return n >= 1 ? n * factorial(n - 1) : 1 }
factorial(1) //1
factorial(2) //2
factorial(3) //6
factorial(4) //24
Finally I know how to do this!!!!!
How do you name an arrow function
You don’t, arrow functions are anonymous
How can you shorten a 1 line arrow function?
Eliminate the curly braces.