Skip to main content

5. 7 Summarizing with reduce

 Summarizing with reduce   Understanding Reduce Purpose of Reduce : reduce is a higher-order function used to compute a single value from an array. It's instrumental in operations like summing up numbers or finding an item in an array that meets a specific criterion (e.g., the script with the most characters). Operation : It works by repeatedly taking an element from the array and combining it with a current value until all elements have been processed. This process is akin to folding or reducing the array into a single value. 🎨: Think of reduce like making juice from oranges. You start with a bunch of oranges (the array), and then you squeeze them one by one into a jug (the single value). Your hands (the combining function) do the squeezing, and you might already have some juice in the jug to start with (the start value). 👩‍🎓: The Mechanics of reduce - The reduce function takes three arguments: the array to reduce, a combining function, and a starting value. The combin...

Chapter 4.8 Array loops

 

Array loops

 
The explanation  provided  in this section shows two different ways to loop through arrays in JavaScript: the traditional for loop and the more modern for...of loop. Let's break down each one for clarity:
 

Traditional for Loop


for (let i = 0; i < JOURNAL.length; i++) {
  let entry = JOURNAL[i];
  // Do something with entry
}

How It Works

  • Initialization: let i = 0; sets up a counter i, starting at 0.
  • Condition: i < JOURNAL.length; means the loop will continue as long as i is less than the length of the JOURNAL array.
  • Increment: i++ increases the counter by 1 after each iteration.
  • Loop Body: Inside the loop, let entry = JOURNAL[i]; accesses each element of JOURNAL using the index i.

Characteristics

  • It gives you control over the index number.
  • You can use the index to access elements in the array.
  • It's a bit more verbose. 

 

Modern for...of Loop


for (let entry of JOURNAL) {
  console.log(`${entry.events.length} events.`);
}

How It Works

  • Syntax: for (let entry of JOURNAL) iterates over each element in the JOURNAL array.
  • Loop Body: In each iteration, entry directly holds the value of the current array element (not the index, but the element itself).

Characteristics

  • It is simpler and more readable for cases where you only need each element and not the index.
  • Directly accesses the element value, making the code cleaner.
  • Works not only for arrays but also for other iterable objects like strings.

Question: I do not understand the following statement:

 console.log(`${entry.events.length} events.`);

Let's break down the statement console.log(${entry.events.length} events.); to make it more understandable. This line of code is from a JavaScript program and involves a few basic concepts: objects, properties, template literals, and the console.log function.

Understanding the Components

  1. entry: This is a variable that represents the current item in the JOURNAL array that the loop is iterating over. Each entry is an object.

  2. entry.events: In this context, entry has a property named events. The events property is an array containing various events.

  3. entry.events.length: The .length property of an array tells you how many items are in the array. So, entry.events.length gives the number of events in the events array for the current entry.

  4. Template Literals (${...}): This is a feature in JavaScript that allows you to embed expressions inside string literals. The syntax is to wrap the expression with ${}. Here, ${entry.events.length} will be replaced with the actual number of events in the entry.events array.

  5. console.log(): This is a function used in JavaScript to print information to the console (a part of the developer tools in browsers or a terminal in Node.js). It's a way to see the output of your code.

Putting It All Together

  • When the for...of loop iterates over the JOURNAL array, it picks each entry one by one.
  • For each entry, it calculates the number of events using entry.events.length.
  • Then, it prints out a message to the console that tells you how many events are in that entry. The message is constructed using a template literal for readability and ease of including dynamic values (in this case, the number of events).
  • So, if an entry had 3 events, the output would be: 3 events.

Example

Suppose an entry in JOURNAL looks like this: { events: ["eat", "sleep", "code"] }. When this entry is processed by the loop, console.log(${entry.events.length} events.); will output 3 events. because there are three items in the events array.

This way of logging helps in quickly understanding the data structure of each journal entry, particularly the number of events recorded per entry.

 

Summary

  • Traditional for loop: Offers more control (especially if you need the index), but is more verbose.
  • Modern for...of loop: Provides a cleaner and more straightforward way to iterate over elements when the index is not needed. It improves readability and reduces the likelihood of errors (like off-by-one errors) that can happen with index manipulation.

In modern JavaScript development, the for...of loop is often preferred for its simplicity and readability when the specific indices of the array elements are not necessary for the task.

 

ANNEX:

Semantic map: Template literals:

 

A template literal in JavaScript is a way to create strings that can include embedded expressions. Introduced in ES6 (ECMAScript 2015), template literals provide a more readable and convenient syntax to create complex strings. Let's break down the concept:

Basic Structure

  • Syntax: Template literals are enclosed by backticks (`) instead of single (') or double (") quotes.
  • Example: `This is a template literal.`

Embedded Expressions

  • Expressions: You can embed expressions within template literals using ${expression} syntax. The expression inside the curly braces is evaluated and its result is included in the string.

            Example

let age = 25;
let message = `You are ${age} years old.`;
console.log(message); // Output: You are 25 years old.

Multi-line Strings

  • Multi-line Support: Template literals can span multiple lines, making it easier to create multi-line strings without using concatenation or escape characters like \n.
  • Example:


let address = `123 Main St.
Springfield, USA`; 

Tagged Template Literals

  • Advanced Use (not beginner topic): Tagged template literals allow you to parse template literals with a function. The first argument of a tag function contains an array of string values, and the other arguments are related to the expressions.
  • Example:

function tag(strings, value1, value2) {
  // Processing the template literal
}
let a = 5, b = 10;
tag`Sum of ${a} and ${b} is ${a + b}`; 

Why Use Template Literals

  1. Readability and Ease: They make the code more readable, especially when dealing with strings that include variables or expressions.
  2. Functionality: Allow the creation of multi-line strings without concatenation.
  3. Dynamic String Creation: Useful for creating strings dynamically based on variables and expressions.

In summary, template literals are a powerful feature in modern JavaScript, enabling developers to work with strings in a more flexible and expressive way. They are particularly useful when you need to integrate variables, expressions, or multi-line text within strings.

 

Link to the chapter in the book:

 

Comments