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: 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...
JavaScript 101: Acing the Interview - The Ultimate Q&A Guide (Part 11) Welcome to the final, and perhaps most practical, session of our JavaScript 101 series. You've learned the syntax, mastered the concepts, and even built a final project. Now, it's time to learn how to articulate that knowledge. Acing a technical interview isn't just about knowing the right answer; it's about explaining it clearly, confidently, and with examples that demonstrate true understanding. This post is your personal interview prep guide. We will cover the most common and crucial junior developer interview questions that have been touched upon throughout this series. We'll break down not just what to say, but how to say it, using real-world analogies to make your answers memorable and impressive. Acing Your Answers: The Structure for Success For each question, a strong answer generally follows this structure: Direct Definition: Start with a clear, concise definition. Key Diffe...
JavaScript 101: Automating Tasks with Loops & Managing Data with Arrays (Part 4) Hello and welcome back! In our last session, we leveled up our program's intelligence with advanced decision-making and took a deep dive into manipulating text with strings. You've learned how to make your code smart. Now, it's time to make it powerful and efficient . Imagine you had to send a personalized email to 1,000 users or calculate the total price of 50 items in a shopping cart. Doing this one by one would be impossible. This is where we introduce two of the most fundamental concepts in all of programming: Loops for automating repetitive tasks, and Arrays for managing lists of data. When you combine loops and arrays, you unlock the ability to process huge amounts of information with just a few lines of code. Let's get started! What You'll Learn in This Session: How to stop repeating yourself using the loop . How to create and manage ordered lists ...
Comments
Post a Comment