What Is a Function in JavaScript?
A function in JavaScript is a reusable block of code that performs a particular task.
Instead of writing the same code again and again, we write it once inside a function and call the function whenever we need it.
Simple Example
function greet() {
console.log("Hello!");
}
greet();
Output:
Hello!
Here:
1.function → keyword used to create a function
2.greet → function name
3.() → parameters go here
4.{ } → contains the code that the function executes
5.greet() → calls/executes the function
Why Do We Use Functions?
The main reason is code reuse.
Without a function:
console.log("Hello John");
console.log("Hello Alice");
console.log("Hello David");
With a function:
function greet(name) {
console.log("Hello " + name);
}
greet("John");
greet("Alice");
greet("David");
Output:
Hello John
Hello Alice
Hello David
1. Function Without Parameters
A function doesn't always need input.
function sayHello() {
console.log("Hello World");
}
sayHello();
2. Function With Parameters
A parameter is a value that the function expects to receive.
function greet(name) {
console.log("Hello " + name);
}
greet("John");
Here:
name
is the parameter.
And:
"John"
is the argument passed to the function.
Think of it like:
Parameter → placeholder
Argument → actual value
Example:
`function add(a, b) {
console.log(a + b);
}
add(10, 20);
`
Output:
30
Here:
a = 10
b = 20
Top comments (0)