Functions: Code Blocks for Specific Tasks
A function is a reusable block of code that performs a specific task.
To create a function, you group one or more lines of code within curly braces { }, forming a block, and give it a name.
function sayHello() { console.log('Hello'); console.log('Nice to meet you'); }
The above function is named sayHello to represent its purpose: printing the messages 'Hello' and 'Nice to meet you'.
Two console.log statements are written inside the function, and the { } curly braces form a single block.
When the function is called, the code inside the function runs, printing the messages 'Hello' and 'Nice to meet you' line by line.
sayHello(); // Outputs 'Hello' and 'Nice to meet you'
Why Use Functions?
The primary purpose of a function is to improve code reusability.
Once a function is defined, it can be called multiple times using its name. This reduces code duplication and improves maintainability.
How to Declare a Function
In JavaScript, you define a function using the function keyword, followed by the function name and parameters.
function add(a, b) { return a + b; }
Here, add is the function's name, and a and b are its parameters.
Inside the curly braces { }, you write the code the function will execute. The return keyword is used to return the result of the function.
How to Call a Function
Calling a function means executing the code inside it.
You call a function by writing its name followed by parentheses ().
const result = add(10, 20); // 30
In the above code, add(10, 20) calls the add function, passing 10 and 20 as arguments.
When the function is called, the parameters a and b receive the values 10 and 20, and the function executes.
The return a + b line inside the function calculates 30 and returns it.
The returned value, 30, is stored in the constant result.
What’s the Difference Between Parameters and Arguments?
- Parameters are variables defined in the function declaration and used inside the function.
- Arguments are the actual values passed to the function when it is called.
function multiply(a, b) { return a * b; } const result = multiply(2, 3); // 6
For example, in the multiply function, a and b are parameters, while 2 and 3 are the arguments passed when the function is called.
What is the most appropriate word to fill in the blank?
Lecture
AI Tutor
Help
Code Editor
Execution Result