JavaScript : Functions and Passing Arguments (Part 7)

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).

console.log(Math.round(23.61)); // Output: 24
console.log(Math.round(23.45)); // Output: 23

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: 24
console.log(Math.ceil(23.45)); // Output: 24

The Math object also includes useful constants. The most famous is Math.PI.

const radius = 10;
// Circumference = 2 * PI * r
const circumference = 2 * Math.PI * radius;

console.log(circumference); // Output: 62.83185...

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 Declaration
function add(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:

  1. Remove the function keyword.

  2. 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 way
const multiply = (a, b) => {
  return a * b;
};

// The short, modern way with implicit return
const 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 way
const square = (x) => x * x;

// The short, modern way
const 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 typesStringNumberBooleannullundefinedSymbolBigInt.

  • 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.

function tryToChange(value) {
  value = 100; // This only changes the COPY of the value inside the function
  console.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 typesObject 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.

function addColor(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 object
const 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.

Comments

Popular posts from this blog

JavaScript: Data Types and Variables (Part 1)

JavaScript : Acing the Interview - The Ultimate Q&A Guide (Part 11)

JavaScript : Loops and Arrays (Part 4)