Calling Functions
So far, we have been defining functions and calling them. It's important to know that calling the function is what actually performs the act of running the function.
Rules
Functions can be called recursively(inside itself).
Functions can be called inside of other functions.
File Location
We will be working in the following file:
javascript-library
└── 0-PreWork
└── 1-Fundamentals
└── 1-Grammar-and-Types
└── 2-ControlFlow-and-ErrorHandling
└── 3-Loops
└── 4-Functions
03-calling-functions.js <----You will be working in this file.
Example
Let's look at an example of a function that multiplies a number times itself.
We declare the function:
We call the function
//1 function getSquare(number){ return number * number; } //2 getSquare(5);
Hoisting Review
Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code), as in this example:
console.log(addNumbers(5,7));
/* ... */
function addNumbers(a, b) { return a + b; }
The scope of a function is the function in which it is declared, or the entire program if it is declared at the top level.
Function Expressions
Remember that function expressions can't be hoisted. This works only when defining the function using the above syntax (i.e. function funcName(){}). The code below will not work. That means, function hoisting only works with function declaration and not with function expression.
Notice below that a function expression is getting created.
The function is being called. It will throw an error saying addNumbers is not a function.
//2
console.log(square(5, 7));
//1
var addNumbers = function(a, b) {
return a + b;
}
Recursion
A recursive function calls itself. We'll talk more about recursion later. Also, this timer could be done with a while loop, but for demo purposes, this works:
var timer = function(seconds){
if (seconds > 0){
console.log(seconds)
return timer(seconds-1)
}else{
return seconds
}
}
timer(10);
Last updated