A function is a block of code that we create to perform a particular task.
Instead of writing the same code again and again we can write it once inside a function and call the function whenever we need it.
Example
javascript
function greet() {
console.log("Hello Raj");
}
greet();
How it works
function greet()
↓
Function is created
↓
Code is written inside {}
↓
greet()
↓
Function is called
↓
"Hello Raj" is printed
Why do we use functions?
Functions help us to:
- Reuse code
- Avoid writing the same code again
- Keep code clean and organized
- Make programs easier to understand
- Perform a specific task whenever needed
Function with Parameters
We can also send information to a function.
javascript
function greet(name) {
console.log("Hello " + name);
}
greet("Raj");
greet("Kumar");
Output:
Hello Raj
Hello Kumar
Herename is called a parameter.
The value "Raj" is called an argument.
A function can also return a value.
javascript
function add(a, b) {
return a + b;
}
let result = add(10, 20);
console.log(result);
Output:
30
Here return sends the result back from the function.


Top comments (0)