JavaScript Functions
# JavaScript Functions
Imagine you have a recipe for baking a cake. Instead of writing out the entire recipe every single time someone asks how to bake one, you write it on a recipe card, name it "Chocolate Cake", and simply hand them the card when they need it.
In JavaScript, Functions are those recipe cards. They are blocks of reusable code designed to perform a particular task.
1. Introduction
A JavaScript function is executed when "something" invokes it (calls it). Functions are the building blocks of readable, maintainable, and professional code. They prevent you from duplicating code (the "DRY" principle - Don't Repeat Yourself).
2. Learning Objectives
By the end of this chapter, you will be able to:
- Declare and call a function.
- Pass data into functions using parameters and arguments.
-
Return data back out of a function using the
returnkeyword.
- Understand function expressions and anonymous functions.
- Build a working BMI (Body Mass Index) Calculator project.
3. Function Declarations
To create a function, you use the function keyword, followed by a name, parentheses (), and curly braces {}.
To make the function actually run, you must "call" or "invoke" it by writing its name followed by parentheses.
4. Parameters and Arguments
Functions become powerful when you can pass data into them. The variables listed inside the parentheses in the function definition are called Parameters. The actual values you pass to the function when you call it are called Arguments.
5. The return Statement
Sometimes, a function is meant to calculate something and give the result back to you, rather than just printing it to the console or DOM. When JavaScript reaches a return statement, the function stops executing and sends the value back to where it was called.
---
6. Real-world Examples & Code Snippets
Example 1: Basic Function
Example 2: Function with Multiple Parameters
Example 3: Function with a Return Value
Output Explanation: The function calculates 4 * 4 and returns 16. That 16 is then saved into the mySquare variable.
Example 4: The Code AFTER Return Never Runs
Example 5: Default Parameters (ES6)
You can provide default values in case the user forgets to pass an argument.
Example 6: Anonymous Functions
A function without a name is an anonymous function. It is often used when a function is passed as an argument to another function, or tied to an event listener.
Example 7: Function Expressions
You can store a function inside a variable. This is called a function expression.
Example 8: Functions Calling Functions
Functions can call other functions. This is how complex programs are built.
Example 9: Variable Scope Basics in Functions
Variables created inside a function CANNOT be accessed outside of it. (We will cover this deeply in the next chapter).
Example 10: Formatting a Username
A practical function that cleans up dirty user input.
---
7. Common Mistakes for Beginners
-
1.
Forgetting to invoke the function: Writing
function sayHi() { ... }but never writingsayHi();below it. The code inside will never run.
-
2.
Confusing Return with Console.log:
console.log()just prints text for the developer to see.returnactually passes data back to the program so other variables can use it. They are entirely different things.
-
3.
Passing arguments in the wrong order: If you have
function divide(a, b)and you calldivide(2, 10),abecomes 2 andbbecomes 10. Order matters strictly.
8. Best Practices
-
One function, one task: A function should do exactly one thing. If your function is named
calculateTax, it should not also be updating the HTML layout and sending an email.
-
Use descriptive names: Names like
doStuff()orfunc1()are terrible. Use verb-noun pairings likecalculateTotal(),getUserData(), orvalidateEmail().
- Keep them small: If your function is 200 lines long, it should probably be broken down into smaller helper functions.
9. Mini Project: BMI Calculator
Let's build a functional Body Mass Index (BMI) calculator.
HTML:
bmi.js:
How it works: We separated our concerns! One function handles math, one handles text categorization, and the main handler grabs the DOM elements and orchestrates the other functions. This is professional architecture!
10. Exercises
-
1.
Write a function called
multiplyByTenthat takes one parameter, multiplies it by 10, andreturns the result.
-
2.
Call the function you just made, passing the number
5, andconsole.log()the returned result.
-
3.
Write a function called
checkEventhat takes a number, and returnstrueif it is even, andfalseif it is odd. (Hint: Use the modulus%operator).
11. MCQs (Multiple Choice Questions)
Q1: What keyword is used to send a value back out of a function? A) output B) send C) return D) export *Answer: C*
Q2: What are the variables listed inside the parentheses of a function definition called? A) Arguments B) Parameters C) Arrays D) Pointers *Answer: B*
Q3: Which of the following correctly calls a function named myFunction?
A) call myFunction()
B) myFunction;
C) execute myFunction()
D) myFunction()
*Answer: D*
12. Interview Questions
Q: What is the difference between a Parameter and an Argument? *A: A parameter is the variable declared in the function definition (the placeholder). An argument is the actual data value passed into the function when it is called/invoked.*
Q: What happens if a function does not have a return statement, but you try to save its result to a variable?
*A: The function will execute normally, but the variable will be assigned the value undefined, because a function that does not explicitly return a value implicitly returns undefined.*
13. FAQs
Q: Can a function return multiple values? *A: A function can only return one single thing. However, that "thing" can be an Array or an Object that contains multiple pieces of data. (We will learn this in Chapters 10 and 11).*
14. Summary
- Functions package code into reusable blocks.
- You declare a function once, and can call it infinite times.
- Parameters let you pass data into functions.
-
The
returnkeyword stops the function and outputs a value.
- Breaking large programs into small, single-task helper functions is a best practice.