When writing programs, we often need to do the same task many times. Instead of repeating code again and again, JavaScript gives us a way to group instructions together and reuse them whenever we want. These reusable chunks of code are called functions.
Think of a function like a recipe: once you write it down, you can use it over and over without rewriting the steps.
🟢 What is a Function?
A function is a block of code that performs a task. You give it a name, and whenever you call that name, the code inside the function runs.
Example:
function sayHello() {
console.log("Hello, world!");
}
sayHello(); // calling (or "invoking") the function
Output:
Hello, world!
🟡 Declaring a Function
There are a few ways to declare (create) functions in JavaScript. The most common are:
1. Function Declaration
function greet() {
console.log("Welcome to JavaScript!");
}
2. Function Expression
const greet = function() {
console.log("Welcome to JavaScript!");
};
3. Arrow Function (modern, shorter syntax)
const greet = () => {
console.log("Welcome to JavaScript!");
};
👉 For beginners, function declarations are the easiest place to start.
🔢 Functions with Parameters
Sometimes we want functions to work with different inputs. We can do this by using parameters.
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Alice");
greetUser("Bob");
Output:
Hello, Alice!
Hello, Bob!
Here, name is a parameter. When we call the function, "Alice" or "Bob" are arguments we pass in.
🎁 Functions that Return Values
Functions don’t just print things — they can also return values for you to use.
function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log(sum); // 8
returnsends a value back from the function.- The returned value can be stored in a variable or used directly.
✍️ Why Use Functions?
- Reusability → write once, use many times.
- Organization → break big problems into smaller pieces.
- Clarity → code becomes easier to read and understand.
🖥️ Where to Run This Code
Like with variables, you can practice functions in your browser:
- Open Chrome (or another browser).
- Right-click → Inspect → Console tab.
- Type in the examples and press Enter.
✨ Key Takeaways
- A function is a reusable block of code.
- Call (invoke) a function by using its name followed by
(). - Functions can take parameters (inputs).
- Functions can return values (outputs).
💡 Bonus: Arrow Functions
As you get more comfortable, you’ll see many developers use arrow functions, a shorter syntax:
const multiply = (a, b) => a * b;
console.log(multiply(4, 3)); // 12
Arrow functions are handy, especially in modern JavaScript, but start with regular function declarations to build a strong foundation.