More on functions
Last week, we started our discussion on JavaScript functions. If you need a recap on functions, these two videos will be helpful.
In this lesson, we dive deeper into more details about functions.
Scope of variables in Functions
Variables defined within the scope of a function has a lifespan within that specific function alone and not available outside of the function in which it was defined. Step through the code snippet and watch the demonstration to see how the scopes of the functions and variables change.
1 function first(val){
2 var name = val
3 console.log(name)
4
5 var addr = "residence"
6
7 function second(val){
8 var name = val
9 console.log(name)
10 }
11
12 second(addr)
13 }
Arrow Functions
We talked a little bit about arrow functions last week, now let's see an example. Instead of the function
keyword, we use an arrow =>
(the equal sign, followed by the greater than symbol). The arrow comes after the list of parameters, and is followed by the function body.
let power = (base, exponent) => {
return base ** exponent;
}
Higher-order Functions
Higher-order functions are functions that operate on other functions, either by taking a function as an argument or by returning a function. In JavaScript, there are a number of built-in higher order functions, that take in functions as arguments.
We saw the map()
function in the previous lesson. The map function takes in a function. You might also have a need to build your own higher-order function.
Let's look at an example of a function that is passed as a parameter to another function.