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.2 Properties

 

 Chapter 4 Properties


👩‍🎓: Properties in JavaScript and Their Access Methods

In JavaScript, properties are values associated with objects. They can be thought of as characteristics of an object, similar to attributes of real-world objects. For example, the length property of a string object represents the number of characters in that string.

Almost all JavaScript values, except null and undefined, have properties. Accessing a property on null or undefined results in a TypeError, as these values are empty and have no properties.

Property Access Syntax:

  1. Dot Notation: object.property

    • Used when the property name is a simple string and known at the time of coding.

    • Example: myString.length, Math.max

  2. Bracket Notation: object[property]

    • Used when the property name is dynamic or not a valid identifier, like a number or a string with spaces.

    • Here, the expression within the brackets is evaluated to get the property name.

    • Example: object["property name"], array[index]

Properties in Arrays:

  • In arrays, the elements are stored as properties, with numbers (indices) as their names.

  • You must use bracket notation for accessing array elements because dot notation is not compatible with numeric property names.

  • Example: array[0] accesses the first element of the array.

Length Property:

  • The length property of an array returns the number of elements in it.

  • Since length is a valid identifier and known in advance, it's typically accessed using dot notation: array.length.

🎨: Think of an object like a magical book. Each property is like a chapter in the book. Dot notation is like knowing the exact chapter name, so you go directly to it. Bracket notation is like having a riddle that, once solved, tells you the chapter name.

And for arrays, imagine them as a series of boxes on a shelf, each with a number. You use these numbers to open the right box and get the contents inside. The length property is like having a sign on the shelf telling you how many boxes are there.

This approach to handling properties makes JavaScript both versatile and powerful, allowing dynamic access to data within your programs.

👩‍🎓: The most common way to access these properties is through dot notation and bracket notation. Dot notation is straightforward and used when you know the exact name of the property. For example, myObject.propertyName. It's simple and readable. However, it only works with property names that are valid identifiers (like variable names).



🎨: Now, let's talk about bracket notation! It's like the Swiss Army knife of accessing properties. You use it when the property name is dynamic or not a valid identifier. For example, if you have a property name stored in a variable or if the property name is something funky like a space or a special character, you go for myObject["propertyName"] or myObject[variable]. It’s like telling JavaScript, "Hey, evaluate this first, then get me that property!"



⚙️: To give a practical example, consider an array. Arrays in JavaScript use numbers as property names to store elements. You can't use dot notation here because property names are numeric. So, if you have an array myArray and want to access its third element, you use myArray[2].

👩‍🎓: Remember, the length property is unique. It's a standard property for arrays, giving the total count of elements. Since length is a valid identifier and known in advance, you typically use dot notation like myArray.length.

🎨: And here's a twist! Trying to access a property on null or undefined will throw an error because these are non-values in JavaScript. So, if you do something like null.length, JavaScript will be like “Nope, that's not going to work!”



That is great but let’s get some examples:


Let's clarify property access in JavaScript objects with more detailed examples:

1. Basic Object and Property Access:

    • Object Definition:

let person = {
name: "Alice",
age: 25,
occupation: "developer"
};


Access via Dot Notation:

    person.name returns "Alice"

    person.age returns 25

    person.occupation returns "developer"

    Access via Bracket Notation:

    person["name"] returns "Alice"

    person["age"] returns 25

    person["occupation"] returns "developer"



2. Using Functions as Properties:

  • Object with Function Property:

let animal = {
makeSound: function() {
return "meow";
},
species: "cat"
};


Accessing Function Property:

    animal.makeSound returns the function itself.

    animal.makeSound() executes the function and returns "meow".

    animal["makeSound"]() also executes the function and returns "meow".

    Using Dot Notation:

    • animal.name would return the function itself, not execute it.

    • To execute the function and get "meow", you should use animal.name().

    Using Bracket Notation:

    • animal["name"] similarly returns the function itself.

    • To execute the function and get "meow", use animal["name"]().



👩‍🎓: In both dot notation and bracket notation, if the property is a function, you need to add () to actually call the function. Without (), you're merely referencing the function, not executing it.



🎨: Think of animal.name or animal["name"] as a button labeled 'meow'. Just looking at or pointing to the button (animal.name or animal["name"] without ()) won't do anything. You need to press the button (animal.name() or animal["name"]()) to hear the meow sound.

In conclusion, whether you use dot notation or bracket notation, if the property you're accessing is a function, you must include () to invoke or execute that function.





3. Properties with Special Characters or Reserved Keywords:

  • Object with Special Property Names:



let specialObject = {
"2": "two",
"John Doe": "Person"
};


Accessing Properties:

    specialObject["2"] returns "two" (dot notation cannot be used here).

    specialObject["John Doe"] returns "Person".





4. Properties with the Same Name as Methods:

(READ THAT AFTER YOU LEARN ABOUT METHODS AND this.)

  • Object with Property Name Similar to Method:



let car = {
model: "Tesla Model S",
getModel: function() {
return this.model;
}
};


Accessing Property and Method:

  • car.model returns "Tesla Model S".

  • car.getModel() executes the function and also returns "Tesla Model S".





Consider an object representing a car, but this time we'll create a separate function to access the model property instead of using a method within the object:

  1. Object Definition:

    
    
    let car = {
  model: "Tesla Model S"
};

    2.Separate Function to Access the Model:


  1. function getModel(carObject) {
      return carObject.model;
    }
  2. Using the Function:

    • You can now call getModel(car) to get the model of the car, which will return "Tesla Model S".

👩‍🎓: In this revised example, the car object still has a model property. The getModel function is defined outside the object and takes the car object as an argument. When called with car as its argument, getModel(car) returns the value of the model property of the car object.

🎨: Think of getModel as a helpful assistant who can tell you the model of any car you point to. You just need to show the assistant (getModel) the car (car object), and they'll tell you the model ("Tesla Model S" in this case).



👩‍🎓: In summary, dot notation is straightforward for simple, valid identifier names, while bracket notation offers more flexibility, especially with special characters, spaces, or dynamic property names. It's essential to understand the context in which each is used for effective JavaScript programming.



The key differences between dot notation and bracket notation for accessing object properties:

Dot notation is the most common and preferred method for accessing properties with simple, valid names. It's faster and easier to read, especially for short property names.

Bracket notation is more versatile and allows for accessing properties with special characters, functions, array literals, or even computed property names. It's also useful for avoiding potential method conflicts.

In summary:

  • Use dot notation for simple, valid property names.

  • Use bracket notation for properties with special characters, functions, complex expressions, or to avoid method conflicts.

Here's a table summarizing the key differences:



Feature

Dot Notation

Bracket Notation

 

Type of key

Valid identifier

Any valid JavaScript expression

Readability

Easier to read for simple names

More verbose but more flexible

Speed

Slightly faster

Slightly slower due to additional processing

Use cases

Simple property access, preferred for most cases

Accessing properties with special characters, functions, complex expressions, or avoiding method conflicts


Link to the chapter in the book Eloquent Javascript:



Comments