Imagine living in a village without tap water. To get water, you need to take an empty bucket, go to the well, draw water, and return home. Instead of explaining this each time, you can simply say draw water. This is similar to creating a function in programming.
Declaring Functions
A functions is a block of code that performs a task. Here’s the syntax:
function
is the keyword.functionName
is the name of your function.parameters
are optional variables you can pass in.
Using Functions
To use a function, write its name followed by parentheses:
Tips: Use Indentation
Indent code within blocks to make it readable. Use either with 2 spaces or tabs, but stay consistent.
Parameters and Arguments
Function can take parameters, which are variables
Return Statements
A function can return a value:
The value returned by the function can be assigned to a variable. If no return statements is provided, the function
returns undefined
.
The Flow of a Function
- Declare the function.
- call the function.
- Evaluate any expressions.
- Return the result.
Hoisting
Function declared with the function
keyword are hoisted, meaning you can call them before they appear in the code.
Function Expressions
You can also declare functions using expressions like this:
However, function expressions are not hoisted.
“So, it’s not recommended to use declared functions before you declare them, as it can confuse you about the order of your code. Don’t rely on hoisting.”
Notes:
- A function is a block of code that performs a task.
- To call functions, add
()
to their name. - Functions can take arguments and have return values.
- Declare functions before using them to avoid confusion with hoisting.
In short, functions help organize code into reusable blocks, making it easier to perform repetitive tasks efficiently.