+ 1
What is meant by "call a function"? And how to call a function?
Explain
5 Réponses
+ 9
declaring a function
function dance(){
alert("I'm dancing");
}
calling a function
dance();
//all blocks of code in dance are executed
+ 5
Calling a function means executing the lines of code that are inside the function and within the scope of the function.
+ 5
Before calling a function, you must know what is a 'function'. A function (or method in OOP), is a collection of expressions and statements. Usage of a function is normally to form a reusable piece of code which does not require you to rewrite the same logic again.
This means that you can 'call' the 'same' piece of code as a 'function' in the future as a line rather than multiple lines of same logic.
For example, in Python, we define a simple factorial function:
def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num - 1)
If we want to calculate factorial of 5, we could 'call' the factorial function rather than write the above 4 lines of code:
>>> factorial(5)
120
There are actually (many?) ways to call a function depends on what language you use. But the most basic one is:
function name + a pair of parenthesis/bracket
e. g, example_function()
And if in the future you want to calculate factorial of 6, you don't need to write again the 4 lines of code. Instead, you'll just need to 'call' the factorial function:
>>> factorial(6)
720
That's basically why we need function and how to call a function.
+ 4
In addition to what is already said, when you call a function your code jumps from the line where you called to the line where function is defined. It executes the entire code inside the function, jumps back to the next line where function was called, continuing with the rest of the code. You may again call the same function, as many times you want.
Apologies, if you know it already :)
+ 3
e.g.
defining a function
function x{
alert("ok!");
}
calling the function
x();