Functions in JavaScript
Reusable Blocks of Code
As your programs get larger, you will often find yourself writing the exact same logic in multiple places. This violates a core principle of programming called DRY (Don't Repeat Yourself).
Functions solve this. A function is a reusable block of code designed to perform a specific task. You define it once, and then you can "call" it as many times as you want.
Declaring a Function
You create a function using the function keyword, followed by a name, parentheses (), and curly braces {}.
function greetUser() {
console.log("Welcome to Himubey Learn!");
}
// Calling (invoking) the function
greetUser();
greetUser(); // Prints the message twice
Parameters and Arguments
Functions become incredibly powerful when you pass data into them. The variables listed in the function definition are called parameters. The actual values you pass in when calling the function are called arguments.
function addNumbers(num1, num2) {
let sum = num1 + num2;
console.log("The sum is: " + sum);
}
addNumbers(5, 10); // Outputs: The sum is: 15
addNumbers(50, 2); // Outputs: The sum is: 52
The return Statement
Often, you don't want a function to just print something to the console. You want it to calculate a value and give that value back to the rest of your program so you can use it. We use the return keyword for this.
function multiply(a, b) {
return a * b; // Ends the function and spits this value out
}
let result = multiply(4, 5);
console.log(result); // Outputs: 20
Functions are the absolute building blocks of JavaScript. By mastering them, you're officially ready to start writing real logic for your web applications!
💡 Himanshu's Tip:
Try to make your functions do one thing, and one thing only. If you have a function called calculateTaxAndSendEmailAndSaveToDatabase, it's doing way too much! Break it apart into three smaller functions.
Interview Questions
- What is the difference between a parameter and an argument?
- Why is the
returnstatement used in a function? - What does the DRY principle stand for, and how do functions help achieve it?