A simple guide for beginners — if you know basic math, you can learn this!
A function is a set of instructions you write once and use many times.
Think of it like a vending machine — you press a button (call the function), it does its job, and gives you something back.
function sayHi() {
console.log("Hi!");
}
sayHi(); // Hi!
sayHi(); // Hi! (use it again!)function greet(name) {
console.log("Hi, " + name + "!");
}
greet("Vivek"); // Hi, Vivek!const greet = function(name) {
console.log("Hi, " + name + "!");
};
greet("Priya"); // Hi, Priya!const greet = (name) => {
console.log("Hi, " + name + "!");
};
// Even shorter (one line):
const greet = (name) => console.log("Hi, " + name + "!");
greet("Shankar"); // Hi, Shanker!💡 All three do the same thing. Arrow functions are the most popular today 😊.
Parameter = the placeholder (in the definition)
Argument = the real value (when you call it)
// 👇 parameters
function add(num1, num2) {
console.log(num1 + num2);
}
// 👇 arguments
add(10, 5); // 15
add(3, 7); // 10Use return when you want the function to give you a result.
function multiply(a, b) {
return a * b;
}
const answer = multiply(4, 5);
console.log(answer); // 20
⚠️ Afterreturn, the function stops. Nothing below it runs.
function check(age) {
if (age >= 18) return "Adult";
return "Minor"; // only runs if age < 18
}
console.log(check(20)); // Adult
console.log(check(15)); // MinorSet a backup value in case nothing is passed.
function welcome(name = "Guest") {
console.log("Welcome, " + name + "!");
}
welcome("Priya"); // Welcome, Priya!
welcome(); // Welcome, Guest!Variables inside a function stay inside — they can't be used outside.
function myFunc() {
const secret = "I'm inside!";
console.log(secret); // ✅ Works
}
myFunc();
console.log(secret); // ❌ ERROR — secret doesn't exist here// ❌ Forgetting () when calling
sayHi; // Does nothing
sayHi(); // ✅ This works
// ❌ Forgetting return
function square(n) {
n * n; // result is thrown away!
}
function square(n) {
return n * n; // ✅ Now it works
}
// ❌ Using a variable outside its scope
function test() {
const x = 10;
}
console.log(x); // ❌ ERROR// Declaration
function name(param) { return value; }
// Expression
const name = function(param) { return value; };
// Arrow
const name = (param) => value;
// Default param
function name(param = "default") { }
// Multiple params
function add(a, b) { return a + b; }Remember: Write once, use many times. That's the power of functions! 💪😀