Learn JavaScript Β· 4/15

Functions: Reusable Logic Containers

7 min read

Functions: Reusable Logic Containers πŸ“¦

Welcome to the world of JavaScript functions! Think of functions as your personal magic spells. πŸ§™β€β™‚οΈ Instead of writing the same chunk of code over and over again, you can bundle it up into a function and simply call it whenever you need it. This not only saves you a ton of time but also keeps your code clean, organized, and much easier to manage.

The Problem: Imagine you're building a website, and you need to greet the user in three different places. Without functions, you'd have to write console.log("Hello, welcome to our awesome website!"); three separate times. Now, what if you decide to change the greeting? You'd have to find and update every single instance. What a headache! 😩

The Solution: Functions let you write that greeting logic once and reuse it with a simple, memorable name. Change it in one place, and it's updated everywhere. Now that's what I call working smart, not hard. 😎


1. Function Declarations: Defining and Calling Functions πŸ“œ

This is the classic way of creating a function, the bread and butter of your JavaScript journey.

Defining a Function:

To declare a function, you use the function keyword, followed by the name you want to give your function, a set of parentheses (), and then a pair of curly braces {} where you'll write the code you want to reuse.

javascript
function greetUser() {
  console.log("Hello, welcome to our awesome website!");
}

Here, we've created a function named greetUser. The code inside the {} is its "brain."

Calling a Function:

Defining a function is like writing down a recipe. The recipe itself doesn't cook the food. You have to actually follow the steps. Similarly, to make a function do its job, you need to "call" or "invoke" it. You do this by writing the function's name followed by parentheses.

javascript
greetUser(); // This will execute the code inside the greetUser function.

And just like that, "Hello, welcome to our awesome website!" will appear in your console. You can call this function as many times as you like!

An interesting fact: In JavaScript, functions are "first-class citizens." This means you can treat them like any other variable. You can pass them to other functions, return them from functions, and even store them in arrays. It's like having a superpower! πŸ¦Έβ€β™€οΈ


2. Parameters and Arguments: Passing Data into Functions πŸ“₯

Static greetings are a bit boring, right? What if we want to greet a specific user by their name? This is where parameters and arguments come into play.

The Problem: Our greetUser function is great, but it's not very personal. It always says the exact same thing. How can we make it more dynamic?

The Solution: We can make our function accept input, just like a vending machine takes your money and gives you a specific snack.

Parameters: These are like placeholders or variables that you define in the function's parentheses when you declare it.

javascript
function greetUser(name) { // 'name' is a parameter
  console.log("Hello, " + name + "! Welcome to our awesome website!");
}

Arguments: These are the actual values you "pass" into the function when you call it. The arguments will fill the parameter placeholders.

javascript
greetUser("Alice"); // "Alice" is the argument.
// Output: Hello, Alice! Welcome to our awesome website!

greetUser("Bob"); // "Bob" is the argument.
// Output: Hello, Bob! Welcome to our awesome website!

You can have multiple parameters and arguments. Just separate them with commas.

javascript
function showFullGreeting(firstName, lastName) {
  console.log("Greetings, " + firstName + " " + lastName + "!");
}

showFullGreeting("John", "Doe");
// Output: Greetings, John Doe!

Industry Practice: Sometimes, you might call a function without passing all the arguments. To avoid errors, you can set default parameter values.

javascript
function greetWithDefault(name = "Guest") {
  console.log("Hello, " + name + "!");
}

greetWithDefault("Jane"); // Output: Hello, Jane!
greetWithDefault();      // Output: Hello, Guest!

3. Return Values: Getting Data Back Out πŸ“€

So far, our functions have only been performing actions (like logging to the console). But what if you need a function to perform a calculation and give you back the result?

The Problem: Imagine you have a function that calculates the area of a rectangle. You don't just want to see the area printed; you want to be able to use that value in another part of your program, maybe to figure out the cost of carpeting.

The Solution: The return statement allows a function to send a value back to whoever called it.

javascript
function calculateRectangleArea(width, height) {
  const area = width * height;
  return area; // This sends the calculated value back out.
}

When you call this function, it's as if the function call itself becomes the value that it returns.

javascript
const myRoomArea = calculateRectangleArea(10, 5); // myRoomArea is now 50.
console.log(myRoomArea); // Output: 50

const costOfCarpet = myRoomArea * 2; // We can use the returned value!
console.log("The carpet will cost: $" + costOfCarpet); // Output: The carpet will cost: $100

A function stops executing the moment it hits a return statement. It's like the function says, "My job here is done!" and hands back the result.


4. Arrow Functions: Modern, Concise Function Syntax 🏹

JavaScript is always evolving, and arrow functions are a more modern and shorter way to write functions. They were introduced in a version of JavaScript called ES6 and are very popular in the industry.

Here's our calculateRectangleArea function as a traditional declaration:

javascript
function calculateRectangleArea(width, height) {
  return width * height;
}

And here it is as an arrow function:

javascript
const calculateRectangleAreaArrow = (width, height) => {
  return width * height;
};

Notice the => "arrow." For very simple functions that just have one line of code to return, you can make it even shorter!

javascript
const calculateRectangleAreaEvenShorter = (width, height) => width * height;

Wow, that's clean! No function keyword, no curly braces, and no return keyword needed (it's implicit).

When to use them? Arrow functions are fantastic for short, non-complex functions. They have some subtle differences in how they handle the this keyword, which is a more advanced topic, but for many day-to-day tasks, they make your code more readable and concise.


5. Understanding Scope: Global, Local, and Block Contexts πŸŒπŸ“

Scope is a fundamental concept that determines where your variables are accessible in your code. Getting this right will save you from many future bugs!

Global Scope: A variable declared outside of any function has a global scope. It can be accessed and modified from anywhere in your code.

javascript
const globalGreeting = "Hello from the big wide world!";

function sayHello() {
  console.log(globalGreeting); // I can access it from in here!
}

sayHello(); // Output: Hello from the big wide world!
console.log(globalGreeting); // And out here too!

The Danger! Having too many global variables can be messy. It's like putting all your stuff in one giant room. Things can get lost or accidentally changed. It's generally a good practice to limit your use of global variables.

Local (or Function) Scope: Variables declared inside a function are in the local scope of that function. They can only be accessed from within that function.

javascript
function calculate() {
  const localSecret = 42;
  console.log(localSecret);
}

calculate(); // Output: 42
// console.log(localSecret); // This would cause an error! The outside world can't see it.

This is great for keeping variables contained and preventing accidental modifications from other parts of your code.

Block Scope: With the introduction of let and const, JavaScript also got block scope. This means a variable is confined to the {} block it was declared in (e.g., inside an if statement or a for loop).

javascript
if (true) {
  const blockScopedMessage = "You can only see me in this block!";
  console.log(blockScopedMessage); // Output: You can only see me in this block!
}

// console.log(blockScopedMessage); // Error! It doesn't exist out here.

This is incredibly useful for creating variables that you only need temporarily within a specific block of code.


πŸ“š Extra Reading & References

Challenge

You are tasked with creating a utility function for an e-commerce platform.

Write a JavaScript arrow function named calculateOrderTotal.

This function must meet the following requirements:

  1. It must accept three parameters in this specific order: price, quantity, and taxRate.
  2. The taxRate parameter should have a default value of 8, which will be used if no value is provided for it when the function is called.
  3. The function should calculate the subtotal by multiplying price and quantity.
  4. It should then calculate the tax amount to be added. The taxRate is a percentage (e.g., a rate of 8 means 8%).
  5. Finally, it must return the final total, which is the subtotal plus the calculated tax amount.

Expected result

Your solution should be a single constant declaration for an arrow function named calculateOrderTotal.

The function must be defined using arrow syntax (=>). The parameter list should be (price, quantity, taxRate = 8), correctly assigning a default value to taxRate.

Inside the function body, the logic should first compute the subtotal (price * quantity), then compute the tax based on that subtotal and the taxRate percentage (e.g., subtotal * (taxRate / 100)). The function must conclude with a return statement that provides the sum of the subtotal and the tax.

A correct implementation would look like this:

javascript
const calculateOrderTotal = (price, quantity, taxRate = 8) => {
  const subtotal = price * quantity;
  const taxAmount = subtotal * (taxRate / 100);
  return subtotal + taxAmount;
};
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.