Skip to content

Latest commit

 

History

History
80 lines (66 loc) · 2.08 KB

File metadata and controls

80 lines (66 loc) · 2.08 KB

Table of Contents

🧠 What are Functions?

Functions are blocks of reusable logic designed to perform a specific task. Instead of repeating the same code again and again, you wrap it in a function and reuse it with different inputs to produce different results. This helps keep your code DRY (Don't Repeat Yourself).

Think of a function like a vending machine:

  • Input (Parameters): You give it money and an item code.
  • Logic (Function Body): The internal machinery processes the request (hidden from the user).
  • Output (Return Value): It dispenses your selected item.

By using functions, you make your code:

  • Modular: Break complex problems into smaller, manageable steps.
  • Maintainable: Update the logic in one place, and it updates everywhere the function is used.
  • Readable: Give descriptive names to blocks of code so others can easily understand what it does.

Function Declarations

function greet() {
console.log("Welcome to Sheryians!");
}
greet();

You define it once, then call it whenever needed.


Parameters vs Arguments

function greet(name) {
console.log("Hello " + name);
}
greet("Harsh");
  • name is a parameter
  • "Harsh" is the argument you pass

Return Values

function sum(a, b) {
return a + b;
}
let total = sum(5, 10); // total is 15
  • return sends back a result to wherever the function was called
  • After return , function exits

Function Expressions

const greet = function () {
console.log("Hello!");
};
  • Functions stored in variables.
  • Cannot be hoisted (you can’t call them before they’re defined)

Arrow Functions

const greet = () => {
console.log("Hi!");
};
  • Cleaner syntax
  • No own this , no arguments object