What are Functions?
- Functions are reusable code blocks designed for particular tasks .
- Functions are executed when they are called or invoked .
- Functions are fundamental in all programming languages .
Program:*
function sayHello() {
console.log("Hello");
}
console.log("Hello")
Output:
Hello
Calling a Function
Calling a function means executing or running the function.
After creating a function, we can call it by using the function name followed by parentheses ().
Example
function greet() {
console.log("Hello");
}
greet();
greet() is used to call the function. When the function is called, the code inside the function is executed.
Output:
Hello
Function Parameters
- Parameters allow us to send values to a function.
- Parameters are written inside parentheses
()when we define a function. - The values passed to the function are called arguments.
Example
function add(a, b) {
console.log(a + b);
}
add(10, 5);
Output:
15
Function Return Values
- A function can return a value to the code that called it.
- The
returnstatement is used to return a value from a function. - The returned value can be stored in a variable or used in another operation.
Example
function add(a, b) {
return a + b;
}
let result = add(10, 10);
console.log(result);
Output:
20
Here:
-
return a + b→ returns the result from the function. -
add(10, 5)→ calls the function. -
result→ stores the returned value.
Function Arguments
Function parameters and arguments are different.
- Parameters are the names written inside the parentheses when defining a function.
- Arguments are the actual values passed to the function when calling it.
Example
function add(a, b) {
console.log(a * b);
}
add(10, 5);
Here:
-
aandb→ Parameters -
10and5→ Arguments
Simple way to remember:
Parameter = Name
Argument = Value
Top comments (0)