JavaScript : Functions and Passing Arguments (Part 7)
Get link
Facebook
X
Pinterest
Email
Other Apps
JavaScript 101: Deeper into Functions and Data Behavior (Part 7)
Hello and welcome back to the JavaScript 101 series! Over the last several posts, we've built an incredible foundation, moving from basic variables to the complex data structures of arrays and objects. You've learned the "what" and the "how" of writing code.
Today, we're diving into the "why." We'll explore how JavaScript behaves under the hood, understanding the critical difference between how it handles simple data versus complex data. We'll also add some powerful tools to our arsenal, including the built-in Math object and a modern, clean way to write functions called Arrow Functions.
This session is about refining your skills and understanding the concepts that separate a hobbyist from a professional developer. Let's get started.
What You'll Learn in This Session:
How to perform complex calculations using the built-in object.
A modern, concise way to write functions with Arrow Functions.
The fundamental concept of Pass by Value (for primitive types).
The critical concept of Pass by Reference (for objects and arrays).
How to safely merge and copy objects using the Spread Syntax.
Your Built-in Calculator: The Math Object
JavaScript comes with a powerful, built-in object called Math that provides tools and constants for performing complex mathematical tasks. You don't need to create it; it's always available.
Adaptive Example: A Budgeting App Imagine you're building a budgeting tool. Users enter expenses, but you need to handle the decimal values in different ways depending on the feature.
Let's say a user enters $23.61 and $23.45.
1. Rounding to the nearest dollar with This rounds to the nearest whole number (>= .5 rounds up, < .5 rounds down).
2. Always rounding down with Sometimes, you need to find the "floor" or the greatest integer less than or equal to the number.
// Useful for showing the "whole dollar" amount spent
console.log(Math.floor(23.61)); // Output: 23
console.log(Math.floor(23.45)); // Output: 23
3. Always rounding up with The opposite of floor is ceil (for "ceiling"), which always rounds up to the next largest integer.
// Useful for calculating how many containers you need. If you need 2.3 containers, you have to buy 3.console.log(Math.ceil(23.61)); // Output: 24console.log(Math.ceil(23.45)); // Output: 24
The Math object also includes useful constants. The most famous is Math.PI.
There are many more Math methods like Math.random(), Math.max(), Math.min(), and Math.pow(). When you need to do math, always check the MDN first!
A Modern Makeover: Arrow Functions
You already know how to write functions using the function keyword. This is called a function declaration.
// Function Declarationfunctionadd(a, b) {
return a + b;
}
Modern JavaScript (ES6) introduced a more concise and popular way to write functions, especially for simple or anonymous (unnamed) tasks. These are called Arrow Functions.
Let's see the evolution:
Step 1: Function Expression First, we can assign an anonymous function to a variable.
const add = function(a, b) {
return a + b;
};
Step 2: Convert to an Arrow Function Now, we can make this more concise:
Remove the function keyword.
Add a "fat arrow" => between the parameters and the function body.
const add = (a, b) => {
return a + b;
};
The Magic of Arrow Function Shorthands
Arrow functions have some fantastic shortcuts that make code even cleaner.
1. Implicit Return: If your function body is only one line and its purpose is just to return a value, you can remove the curly braces {} and the return keyword. The result of the expression is returned automatically.
// The long wayconst multiply = (a, b) => {
return a * b;
};
// The short, modern way with implicit returnconst multiply = (a, b) => a * b;
console.log(multiply(5, 10)); // Output: 50
2. Omitting Parentheses: If your function has exactly one parameter, you can even omit the parentheses around it.
// The long wayconst square = (x) => x * x;
// The short, modern wayconst square = x => x * x;
console.log(square(9)); // Output: 81
How Data Behaves: Pass by Value vs. Pass by Reference
This is one of the most important concepts for understanding why your code might behave in unexpected ways. It all comes down to how JavaScript passes data into functions.
Pass by Value: "Here's a Photocopy"
Analogy: Imagine your friend has class notes. They give you a photocopy. You take your copy home and scribble all over it, highlighting things and adding diagrams. Does this affect your friend's original notes? Of course not. You only changed your copy.
This is Pass by Value.
It applies to all primitive types: String, Number, Boolean, null, undefined, Symbol, BigInt.
When you pass a primitive to a function, JavaScript creates a copy of that value and gives it to the function. Any changes inside the function happen to the copy, leaving the original untouched.
functiontryToChange(value) {
value = 100; // This only changes the COPY of the value inside the functionconsole.log(`Inside function: ${value}`); // Output: Inside function: 100
}
let originalValue = 50;
tryToChange(originalValue);
console.log(`Outside function: ${originalValue}`); // Output: Outside function: 50 (The original is unchanged!)
Pass by Reference: "Here are the Keys to My Car"
Analogy: Now, imagine your friend gives you the keys to their car. There is only one car. If you take the car and put a scratch on the door, have you changed your friend's car? Yes. You both had access to the exact same car.
This is Pass by Reference.
It applies to all non-primitive types: Object and Array.
When you pass an object or array to a function, JavaScript passes a reference (think of it as a memory address, or the "keys") to the original object.
Both the original variable and the function parameter point to the exact same object in memory. Any changes made inside the function will affect the original object.
functionaddColor(product) {
// This modifies the original object because 'product' is a reference to it
product.color = "Red";
console.log(product.name, "is now", product.color);
}
const myProduct = { name: "T-Shirt", size: "M" };
addColor(myProduct);
console.log(myProduct); // Output: { name: "T-Shirt", size: "M", color: "Red" } (The original object was changed!)
Understanding this difference is critical for debugging and preventing unintended side effects in your code.
The Solution: Safely Merging Objects with Spread Syntax
So, how can you update an object based on another without modifying the original? You create a copy! The modern way to do this is with the Spread Syntax (.
Adaptive Example: Updating a User Profile You have an existing user profile and receive an object with updated information. You want to merge them into a new, fully updated profile.
const existingUser = {
id: 123,
name: "Alex Johnson",
email: "alex.johnson@example.com",
membershipStatus: "active"
};
const updatedInfo = {
email: "alexj@example.net",
age: 29,
membershipStatus: "premium"
};
// Use spread syntax to create a new objectconst updatedUser = {
...existingUser, // 1. Copy all properties from existingUser
...updatedInfo // 2. Copy all properties from updatedInfo, overwriting any duplicates
};
console.log(updatedUser);
// Output:// {// id: 123,// name: "Alex Johnson",// email: "alexj@example.net", // Overwritten// membershipStatus: "premium", // Overwritten// age: 29 // Added// }
The spread syntax creates a new object, effectively giving you a "photocopy" to work with, thus avoiding the Pass by Reference problem.
Conclusion: You Are Ready!
This session pulled back the curtain on some deeper JavaScript concepts. By understanding how data behaves (Pass by Value vs. Reference) and learning the modern syntax for functions and object manipulation, you are now equipped to write code that is not only functional but also clean, efficient, and professional.
This marks the end of our JavaScript 101 series, but it's just the beginning of your journey. You have all the fundamental tools you need. Now, go out and apply them. Build a project, solve a problem, and continue learning. The web is your canvas.
JavaScript 101: The Final Project - Putting It All Together (Part 10) Welcome to the grand finale of the JavaScript 101 series! You have traveled an incredible distance, from the first console.log("Hello, World!"); to mastering complex data structures, functions, and the hidden rules of the JavaScript engine. Now, it's time to put all that knowledge to the test. This final session is a capstone project. We will take a complex problem, break it down into smaller, manageable pieces, and use all the skills you've acquired—variables, operators, logic, loops, functions, and the Math object—to build a complete program from scratch. This isn't just about writing code; it's about thinking like a programmer. Let's build something to be proud of. Today's Mission: The Miraculous Number Checker Our final project is to build a program that determines if a given number plate is "Miraculous" or "Non Miraculous." This might sound whimsical, b...
JavaScript 101: Making Decisions and Reusing Code (Part 2) Welcome back! In Part 1 , we covered the absolute basics: what JavaScript is, how to log messages to the console, and how to store information in variables using let and const . We built the foundation. Now, it's time to start building on it. Storing data is great, but the real power comes when we can do things with that data. In this session, we're going to learn how to perform calculations, make comparisons, and teach our programs to make decisions. We'll also learn the secret to writing efficient, reusable code with functions . Let's get started! What You'll Learn in This Session: How to perform math with Arithmetic Operators . The importance of Operator Precedence (the order of operations). How to compare values using Relational and Logical Operators . How to control the flow of your program with statements . How to write reusable blocks of ...
JavaScript 101: Your First Step into the World of Code (Part 1) Welcome to the start of your programming journey! If you've ever wondered how websites go from being static pages to interactive, dynamic experiences, you're in the right place. The magic behind it all is a powerful language called JavaScript . This series is designed for absolute beginners. We'll start from scratch, and by the end of this first post, you'll not only understand what JavaScript is but also write your very first lines of code. Ready? Let's get our laptops ready and dive in! What You'll Learn in This Session: Why we need JavaScript and where it's used. How to write and see the output of your first program. The basic "ingredients" of code: Primitive Data Types. How to store information using Variables ( var , let , and const ). The do's and don'ts of naming your variables. Why Do We Even Need JavaScript? Imagine you're building a house. HTML (HyperText Marku...
Comments
Post a Comment