function greet() {
console.log("Hello!");
}
// Call the function
greet();
Functions allow you to group multiple lines of code under a single name. Instead of writing the same logic 10 times, you write it once in a function and "call" it whenever you need it.
function greet(userName) {
console.log("Welcome, " + userName);
}
// Passing data
greet("John");
greet("Sundhar");
Parameters act as placeholders. When you call the function, you pass in real data (arguments) that the function uses to perform its task uniquely for that specific input.
function add(a, b) {
return a + b;
}
// Storing the result
let result = add(2, 3);
console.log(result); // 5
The return keyword stops the function and sends a value back to wherever it was called. Think of it like a chef finishing a meal and "returning" it to the waiter.