JavaScript Functions Explained
In JavaScript, functions are blocks of code designed to perform a specific task. You can reuse functions, pass arguments, and return values.
1. Function Declaration (Named Function)
This is the most common way to define a function.
Example:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice"));
Output
Hello, Alice!
2. Function Expression
Functions can also be assigned to variables.
Example:
const greet = function(name) {
return "Hi, " + name;
};
console.log(greet("Bob"));
Output
Hi, Bob
3. Arrow Function (ES6+)
A shorter syntax introduced in ES6.
Example:
const greet = (name) => {
return "Hey, " + name;
};
console.log(greet("Charlie"));
Output
Hey, Charlie
One-liner version:
const greet = name => "Hey, " + name;
4. Function with Default Parameters
You can give parameters a default value.
Example:
function greet(name = "Guest") {
return "Welcome, " + name;
}
console.log(greet()); // No argument passed
Output
Welcome, Guest
5. Function Returning a Value
Functions can return data to be used elsewhere.
Example:
function add(a, b) {
return a + b;
}
let sum = add(5, 7);
console.log(sum);
Output
12
Summary Table – JavaScript Functions
Type | Syntax Style | Can Be Named? | Introduced In |
---|---|---|---|
Function Declaration | function name() |
Yes | ES1 |
Function Expression | const name = function() |
Optional | ES1 |
Arrow Function | const name = () => |
No name by default | ES6 |