Lesson 2 Review
In our last lesson, we learned how to use Conditional Statements (if / else) and Strict Equality (===) to make logical decisions. But what if you need to run that same exact logic 50 times across your website? Copying and pasting the code 50 times is terrible engineering. Today, we solve that with Functions.
Step 1: Function Declarations (The Blueprint)
A function is a reusable block of code designed to perform a specific task. You write the code once, and then you can "call" it (execute it) as many times as you want.
There are two parts to using a function:
- Declaring it: Creating the blueprint using the
functionkeyword. - Calling it: Telling the browser to actually run the blueprint using parentheses
().
The JavaScript: Creating and Calling a Function
function greetUser() {
console.log("Hello! Welcome to our application.");
console.log("Loading your dashboard...");
}
// 2. Call the Function (If you forget the parentheses, nothing happens!)
greetUser();
greetUser(); // Runs the code a second time!
Step 2: Parameters and Arguments (Dynamic Data)
A function that does the exact same thing every time isn't very useful. We want to pass dynamic data into the function so it can calculate different results. We do this using Parameters and Arguments.
- Parameters: The empty placeholders defined inside the parentheses when you create the function.
- Arguments: The actual real data you pass into the parentheses when you call the function.
The JavaScript: Making it Dynamic
function registerUser(name, age) {
console.log("User Registered: " + name);
if (age >= 18) {
console.log("Access level: Adult");
} else {
console.log("Access level: Minor");
}
}
// "Alice" and 25 are Arguments (the actual data being passed in)
registerUser("Alice", 25);
registerUser("Bob", 16);
Console Output:
> Access level: Adult
> User Registered: Bob
> Access level: Minor
Step 3: The Return Statement (Giving Data Back)
So far, our functions just print messages to the console. But in real software engineering, you usually want a function to calculate a math equation and give the final answer back to the rest of your program so you can use it somewhere else (like displaying it on the screen in HTML).
To do this, we use the return keyword. Important: The moment a function hits a return statement, the function immediately stops running. Any code written beneath a return statement will never execute.
The HTML & JavaScript: Using Returned Data
<div id="cart-total"></div>
/* JavaScript */
function calculateTax(price) {
let taxAmount = price * 0.08; // 8% Tax
let finalPrice = price + taxAmount;
// Send the final number BACK to whoever called the function!
return finalPrice;
}
// We call the function and catch the returned value in a new variable
let checkoutTotal = calculateTax(100);
// Now we can inject that returned data into our HTML
document.getElementById("cart-total").innerHTML = "Total: $" + checkoutTotal;
HTML Output:
Step 4: Arrow Functions (Modern ES6 Syntax)
In 2015, JavaScript introduced a newer, shorter way to write functions called Arrow Functions. You will see this syntax everywhere in modern frameworks like React and Node.js.
Instead of using the function keyword, you store the function inside a const variable and use a "fat arrow" =>.
The JavaScript: Traditional vs Arrow Syntax
function multiply(a, b) {
return a * b;
}
// Modern Arrow Function Syntax
const multiplyArrow = (a, b) => {
return a * b;
};
// They are called the exact same way
console.log( multiplyArrow(5, 5) ); // Outputs 25
Step 5: Scope (Where Does Data Live?)
This is a critical concept. Scope determines where your variables are allowed to be seen and used.
- Global Scope: Variables created outside of any function. They can be seen and used by absolutely any code in your file.
- Local (Block) Scope: Variables created inside a function (or an
ifstatement). They are locked inside those curly braces{}. The rest of the program cannot see them. When the function finishes running, those local variables are destroyed!
The JavaScript: Scope Traps
function startLevel() {
let secretKey = "XYZ-99"; // LOCAL: Only startLevel() can see this
console.log(playerName + " started the level."); // Works fine!
}
startLevel();
// This will cause a FATAL ERROR because secretKey is locked inside the function!
console.log(secretKey); // ReferenceError: secretKey is not defined
Final Quiz: Test Your JavaScript Logic
Click the buttons below to verify your knowledge.
2 Comments
ReplyDeletefunction greet(name) { //This is function declaration
console.log("Hello "+name+" Good Morning");
}
greet("Nagendra"); //name = Nagendra
greet("Alice"); //name = Alice
greet("Bob"); //name = Bob
// Functions are reusable blocks of code that perform a specific task. They allow us to organize our code and avoid repetition. In this example, we have defined a function called greet that logs a greeting message to the console. We can call this function multiple times to display the message whenever needed.
function sum(a,b) { // a,b are parameters
ReplyDeleteconsole.log("The sum is: " + (a + b) ); //Debugging purpose
}
sum(5,10); //5,10 are arguments
sum(2,4); //2,4 are arguments
//This is a single line comment
/*
This is a
multi-line comment
*/