From 50a927d1e7903394a4ee73b049d9d38b49ab61d6 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 01:43:59 +0000
Subject: [PATCH 01/21] Add new lesson on objects for code organisation
Continuing from https://github.com/TheOdinProject/curriculum/pull/27381
Co-authored-by: Bradley Finney <77649883+takinabradley@users.noreply.github.com>
---
.../organizing_code_with_objects.md | 343 ++++++++++++++++++
1 file changed, 343 insertions(+)
create mode 100644 javascript/organizing_your_javascript_code/organizing_code_with_objects.md
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
new file mode 100644
index 00000000000..3dd18896ac2
--- /dev/null
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -0,0 +1,343 @@
+### Introduction
+
+In our JavaScript fundamentals course, you should have learned the [basics of using objects](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/fundamentals-part-5) to store and retrieve data. In this lesson, we'll start with a little refresher, then explore using objects in more detail. Folks on the Ruby track, you'll have a little more experience with some of these concepts already, but this lesson will still be good to go through as JavaScript is a little more flexible with its use of objects.
+
+### Lesson overview
+
+This section contains a general overview of topics that you will learn in this lesson.
+
+- Using objects to organize data.
+- Using objects to organize functionality.
+- Object methods and the `this` keyword.
+- Public and private interfaces.
+
+### Refresher
+
+There are multiple ways to define objects in JavaScript, but in many cases **object literal** syntax is used as follows:
+
+```javascript
+const myObject = {
+ property: "Value!",
+ otherProperty: 77,
+ "obnoxious property": function() {
+ // do stuff!
+ },
+};
+```
+
+There are also 2 ways to get information out of an object: dot notation and bracket notation.
+
+```javascript
+// dot notation
+console.log(myObject.property); // "Value!"
+
+// bracket notation
+console.log(myObject["obnoxious property"]); // [Function]
+```
+
+Which method you use will depend on context. Dot notation is cleaner and is usually preferred, but there are plenty of circumstances when it is not possible to use it. For example, `myObject."obnoxious property"` won't work because that property is a string with a space in it. Likewise, you cannot use variables in dot notation:
+
+```javascript
+const variable = "property";
+
+// "undefined" because it's looking for a property named "variable" in our object
+console.log(myObject.variable);
+
+// this is equivalent to myObject["property"] and returns "Value!"
+console.log(myObject[variable]);
+```
+
+### Objects as a data structure
+
+You've already been introduced to the basic use of a JavaScript object - storing related information with key/value pairs. This is one of the simplest ways you can begin to organize your code! Take these examples from a 'tic tac toe' game - first without objects:
+
+```javascript
+// without objects
+const playerOneName = "tim";
+const playerTwoName = "jenn";
+const playerOneMarker = "X";
+const playerTwoMarker = "O";
+```
+
+Now using objects:
+
+```javascript
+// with objects
+const playerOne = {
+ name: "tim",
+ marker: "X",
+};
+
+const playerTwo = {
+ name: "jenn",
+ marker: "O",
+};
+```
+
+At first glance, the first doesn't seem so bad.. and it actually takes fewer lines to write than the example using objects, but the benefits of the second approach are huge! Grouping related data together into objects allows you to pass the data around easily. Let me demonstrate:
+
+```javascript
+function printName(player) {
+ console.log(player.name);
+}
+```
+
+This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player's name, you would have to remember the correct variable name and then manually console.log it:
+
+```javascript
+console.log(playerOneName);
+console.log(playerTwoName);
+```
+
+Again, this isn't *that* bad... but what if you *don't know* which player's name you want to print?
+
+```javascript
+function gameOver(winningPlayer){
+ console.log("Congratulations!");
+ console.log(`${winningPlayer.name} is the winner!`);
+}
+```
+
+Or, what if we aren't making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case, using objects to keep track of each particular item's name, price, description and other things is the only way to go. You will continue to use and see objects used in this way throughout the curriculum.
+
+### Objects as a design pattern
+
+The grouping power of objects isn't just useful for organizing data - it's useful for organizing *functionality* as well! Using objects for this purpose is one of the core tenants of Object Oriented Programming (OOP).
+
+The introductory paragraph for Object Oriented Programming on Wikipedia says this:
+
+> Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields (often known as attributes or properties), and code in the form of procedures (often known as methods). In OOP, computer programs are designed by making them out of objects that interact with one another.
+
+Essentially, what this means is that code can be organized into objects that contain not only data, but also **methods** (or functions in an object) that interact with that data.
+
+Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributes of a *thing* are expressed as properties, and the ways you can interact with that thing are expressed as methods.
+
+Let's take an example of some *thing* - we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an "on" state, or an "off" state. These might be expressed as properties of a lightbulb object:
+
+```javascript
+const lightbulb = {
+ color: "cool white", // this lightbulb is white
+ isLit: false, // and is currently "off"
+};
+```
+
+You may want to have the ability to switch a lightbulb from it's unlit state to it's lit state, or vice-versa. To do that, you might add a *method*.
+
+The easiest way to get started creating methods to interact with your objects might be combining Object Literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from.
+
+The following is an example of using the `this` keyword to add two methods to our object, `switchOn`, and `switchOff`:
+
+```javascript
+const lightbulb = {
+ color: "cool white",
+ isLit: false,
+
+ // shorthand syntax for adding methods to objects
+ switchOn() {
+ this.isLit = true;
+ },
+ switchOff() {
+ this.isLit = false;
+ },
+};
+
+lightbulb.switchOn();
+console.log(lightbulb.isLit); // true - we switched it on
+```
+
+These methods use the `this` keyword to refer to the object they get called from (`lightbulb`). The `this` keyword can be used to access and modify properties of an object in exactly the same way you would for any other variable that points to an object.
+
+Feel free to copy this code in the console and experiment with it! If you're inclined, perhaps you could create a method to change the color of the light, as if it's one of those fancy RGB LEDs those gamer nerds and keyboard enthusiasts seem to like so much.
+
+Moving past physical items, we could also try to describe something a little bit more abstract like a game as an object. Since we've already explored Rock Paper Scissors in Foundations, let's use that as an example.
+
+A rock paper scissors game might involve a couple basic things:
+
+- Players' scores
+- The ability to play a round (and playing a round should update a player's score)
+
+And might also include a couple nice-to-haves
+
+- The ability to determine the current winning player
+- The ability to restart the game
+
+So, at its most basic, an object that represents the game might look something like this (assuming we're playing against a computer player):
+
+```javascript
+const rps = {
+ playerScore: 0,
+ computerScore: 0,
+ playRound(playerChoice) {
+ // code to play the round... (and update the scores when a player wins)
+ },
+};
+```
+
+And if we fleshed it out, our object may come out to look something like this:
+
+```javascript
+const rps = {
+ playerScore: 0,
+ computerScore: 0,
+ playRound(playerChoice) {
+ /*
+ 1. if an invalid choice is chosen, throw an error
+ 2. get the computer's choice
+ 3. determine the winner using the player's choice and the computer's choice
+ - apply points if necessary to the playerScore/computerScore properties
+ - return who won ('player', 'computer', or 'tie')
+ */
+ },
+ getWinningPlayer() {
+ // return the player with the most points ("player", "computer", or "tie")
+ },
+ reset() {
+ // reset both player's scores to 0
+ },
+};
+
+rps.playRound('rock'); // returns 'player' if we win...
+console.log(rps.playerScore); // ...and our score would have increased
+
+// We also have the ability to check the winning player and reset the game at any time
+console.log(rps.getWinningPlayer()); // "player", if we won above round
+rps.reset();
+```
+
+Take the time to fill in the blanks for the code above, in order to make it work as the comments describe. Use your new knowledge of the `this` keyword to update the player's scores! A working object may be useful for your understanding in the following paragraphs, and provide you with a space to experiment with the ideas in this lesson.
+
+### Private methods/properties
+
+Once you've got a working object that allows you to play rounds of Rock, Paper, Scissors, you may be look at this code and feel that you personally prefer to split your code between more functions/methods than you see here, but also recognize that those functions may not really be a useful interaction point for anyone using your object.
+
+But, there is no rule saying that you can't add those functions to your object as well! A common convention is to prefix methods and properties that you don't intend other people to use with an underscore (`_`). This convention conveys to others that "These things are meant to be used internally by this object, please interact with the other available methods and properties on this object's interface instead"
+
+Another name for properties like this might be **private properties**/**private methods**, and even though object literal syntax doesn't provide a way to truly *prevent* people from accessing them, you will learn in later lessons about other methods of creating objects that *can*.
+
+Some additional methods or properties one might add to *this* object may be:
+
+- A method that grabs a random computer choice
+- A method that determines if two choices are a tie
+- A method that determines if the player is the winner
+- A list containing all the valid choices
+
+Let's see what that looks like!
+
+```javascript
+const rps = {
+ _options: ['rock', 'paper', 'scissors'],
+ _getRandomChoice() {
+ // returns 'rock', 'paper', or 'scissors' randomly
+ },
+ _isTie(playerChoice, computerChoice) {
+ // determines if two choices are a tie, and returns `true` or `false`
+ },
+ _isPlayerWinner(playerChoice, computerChoice) {
+ // returns `true` if the player is the winner, and `false` if not
+ },
+ playerScore: 0,
+ computerScore: 0,
+ playRound(playerChoice) {/* ... */},
+ getWinningPlayer() {/* ... */},
+ reset() {/* ... */},
+};
+```
+
+Private properties/methods aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, even protect certain properties (like the player's scores) from being modified in ways that you may not have intended. Back off, cheaters!
+
+If you feel inclined to create and use any of these new methods or properties in your previous `playRound`, `getWinningPlayer`, or `reset` methods, have at it! You may appreciate some readability gained from extracting logic out into private methods.
+
+### Public interfaces
+
+The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**, or **public properties**/**public methods**. Having a good, well thought out interface on your objects is important - not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future.
+
+This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code.
+
+Furthermore, with the various object creation methods you'll learn throughout this section of the curriculum, you'll be able to easily duplicate and reuse objects like these! Imagine you have an app where users can create and play *multiple* rock-paper-scissor games at once. Managing the data and interacting with each of those games would be no sweat with objects!
+
+
+
+#### Should I use methods to modify properties, or modify them directly?
+
+When using objects as a *data structure* to simply store related some related values together, it's probably just fine to manipulate the data within them directly.
+
+However, once you've grouped data and functionality together in an interactable object, it's best to provide dedicated methods for interacting with objects in pre-defined ways.
+
+Objects can become complicated little machines, and may rely on their properties containing particular values to act properly. Direct access can be like swapping out parts in a running computer, causing unexpected behavior. Methods can act as a safeguard that prevent incorrect values from being assigned.
+
+
+
+### Objects as machines
+
+Sometimes, you may want to create objects that embody complex concepts rather actual, physical items - similar to the RPS game above. Objects can be used to represent almost anything you can think of, and it's impossible to give a comprehensive list of examples. However, a few examples might be:
+
+- An object that manages other objects, such as an "inventory" object that contains a list of items, and actions that can be done with those items.
+- An object that can listen for events that happen, and respond appropriately (think of `.addEventListener` on DOM elements)
+- A "Debt" object that keeps track of a debt owed, how much has been paid, and how much of the debt is remaining.
+
+You may have trouble figuring out what public interface of these objects might contain at first. These sorts of things come with experience, and concepts taught in later lessons can help as well. One way you might conceptualize these objects, though, might be to imagine them as little 'machines' you're making out of code.
+
+The properties of the machine could be thought of displays that might show information such as:
+
+- A list of the items you've collected, the total amount of items you can carry, and how much you're currently carrying
+- A list of functions that are listening for an event
+- The person who owes a particular debt, and the original amount owed.
+
+The methods of your machine might be akin to buttons and such that make the machinde *do* a specific thing, such as:
+
+- Remove an item you own from a list, add a new item, upgrade an item, craft a new item
+- Fire all the functions that are listening to a 'click' event, or add a new function to listen to the 'click' event
+- Pay an amount of money towards a debt, and determine how much more money is owed on a debt
+
+Again, objects can be used to represent almost anything you can think of, the limit is your imagination!
+
+### Assignment
+
+
+
+1. Check out [DevSage's video explanation of the `this` keyword](https://www.youtube.com/watch?v=cwChC4BQF0Q) that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. Don't worry too much about the part on constructor functions at the end, as they will be covered in another lesson.
+
+1. Try modelling the behavior of a piggy bank as an object:
+ 1. You should be able to interact with the object via a method that allows you to deposit coins.
+ - For now, use a string to represent the name of a coin. Ex. `piggyBank.deposit('penny')`
+ - You should keep the coin around by storing it in some kind of list.
+ 1. The object should also have a property or method that tells you how much money you have saved as a number.
+ - For simplicity, using only the smallest subunit of a given currency is acceptable.
+ - Ex: If there are 5 US quarters in the piggy bank, then the number `125` for '125 cents' is acceptable.
+ 1. You should be able to read the list of all coins that are currently in the piggy bank.
+ 1. Add a method to the piggy bank object to remove a specific type of coin from the piggy bank if it's available.
+ - Ensure you can still get the correct savings after removing coins!
+ 1. Lastly, create a way to remove all the money from the jar and start fresh.
+
+1. Try to model something else as an object! Try to keep it simple, but have fun with it!
+
+#### Extra credit
+
+1. You may have exposed the list that the piggy bank uses to track coins as a public property. Depending on how you implemented the piggy bank, modifying this list without using something like a `deposit` or `withdraw` method on the object could throw some of it's properties out of wack, like the one that tells you the amount of savings you've accrued.
+
+ Additionally, adding an unexpected value to this list by modifying it directly could cause errors within your piggy bank methods. Let's try to ensure that doesn't happen!
+ - Indicate that the list of coins the piggy bank uses is a **private property** of the object.
+ - Create a **public method** that gives the user a *copy* of the list that they can manipulate to their hearts content without breaking the piggy bank object.
+
+1. Try creating a couple 'coin' objects to deposit into the piggy bank instead of using a string.
+ - A coin object might contain properties like the name of the coin, and it's value (preferably in the same unit the piggy bank measures it's savings).
+ - Make sure that your piggy bank object is still able to keep track of savings and remove coins correctly after this change!
+ - After making this change, consider how you are calculating savings for the piggy bank compared to before. Do you prefer working with the objects or the strings more?
+ - Consider how the piggy bank might check for a correct string vs checking for an object with the correct properties when depositing. Which seems easier? Does one seem more flexible than the other?
+
+
+
+### Knowledge check
+
+The following questions are an opportunity to reflect on key topics in this lesson. If you can't answer a question, click on it to review the material, but keep in mind you are not expected to memorize or master this knowledge.
+
+- [What are two ways you can use objects to organize code?](#objects-as-a-data-structure)
+- [What is a 'method'?](#objects-as-a-design-pattern)
+- [What is the `this` keyword used for?](#objects-as-a-design-pattern)
+- [What methods should exist as part of an object's public interface?](#objects-as-a-design-pattern)
+
+### Additional resources
+
+This section contains helpful links to related content. It isn't required, so consider it supplemental.
+
+- [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/) covers how `this` changes in various situations.
From 74ae24ad9652c38ff70c8855cc36723e14b40bd8 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 01:50:27 +0000
Subject: [PATCH 02/21] Remove object organisational contents from constructors
lesson
Now in the new "Organizing Code with Objects" lesson
---
.../objects_and_object_constructors.md | 127 +++---------------
1 file changed, 22 insertions(+), 105 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
index c4b302afa34..5496913b3d8 100644
--- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
+++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
@@ -1,108 +1,25 @@
### Introduction
-In our JavaScript fundamentals course, you should have learned the [basics of using objects](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/fundamentals-part-5) to store and retrieve data. Let's start with a little refresher.
-
-There are multiple ways to define objects but in most cases, it is best to use the **object literal** syntax as follows:
-
-```javascript
-const myObject = {
- property: 'Value!',
- otherProperty: 77,
- "obnoxious property": function() {
- // do stuff!
- }
-};
-```
-
-There are also 2 ways to get information out of an object: dot notation and bracket notation.
-
-```javascript
-// dot notation
-myObject.property; // 'Value!'
-
-// bracket notation
-myObject["obnoxious property"]; // [Function]
-```
-
-Which method you use will depend on context. Dot notation is cleaner and is usually preferred, but there are plenty of circumstances when it is not possible to use it. For example, `myObject."obnoxious property"` won't work because that property is a string with a space in it. Likewise, you cannot use variables in dot notation:
-
-```javascript
-const variable = 'property';
-
-myObject.variable; // this gives us 'undefined' because it's looking for a property named 'variable' in our object
-
-myObject[variable]; // this is equivalent to myObject['property'] and returns 'Value!'
-```
-
-If you are feeling rusty on using objects, now might be a good time to go back and review the content in our [object basics lesson](https://www.theodinproject.com/lessons/foundations-object-basics) from our JavaScript Basics course.
+Now that you've got a basic understanding of *why* and *how* you might use objects to organize data and functionality, it's important to learn some basic strategies for creating duplicates (often called **instances**) of objects, and using existing types of objects as a base for creating new ones through **inheritance**.
### Lesson overview
This section contains a general overview of topics that you will learn in this lesson.
+- How the `this` keyword behaves in different situations.
- How to write an object constructor and instantiate the object.
- What a prototype is and how it can be used.
- Prototypal inheritance.
- Basic do's and don'ts of prototypal inheritance.
-- The `this` keyword.
-
-### Objects as a design pattern
-
-One of the simplest ways you can begin to organize your code is by grouping things into objects. Take these examples from a 'tic tac toe' game:
-
-```javascript
-// example one
-const playerOneName = "tim";
-const playerTwoName = "jenn";
-const playerOneMarker = "X";
-const playerTwoMarker = "O";
-
-// example two
-const playerOne = {
- name: "tim",
- marker: "X"
-};
-
-const playerTwo = {
- name: "jenn",
- marker: "O"
-};
-```
-
-At first glance, the first doesn't seem so bad... and it actually takes fewer lines to write than the example using objects, but the benefits of the second approach are huge! Let me demonstrate:
-
-```javascript
-function printName(player) {
- console.log(player.name);
-}
-```
-
-This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player's name, you would have to remember the correct variable name and then manually `console.log` it:
-
-```javascript
-console.log(playerOneName);
-console.log(playerTwoName);
-```
-
-Again, this isn't *that* bad... but what if you *don't know* which player's name you want to print?
-
-```javascript
-function gameOver(winningPlayer){
- console.log("Congratulations!");
- console.log(winningPlayer.name + " is the winner!");
-}
-```
-
-Or, what if we aren't making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case, using objects to keep track of an item's name, price, description and other things is the only way to go. Unfortunately, in that type of situation, manually typing out the contents of our objects is not feasible either. We need a cleaner way to create our objects, which brings us to...
### Object constructors
-When you have a specific type of object that you need to duplicate like our player or inventory items, a better way to create them is using an object constructor, which is just a regular function that by convention is named with an uppercase initial letter. It looks like this:
+Manually typing out the contents of all of our objects with object literals is not always feasible. When you have a specific type of object that you need to make multiple of, a better way to create them is using an object constructor, which is really just a function:
```javascript
function Player(name, marker) {
- this.name = name;
- this.marker = marker;
+ this.name = name;
+ this.marker = marker;
}
```
@@ -117,11 +34,11 @@ Just like with objects created using the Object Literal method, you can add func
```javascript
function Player(name, marker) {
- this.name = name;
- this.marker = marker;
- this.sayName = function() {
- console.log(this.name)
- };
+ this.name = name;
+ this.marker = marker;
+ this.sayName = function() {
+ console.log(this.name);
+ };
}
const player1 = new Player('steve', 'X');
@@ -141,11 +58,11 @@ function Player(name, marker) {
if (!new.target) {
throw Error("You must use the 'new' operator to call the constructor");
}
- this.name = name;
- this.marker = marker;
- this.sayName = function() {
- console.log(this.name)
- };
+ this.name = name;
+ this.marker = marker;
+ this.sayName = function() {
+ console.log(this.name);
+ };
}
```
@@ -210,7 +127,7 @@ The last sub-item needs a little more explanation. What does defining 'on the pr
```javascript
Player.prototype.sayHello = function() {
- console.log("Hello, I'm a player!");
+ console.log("Hello, I'm a player!");
};
player1.sayHello(); // logs "Hello, I'm a player!"
@@ -294,12 +211,12 @@ function Person(name) {
}
Person.prototype.sayName = function() {
- console.log(`Hello, I'm ${this.name}!`);
+ console.log(`Hello, I'm ${this.name}!`);
};
function Player(name, marker) {
this.name = name;
- this.marker = marker;
+ this.marker = marker;
}
Player.prototype.getMarker = function() {
@@ -342,12 +259,12 @@ function Person(name) {
}
Person.prototype.sayName = function() {
- console.log(`Hello, I'm ${this.name}!`);
+ console.log(`Hello, I'm ${this.name}!`);
};
function Player(name, marker) {
this.name = name;
- this.marker = marker;
+ this.marker = marker;
}
// Don't do this!
@@ -355,8 +272,8 @@ function Player(name, marker) {
Player.prototype = Person.prototype;
function Enemy(name) {
- this.name = name;
- this.marker = '^';
+ this.name = name;
+ this.marker = '^';
}
// Not again!
From a52dcc66cc799683b93383cfb6394639aaaaf619 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 02:04:21 +0000
Subject: [PATCH 03/21] Streamline player object example
---
.../organizing_code_with_objects.md | 25 +++++--------------
1 file changed, 6 insertions(+), 19 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
index 3dd18896ac2..fd849c0ddfb 100644
--- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -74,31 +74,18 @@ const playerTwo = {
};
```
-At first glance, the first doesn't seem so bad.. and it actually takes fewer lines to write than the example using objects, but the benefits of the second approach are huge! Grouping related data together into objects allows you to pass the data around easily. Let me demonstrate:
+At first glance, the first doesn't seem so bad... but the benefits of the second approach are huge! Grouping related data together into objects allows you to pass the data around easily. For example:
```javascript
-function printName(player) {
- console.log(player.name);
-}
-```
-
-This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player's name, you would have to remember the correct variable name and then manually console.log it:
-
-```javascript
-console.log(playerOneName);
-console.log(playerTwoName);
-```
-
-Again, this isn't *that* bad... but what if you *don't know* which player's name you want to print?
-
-```javascript
-function gameOver(winningPlayer){
+function gameOver(winningPlayer) {
console.log("Congratulations!");
- console.log(`${winningPlayer.name} is the winner!`);
+ console.log(`${winningPlayer.name} (${winningPlayer.marker}) is the winner!`);
}
```
-Or, what if we aren't making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case, using objects to keep track of each particular item's name, price, description and other things is the only way to go. You will continue to use and see objects used in this way throughout the curriculum.
+Instead of having to have separate parameters for the name and the marker, we have just the one for the entire object and now we have access to all the properties within. If we end up adding more properties to the player objects and needing them in the `gameOver` function, again, we have access to that already since we passed the whole object in, rather than into individual parameters.
+
+But what if we aren't making a simple 2-player game? Something more complicated such as an online shopping site with a large inventory? Using objects to group together each particular item's name, price, description and other things is the only way to go. You will continue to use and see objects used in this way throughout the curriculum.
### Objects as a design pattern
From 0e6468dc662978d6b3f7493f75b3a5cf263eeca0 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 02:32:33 +0000
Subject: [PATCH 04/21] Streamline lightbulb and RPS objects examples
---
.../organizing_code_with_objects.md | 72 +++++++++++--------
1 file changed, 41 insertions(+), 31 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
index fd849c0ddfb..02d3889b00c 100644
--- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -89,13 +89,9 @@ But what if we aren't making a simple 2-player game? Something more complicated
### Objects as a design pattern
-The grouping power of objects isn't just useful for organizing data - it's useful for organizing *functionality* as well! Using objects for this purpose is one of the core tenants of Object Oriented Programming (OOP).
+The grouping power of objects isn't just useful for organizing data, it's useful for organizing *functionality* as well! Using objects for this purpose is one of the core tenants of Object Oriented Programming (OOP), which is a programming paradigm based on the concept of "objects", which can contain data and code: data in the form of fields (often known as attributes or properties), and code in the form of procedures (often known as methods). In OOP, computer programs are designed by making them out of objects that interact with one another.
-The introductory paragraph for Object Oriented Programming on Wikipedia says this:
-
-> Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields (often known as attributes or properties), and code in the form of procedures (often known as methods). In OOP, computer programs are designed by making them out of objects that interact with one another.
-
-Essentially, what this means is that code can be organized into objects that contain not only data, but also **methods** (or functions in an object) that interact with that data.
+This means we're not limited to storing data in objects, we can store logic as well via **methods** (which are just functions that are part of an object), then use those methods to interact with the data.
Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributes of a *thing* are expressed as properties, and the ways you can interact with that thing are expressed as methods.
@@ -108,21 +104,20 @@ const lightbulb = {
};
```
-You may want to have the ability to switch a lightbulb from it's unlit state to it's lit state, or vice-versa. To do that, you might add a *method*.
-
-The easiest way to get started creating methods to interact with your objects might be combining Object Literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from.
+You may want to have the ability to switch a lightbulb from its unlit state to its lit state, or vice-versa. To do that, you might add a method.
-The following is an example of using the `this` keyword to add two methods to our object, `switchOn`, and `switchOff`:
+The easiest way to get started creating methods to interact with your objects might be combining object literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from.
```javascript
const lightbulb = {
color: "cool white",
isLit: false,
- // shorthand syntax for adding methods to objects
- switchOn() {
+ // a method is simply a function assigned to a property
+ switchOn: function() {
this.isLit = true;
},
+ // shorthand for adding a method to an object literal
switchOff() {
this.isLit = false;
},
@@ -132,18 +127,26 @@ lightbulb.switchOn();
console.log(lightbulb.isLit); // true - we switched it on
```
-These methods use the `this` keyword to refer to the object they get called from (`lightbulb`). The `this` keyword can be used to access and modify properties of an object in exactly the same way you would for any other variable that points to an object.
+
-Feel free to copy this code in the console and experiment with it! If you're inclined, perhaps you could create a method to change the color of the light, as if it's one of those fancy RGB LEDs those gamer nerds and keyboard enthusiasts seem to like so much.
+#### Arrow functions and "this"
+
+The `this` keyword behaves differently inside arrow functions compared to traditional function expressions (which includes the shorthand syntax). We don't need to dive into how or why it differs yet, just know that if you used arrow functions in the above example, they would not behave as you expect.
+
+
+
+These methods use the `this` keyword to refer to the object they get called from (`lightbulb`). The `this` keyword can be used to read and assign properties of an object in exactly the same way you would for any other variable that points to an object.
+
+#### Objects for more abstract concepts
Moving past physical items, we could also try to describe something a little bit more abstract like a game as an object. Since we've already explored Rock Paper Scissors in Foundations, let's use that as an example.
-A rock paper scissors game might involve a couple basic things:
+A rock paper scissors game might involve a couple of basic things:
- Players' scores
- The ability to play a round (and playing a round should update a player's score)
-And might also include a couple nice-to-haves
+And might also include a couple nice-to-haves:
- The ability to determine the current winning player
- The ability to restart the game
@@ -155,7 +158,7 @@ const rps = {
playerScore: 0,
computerScore: 0,
playRound(playerChoice) {
- // code to play the round... (and update the scores when a player wins)
+ // code to play the round, update score if needed, then return the result
},
};
```
@@ -167,31 +170,38 @@ const rps = {
playerScore: 0,
computerScore: 0,
playRound(playerChoice) {
- /*
- 1. if an invalid choice is chosen, throw an error
- 2. get the computer's choice
- 3. determine the winner using the player's choice and the computer's choice
- - apply points if necessary to the playerScore/computerScore properties
- - return who won ('player', 'computer', or 'tie')
- */
+ // code to play the round, update score if needed, then return the result
},
getWinningPlayer() {
// return the player with the most points ("player", "computer", or "tie")
},
reset() {
- // reset both player's scores to 0
+ // reset both players' scores to 0
},
};
+```
-rps.playRound('rock'); // returns 'player' if we win...
-console.log(rps.playerScore); // ...and our score would have increased
+Let's play a bit and see who's in the lead!
-// We also have the ability to check the winning player and reset the game at any time
-console.log(rps.getWinningPlayer()); // "player", if we won above round
-rps.reset();
+```javascript
+rps.playRound("rock"); // returns "player" because we're awesome at RPS
+console.log(rps.playerScore); // 1 - we won and so our score increased
+
+rps.playRound("rock"); // returns "computer" because... luck...
+console.log(rps.computerScore); // 1
+
+rps.playRound("scissors"); // returns "player" because we're awesome at RPS (again)
+console.log(rps.playerScore); // 2
+console.log(rps.getWinningPlayer()); // "player" since we're 2-1 up
```
-Take the time to fill in the blanks for the code above, in order to make it work as the comments describe. Use your new knowledge of the `this` keyword to update the player's scores! A working object may be useful for your understanding in the following paragraphs, and provide you with a space to experiment with the ideas in this lesson.
+We've had enough fun for a day so let's reset everything for the next person.
+
+```javascript
+rps.reset();
+console.log(rps.playerScore); // 0
+console.log(rps.computerScore); // 0
+```
### Private methods/properties
From 170ff895c325f44e25f000ced7a2e77b7df28049 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 02:45:15 +0000
Subject: [PATCH 05/21] Remove section on private/public interfaces
Goes beyond a sensible scope for this lesson, involving outdated
practices.
True privacy is covered in later lessons and only an awareness of the
idea of privacy and `_` syntax is sufficient.
---
.../organizing_code_with_objects.md | 65 ++-----------------
1 file changed, 6 insertions(+), 59 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
index 02d3889b00c..0e0c2c884b6 100644
--- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -9,7 +9,6 @@ This section contains a general overview of topics that you will learn in this l
- Using objects to organize data.
- Using objects to organize functionality.
- Object methods and the `this` keyword.
-- Public and private interfaces.
### Refresher
@@ -106,7 +105,7 @@ const lightbulb = {
You may want to have the ability to switch a lightbulb from its unlit state to its lit state, or vice-versa. To do that, you might add a method.
-The easiest way to get started creating methods to interact with your objects might be combining object literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from.
+The easiest way to get started creating methods to interact with your objects might be combining object literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from.
```javascript
const lightbulb = {
@@ -203,64 +202,13 @@ console.log(rps.playerScore); // 0
console.log(rps.computerScore); // 0
```
-### Private methods/properties
-
-Once you've got a working object that allows you to play rounds of Rock, Paper, Scissors, you may be look at this code and feel that you personally prefer to split your code between more functions/methods than you see here, but also recognize that those functions may not really be a useful interaction point for anyone using your object.
-
-But, there is no rule saying that you can't add those functions to your object as well! A common convention is to prefix methods and properties that you don't intend other people to use with an underscore (`_`). This convention conveys to others that "These things are meant to be used internally by this object, please interact with the other available methods and properties on this object's interface instead"
-
-Another name for properties like this might be **private properties**/**private methods**, and even though object literal syntax doesn't provide a way to truly *prevent* people from accessing them, you will learn in later lessons about other methods of creating objects that *can*.
-
-Some additional methods or properties one might add to *this* object may be:
-
-- A method that grabs a random computer choice
-- A method that determines if two choices are a tie
-- A method that determines if the player is the winner
-- A list containing all the valid choices
-
-Let's see what that looks like!
-
-```javascript
-const rps = {
- _options: ['rock', 'paper', 'scissors'],
- _getRandomChoice() {
- // returns 'rock', 'paper', or 'scissors' randomly
- },
- _isTie(playerChoice, computerChoice) {
- // determines if two choices are a tie, and returns `true` or `false`
- },
- _isPlayerWinner(playerChoice, computerChoice) {
- // returns `true` if the player is the winner, and `false` if not
- },
- playerScore: 0,
- computerScore: 0,
- playRound(playerChoice) {/* ... */},
- getWinningPlayer() {/* ... */},
- reset() {/* ... */},
-};
-```
-
-Private properties/methods aren't strictly required, but they can help make the intended use of the object more understandable, and when used thoughtfully, even protect certain properties (like the player's scores) from being modified in ways that you may not have intended. Back off, cheaters!
-
-If you feel inclined to create and use any of these new methods or properties in your previous `playRound`, `getWinningPlayer`, or `reset` methods, have at it! You may appreciate some readability gained from extracting logic out into private methods.
-
-### Public interfaces
-
-The methods and properties you *do* intend for others to use on your objects might be considered your object's **public interface**, or **public properties**/**public methods**. Having a good, well thought out interface on your objects is important - not only because it makes your object pleasant to use by you and others, but also to keep objects flexible and extensible in the future.
-
-This idea of grouping related functionality within an object is *extremely powerful*, and can often result in more organized, understandable code.
-
-Furthermore, with the various object creation methods you'll learn throughout this section of the curriculum, you'll be able to easily duplicate and reuse objects like these! Imagine you have an app where users can create and play *multiple* rock-paper-scissor games at once. Managing the data and interacting with each of those games would be no sweat with objects!
-
-#### Should I use methods to modify properties, or modify them directly?
-
-When using objects as a *data structure* to simply store related some related values together, it's probably just fine to manipulate the data within them directly.
+#### Underscore properties
-However, once you've grouped data and functionality together in an interactable object, it's best to provide dedicated methods for interacting with objects in pre-defined ways.
+Out in the wild, you may see code with object properties that start with `_` e.g. `_someProperty`. This is purely a developer convention that indicates the property is intended to be "private". A private property is one that's only meant for internal use and not meant to be read or called outside of the object itself (such as helper methods).
-Objects can become complicated little machines, and may rely on their properties containing particular values to act properly. Direct access can be like swapping out parts in a running computer, causing unexpected behavior. Methods can act as a safeguard that prevent incorrect values from being assigned.
+JavaScript does not actually have the concept of real private properties for objects, at least not for object literals. Developers historically would add a leading `_` to indicate a property should be treated as if it was private, even if technically they'd still be accessible outside of the object internals ("public"). There are ways to implement actual privacy (which would actually prevent accessing something outside of the object itself) but they involve more advanced things and will be covered in later lessons.
@@ -329,9 +277,8 @@ Again, objects can be used to represent almost anything you can think of, the li
The following questions are an opportunity to reflect on key topics in this lesson. If you can't answer a question, click on it to review the material, but keep in mind you are not expected to memorize or master this knowledge.
- [What are two ways you can use objects to organize code?](#objects-as-a-data-structure)
-- [What is a 'method'?](#objects-as-a-design-pattern)
-- [What is the `this` keyword used for?](#objects-as-a-design-pattern)
-- [What methods should exist as part of an object's public interface?](#objects-as-a-design-pattern)
+- [What is a method?](#objects-as-a-design-pattern)
+- [What is the `this` keyword used for?](#this-keyword)
### Additional resources
From d984df2bc564e70ba99d2c41f2f42ea909fe7229 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 03:01:48 +0000
Subject: [PATCH 06/21] Streamline section on objects as machines
---
.../organizing_code_with_objects.md | 24 +++++++++----------
1 file changed, 12 insertions(+), 12 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
index 0e0c2c884b6..c2f51ef9342 100644
--- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -214,27 +214,27 @@ JavaScript does not actually have the concept of real private properties for obj
### Objects as machines
-Sometimes, you may want to create objects that embody complex concepts rather actual, physical items - similar to the RPS game above. Objects can be used to represent almost anything you can think of, and it's impossible to give a comprehensive list of examples. However, a few examples might be:
+As we've just seen, we can use objects to represent not just physical things but conceptual things too, such as the game of Rock Paper Scissors. Objects can be used to represent almost anything you can think of. It'll be impossible to give a comprehensive list of examples, but some uses include:
-- An object that manages other objects, such as an "inventory" object that contains a list of items, and actions that can be done with those items.
-- An object that can listen for events that happen, and respond appropriately (think of `.addEventListener` on DOM elements)
-- A "Debt" object that keeps track of a debt owed, how much has been paid, and how much of the debt is remaining.
+- An object that manages other objects, such as an "inventory" object that contains item objects in an array, and methods that can be done to interact with that array of items
+- An object that can listen for events that happen and respond appropriately (think of `.addEventListener` on DOM elements)
+- An object that manages all things relating to the DOM, by setting event listeners that call other objects' methods, and displaying data from other objects on the web page.
-You may have trouble figuring out what public interface of these objects might contain at first. These sorts of things come with experience, and concepts taught in later lessons can help as well. One way you might conceptualize these objects, though, might be to imagine them as little 'machines' you're making out of code.
+You may have trouble figuring out what these kinds of objects might contain at first, but these things come with experience, especially with later learning. One way you might conceptualize these objects though, might be to imagine them as little "machines" you're making out of code.
-The properties of the machine could be thought of displays that might show information such as:
+The properties of the machine could be thought as if they were displays that might show information such as:
-- A list of the items you've collected, the total amount of items you can carry, and how much you're currently carrying
+- A list of the items you've collected and the maximum number of items you can carry
- A list of functions that are listening for an event
-- The person who owes a particular debt, and the original amount owed.
+- The DOM elements for the buttons for interaction, and elements for displaying data
The methods of your machine might be akin to buttons and such that make the machinde *do* a specific thing, such as:
-- Remove an item you own from a list, add a new item, upgrade an item, craft a new item
-- Fire all the functions that are listening to a 'click' event, or add a new function to listen to the 'click' event
-- Pay an amount of money towards a debt, and determine how much more money is owed on a debt
+- Remove an item you own from a list and add new items
+- Fire all the functions that are listening to a "click" event, or add a new function to listen to the "click" event
+- Read data from somewhere else and set the `.textContent` of certain DOM elements
-Again, objects can be used to represent almost anything you can think of, the limit is your imagination!
+Again, objects can be used to represent almost anything you can think of. The limit is your imagination!
### Assignment
From 294cf5d840397d03ab5a9581b1dc167556b39482 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 03:33:26 +0000
Subject: [PATCH 07/21] Replace lightbulb example with car
Lightbulb example demonstrated two simple methods but could raise
questions like "why not just assign the property directly?"
Tricky to answer with this example without going off on a tangent, especially given
the removal of the private/public interface content.
The car example's methods should teach the same points but provide a
more justified example of using methods over direct/manual interaction.
---
.../organizing_code_with_objects.md | 46 ++++++++++---------
1 file changed, 25 insertions(+), 21 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
index c2f51ef9342..b4f6038f843 100644
--- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -94,36 +94,40 @@ This means we're not limited to storing data in objects, we can store logic as w
Nearly *anything* you can think about can be described as an object. To do so, all you have to do is ask yourself is "What properties (physical or conceptual) does my thing have?", and "How can I interact with it?". The properties or attributes of a *thing* are expressed as properties, and the ways you can interact with that thing are expressed as methods.
-Let's take an example of some *thing* - we'll choose a lightbulb. A lightbulb can have a color, and it can be in either an "on" state, or an "off" state. These might be expressed as properties of a lightbulb object:
+Let's take an example of some *thing* - we'll choose a car. A car can have a make, model, registration year, color and price. These might be expressed as properties of an object:
```javascript
-const lightbulb = {
- color: "cool white", // this lightbulb is white
- isLit: false, // and is currently "off"
+const car = {
+ make: "Volkswagen",
+ model: "Golf",
+ year: 2026,
+ color: "blue",
+ priceUSD: 40000,
};
```
-You may want to have the ability to switch a lightbulb from its unlit state to its lit state, or vice-versa. To do that, you might add a method.
-
-The easiest way to get started creating methods to interact with your objects might be combining object literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from.
+You may want to have the ability to apply a discount to the car, or get a summary of all of the details in one go. For this, may want to use methods. The easiest way to get started creating methods to interact with your objects might be combining object literal syntax with JavaScript's `this` keyword. The `this` keyword is used to refer to the object a particular method is called from.
```javascript
-const lightbulb = {
- color: "cool white",
- isLit: false,
-
- // a method is simply a function assigned to a property
- switchOn: function() {
- this.isLit = true;
+const car = {
+ make: "Volkswagen",
+ model: "Golf",
+ year: 2026,
+ color: "blue",
+ priceUSD: 40000,
+
+ // a method is just a function assigned to a property
+ applyDiscount: function(discountPercentage) {
+ const multiplier = 1 - discountPercentage / 100;
+ this.priceUSD *= multipler;
},
- // shorthand for adding a method to an object literal
- switchOff() {
- this.isLit = false;
+ // shorthand way to add a method to an object literal
+ getSummary() {
+ return `${this.year} ${this.make} ${this.model} in ${this.color}, priced at $${priceUSD} (USD).`;
},
-};
-lightbulb.switchOn();
-console.log(lightbulb.isLit); // true - we switched it on
+ // ...any other methods...
+};
```
@@ -134,7 +138,7 @@ The `this` keyword behaves differently inside arrow functions compared to tradit
-These methods use the `this` keyword to refer to the object they get called from (`lightbulb`). The `this` keyword can be used to read and assign properties of an object in exactly the same way you would for any other variable that points to an object.
+These methods use the `this` keyword to refer to the object they get called from (`car`). The `this` keyword can be used to read and assign properties of an object in exactly the same way you would for any other variable that points to an object, and we use methods just the same as we might use a function - creating reusable code under an intuitive name. Much nicer than manually writing the logic out each and every time we want to do some of those things.
#### Objects for more abstract concepts
From ad323c3da076668f49bca0a2b9c4d6d53323b3fe Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 18:02:42 +0000
Subject: [PATCH 08/21] Unify quotes style between lessons
Double quotes more commonly used across our whole curriculum for JS
---
.../objects_and_object_constructors.md | 36 +++++++++----------
1 file changed, 18 insertions(+), 18 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
index 5496913b3d8..8da3bd910ab 100644
--- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
+++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
@@ -6,11 +6,11 @@ Now that you've got a basic understanding of *why* and *how* you might use objec
This section contains a general overview of topics that you will learn in this lesson.
-- How the `this` keyword behaves in different situations.
- How to write an object constructor and instantiate the object.
- What a prototype is and how it can be used.
- Prototypal inheritance.
- Basic do's and don'ts of prototypal inheritance.
+- How the `this` keyword behaves in different situations.
### Object constructors
@@ -26,8 +26,8 @@ function Player(name, marker) {
and you can use it by calling the function with the keyword `new`.
```javascript
-const player = new Player('steve', 'X');
-console.log(player.name); // 'steve'
+const player = new Player("steve", "X");
+console.log(player.name); // "steve"
```
Just like with objects created using the Object Literal method, you can add functions to the object:
@@ -41,10 +41,10 @@ function Player(name, marker) {
};
}
-const player1 = new Player('steve', 'X');
-const player2 = new Player('also steve', 'O');
-player1.sayName(); // logs 'steve'
-player2.sayName(); // logs 'also steve'
+const player1 = new Player("steve", "X");
+const player2 = new Player("also steve", "O");
+player1.sayName(); // logs "steve"
+player2.sayName(); // logs "also steve"
```
@@ -178,14 +178,14 @@ What's this `.valueOf` function, and where did it come from if we did not define
How do we know that this `.valueOf` function is defined on `Object.prototype`? We make use of another function called `.hasOwnProperty`:
```javascript
-player1.hasOwnProperty('valueOf'); // false
-Object.prototype.hasOwnProperty('valueOf'); // true
+player1.hasOwnProperty("valueOf"); // false
+Object.prototype.hasOwnProperty("valueOf"); // true
```
Now where did this [`.hasOwnProperty` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) come from? A quick check helps:
```javascript
-Object.prototype.hasOwnProperty('hasOwnProperty'); // true
+Object.prototype.hasOwnProperty("hasOwnProperty"); // true
```
Essentially, this is how JavaScript makes use of prototypes. An object inherits from its `[[Prototype]]` object which in turn inherits from its own `[[Prototype]]` etc., thus forming a chain. This kind of inheritance using prototypes is hence named as Prototypal inheritance. JavaScript figures out which properties exist (or do not exist) on the object and starts traversing the chain to find the property or function, like so:
@@ -220,7 +220,7 @@ function Player(name, marker) {
}
Player.prototype.getMarker = function() {
- console.log(`My marker is '${this.marker}'`);
+ console.log(`My marker is "${this.marker}"`);
};
Object.getPrototypeOf(Player.prototype); // returns Object.prototype
@@ -229,14 +229,14 @@ Object.getPrototypeOf(Player.prototype); // returns Object.prototype
Object.setPrototypeOf(Player.prototype, Person.prototype);
Object.getPrototypeOf(Player.prototype); // returns Person.prototype
-const player1 = new Player('steve', 'X');
-const player2 = new Player('also steve', 'O');
+const player1 = new Player("steve", "X");
+const player2 = new Player("also steve", "O");
player1.sayName(); // Hello, I'm steve!
player2.sayName(); // Hello, I'm also steve!
-player1.getMarker(); // My marker is 'X'
-player2.getMarker(); // My marker is 'O'
+player1.getMarker(); // My marker is "X"
+player2.getMarker(); // My marker is "O"
```
From the code, we can see that we've defined a `Person` from whom a `Player` inherits properties and functions, and that the created `Player` objects are able to access both the `.sayName` and the `.getMarker` functions, in spite of them being defined on two separate `.prototype` objects! This is enabled by the use of the `Object.setPrototypeOf()` function. It takes two arguments - the first is the one which inherits and the second argument is the one which you want the first argument to inherit from. This ensures that the created `Player` objects are able to access the `.sayName` and `.getMarker` functions through their prototype chain.
@@ -273,7 +273,7 @@ Player.prototype = Person.prototype;
function Enemy(name) {
this.name = name;
- this.marker = '^';
+ this.marker = "^";
}
// Not again!
@@ -281,10 +281,10 @@ function Enemy(name) {
Enemy.prototype = Person.prototype;
Enemy.prototype.sayName = function() {
- console.log('HAHAHAHAHAHA');
+ console.log("HAHAHAHAHAHA");
};
-const carl = new Player('carl', 'X');
+const carl = new Player("carl", "X");
carl.sayName(); // Uh oh! this logs "HAHAHAHAHAHA" because we edited the sayName function!
```
From 041e8814b27d1940876ffa291aaf3a9ff4ce7814 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 18:36:34 +0000
Subject: [PATCH 09/21] Streamline hobbit.info() exercise examples
---
.../objects_and_object_constructors.md | 14 ++++++++------
1 file changed, 8 insertions(+), 6 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
index 8da3bd910ab..2c3295544d0 100644
--- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
+++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
@@ -72,17 +72,19 @@ function Player(name, marker) {
Write a constructor for making "Book" objects. We will revisit this in the next project. Your book objects should have the book's `title`, `author`, the number of `pages`, and whether or not you have `read` the book.
-Put a function into the constructor that can report the book info like so:
+Put a function `info()` into the constructor that can report the book info like so:
```javascript
-theHobbit.info(); // "The Hobbit by J.R.R. Tolkien, 295 pages, not read yet"
+console.log(theHobbit.info()); // "The Hobbit by J.R.R. Tolkien, 295 pages, not read yet"
```
-Note: It is almost *always* best to `return` things rather than putting `console.log()` directly into the function. In this case, return the `info` string and log it after the function has been called:
+
-```javascript
-console.log(theHobbit.info());
-```
+#### console.log vs return
+
+We use examples of functions that call `console.log()` for demonstration, but instead of making functions directly log things, it's generally more sensible to make them `return` values. That way, you can pass the values wherever you wish without being tied to whatever that function does; you may not always want to log the value.
+
+
### The prototype
From 0650eca86a98f51a6c2c258fcbfa3e4c44c3443d Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 18:42:42 +0000
Subject: [PATCH 10/21] Clarify behaviour of `new` keyword when calling
functions
---
.../objects_and_object_constructors.md | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
index 2c3295544d0..829c14029d3 100644
--- a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
+++ b/javascript/organizing_your_javascript_code/objects_and_object_constructors.md
@@ -23,14 +23,16 @@ function Player(name, marker) {
}
```
-and you can use it by calling the function with the keyword `new`.
+The only difference is that you use it by calling the function with the keyword `new`:
```javascript
const player = new Player("steve", "X");
console.log(player.name); // "steve"
```
-Just like with objects created using the Object Literal method, you can add functions to the object:
+This is not the same as calling `Player("steve", "X")` (without the `new` keyword).
When we call a function with `new`, it creates a new object, makes `this` inside the function refer to that object, and makes that object inherit from the function's `.prototype` property (more on that later). The new object is then returned (even though we don't specify a `return` value in the constructor function).
+
+Just like with objects created using the object literal method, you can add functions to the object:
```javascript
function Player(name, marker) {
@@ -51,7 +53,7 @@ player2.sayName(); // logs "also steve"
#### Safeguarding constructors
-Note that, as constructors are just regular functions, they could be called without using `new` by mistake, which would cause hard-to-track errors. To prevent that, you can use the `new.target` meta-property like this:
+Since constructors can be called without using `new` by mistake, which would cause hard-to-track errors as it won't do all the new object and `this` binding stuff, we should safeguard them. You can use the `new.target` meta-property like this, which will throw an error if `Player` is called without `new`:
```javascript
function Player(name, marker) {
From b358b93b7b805963622f4a41e1a54a2544503641 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 20:36:42 +0000
Subject: [PATCH 11/21] Rename constructors lesson
Only about constructors now - organisational stuff extracted to separate
lesson
---
...{objects_and_object_constructors.md => object_constructors.md} | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename javascript/organizing_your_javascript_code/{objects_and_object_constructors.md => object_constructors.md} (100%)
diff --git a/javascript/organizing_your_javascript_code/objects_and_object_constructors.md b/javascript/organizing_your_javascript_code/object_constructors.md
similarity index 100%
rename from javascript/organizing_your_javascript_code/objects_and_object_constructors.md
rename to javascript/organizing_your_javascript_code/object_constructors.md
From 7e44a1469f47b6d76461ae34e3a292099dab2931 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Fri, 6 Feb 2026 20:37:58 +0000
Subject: [PATCH 12/21] Remove additional resources from object lessons
Either they'd go out of scope or end up just repeating what the lesson
already covers (or already integrated into the lesson in a previous
change).
---
.../object_constructors.md | 9 ---------
.../organizing_code_with_objects.md | 6 ------
2 files changed, 15 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/object_constructors.md b/javascript/organizing_your_javascript_code/object_constructors.md
index 829c14029d3..94fe54da217 100644
--- a/javascript/organizing_your_javascript_code/object_constructors.md
+++ b/javascript/organizing_your_javascript_code/object_constructors.md
@@ -315,12 +315,3 @@ The following questions are an opportunity to reflect on key topics in this less
- [What is prototypal inheritance?](https://javascript.info/prototype-inheritance)
- [What are the basic do's and don't's of prototypal inheritance?](#recommended-method-for-prototypal-inheritance)
- [How does `this` behave in different situations?](https://www.javascripttutorial.net/javascript-this/)
-
-### Additional resources
-
-This section contains helpful links to related content. It isn't required, so consider it supplemental.
-
-- This [`Object.create` method video by techsith](https://www.youtube.com/watch?v=MACDGu96wrA) provides another point of view on how to use `Object.create` to extend objects by setting the prototype.
-- The first answer on this StackOverflow question regarding [defining methods via the prototype vs in the constructor](https://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype/9772864#9772864) helps explain when you might want to use one over the other.
-- [Interactive Scrim on objects and object constructors.](https://scrimba.com/scrim/co2624f87981575448091d5a2)
-- Check out this video explanation on the [`this` keyword from DevSage](https://www.youtube.com/watch?v=cwChC4BQF0Q) that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly.
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
index b4f6038f843..abad637a1f6 100644
--- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -283,9 +283,3 @@ The following questions are an opportunity to reflect on key topics in this less
- [What are two ways you can use objects to organize code?](#objects-as-a-data-structure)
- [What is a method?](#objects-as-a-design-pattern)
- [What is the `this` keyword used for?](#this-keyword)
-
-### Additional resources
-
-This section contains helpful links to related content. It isn't required, so consider it supplemental.
-
-- [JavaScript Tutorial's article on the `this` keyword](https://www.javascripttutorial.net/javascript-this/) covers how `this` changes in various situations.
From a9f925012c8128b30f2b0f831d126b3dbf3f8272 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Sun, 8 Feb 2026 17:33:17 +0000
Subject: [PATCH 13/21] Add brief mention of namespacing
Just introducing the term.
Considered putting it in a separate small section before the data
structure bit, but felt it would put too much weight on the idea and
people would start looking too deeply into namespacing in isolation.
---
.../organizing_code_with_objects.md | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
index abad637a1f6..46b7edfd2ae 100644
--- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -73,7 +73,9 @@ const playerTwo = {
};
```
-At first glance, the first doesn't seem so bad... but the benefits of the second approach are huge! Grouping related data together into objects allows you to pass the data around easily. For example:
+At first glance, the first doesn't seem so bad... but the benefits of the second approach are huge! Since the values are assigned to keys in objects, instead of a bunch of long and isolated variable names, we can use briefer variable names that are arguably easier to read at a glance, where the object name helps give context. Normally, `name` and `marker` would not be reusable in the same scope, but via "namespacing", we can still use them as part of `playerOne.name` or `playerTwo.marker` etc. Folks on the Ruby track may be familiar with doing something similar via Ruby's modules; in JavaScript, it's very normal to use objects for this purpose.
+
+But naming isn't the only benefit. Grouping related data together into objects allows you to pass all the data around more easily. For example:
```javascript
function gameOver(winningPlayer) {
From fc9c65ff1e0cda4e24968f87c7b7f213633bef1b Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Sun, 8 Feb 2026 18:28:07 +0000
Subject: [PATCH 14/21] Remove object organisation assignment
Tough decision.
The original assignment, especially without the public/private stuff,
felt a bit too contrived without as much practical learning value.
Possible readings generally covered much more scope than this lesson
(i.e. constructors/classes, inheritance encapsulation etc.)
Instead of trying to find an assignment for the sake of an assignment, I
felt it would be more sensible to omit an actual assignment since this
lesson is mostly basic conceptual "preparation" for the coming lessons
and projects.
---
.../organizing_code_with_objects.md | 32 ++-----------------
1 file changed, 3 insertions(+), 29 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
index 46b7edfd2ae..ff54f34c9bc 100644
--- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -246,35 +246,9 @@ Again, objects can be used to represent almost anything you can think of. The li
-1. Check out [DevSage's video explanation of the `this` keyword](https://www.youtube.com/watch?v=cwChC4BQF0Q) that gives a different perspective on how its context changes, as well as scenarios in which `this` behaves unexpectedly. Don't worry too much about the part on constructor functions at the end, as they will be covered in another lesson.
-
-1. Try modelling the behavior of a piggy bank as an object:
- 1. You should be able to interact with the object via a method that allows you to deposit coins.
- - For now, use a string to represent the name of a coin. Ex. `piggyBank.deposit('penny')`
- - You should keep the coin around by storing it in some kind of list.
- 1. The object should also have a property or method that tells you how much money you have saved as a number.
- - For simplicity, using only the smallest subunit of a given currency is acceptable.
- - Ex: If there are 5 US quarters in the piggy bank, then the number `125` for '125 cents' is acceptable.
- 1. You should be able to read the list of all coins that are currently in the piggy bank.
- 1. Add a method to the piggy bank object to remove a specific type of coin from the piggy bank if it's available.
- - Ensure you can still get the correct savings after removing coins!
- 1. Lastly, create a way to remove all the money from the jar and start fresh.
-
-1. Try to model something else as an object! Try to keep it simple, but have fun with it!
-
-#### Extra credit
-
-1. You may have exposed the list that the piggy bank uses to track coins as a public property. Depending on how you implemented the piggy bank, modifying this list without using something like a `deposit` or `withdraw` method on the object could throw some of it's properties out of wack, like the one that tells you the amount of savings you've accrued.
-
- Additionally, adding an unexpected value to this list by modifying it directly could cause errors within your piggy bank methods. Let's try to ensure that doesn't happen!
- - Indicate that the list of coins the piggy bank uses is a **private property** of the object.
- - Create a **public method** that gives the user a *copy* of the list that they can manipulate to their hearts content without breaking the piggy bank object.
-
-1. Try creating a couple 'coin' objects to deposit into the piggy bank instead of using a string.
- - A coin object might contain properties like the name of the coin, and it's value (preferably in the same unit the piggy bank measures it's savings).
- - Make sure that your piggy bank object is still able to keep track of savings and remove coins correctly after this change!
- - After making this change, consider how you are calculating savings for the piggy bank compared to before. Do you prefer working with the objects or the strings more?
- - Consider how the piggy bank might check for a correct string vs checking for an object with the correct properties when depositing. Which seems easier? Does one seem more flexible than the other?
+No assignment for this particular lesson! While JavaScript is a very flexible language that involves concepts from many different programming paradigms, a lot of it is built around "Object-oriented programming" (OOP).
+
+While this lesson has touched on the basic ideas behind why we might use objects in the first place, we will explore these concepts much more practically in the coming lessons via a multitude of techniques for creating and using objects.
From 5cd429656f7bf8452735b20ffa411cb4029f2fa4 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Sun, 8 Feb 2026 18:31:09 +0000
Subject: [PATCH 15/21] Tweak `this` knowledge check question
Pedantry
---
.../organizing_code_with_objects.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
index ff54f34c9bc..c97a78f1e3e 100644
--- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -258,4 +258,4 @@ The following questions are an opportunity to reflect on key topics in this less
- [What are two ways you can use objects to organize code?](#objects-as-a-data-structure)
- [What is a method?](#objects-as-a-design-pattern)
-- [What is the `this` keyword used for?](#this-keyword)
+- [In object methods, what is the `this` keyword used for?](#this-keyword)
From 69752a5a97e1795d4c58234334740f5fd4360dbc Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Sun, 8 Feb 2026 18:35:05 +0000
Subject: [PATCH 16/21] Add subsections to module pattern section
Clearer separation between "IIFE" and "module pattern" concepts
---
.../factory_functions_and_module_pattern.md | 28 +++++++++++--------
1 file changed, 16 insertions(+), 12 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md b/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
index 6b30f51280c..ea26000d87b 100644
--- a/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
+++ b/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
@@ -253,15 +253,9 @@ function createPlayer(name, level) {
}
```
-### The module pattern: IIFEs
+### The module pattern
-
-
-#### ES6 modules
-
-ECMAScript 6 (released in 2015) introduced a new JavaScript feature called "modules", which are a set of syntax for importing and exporting code between different JavaScript files. For now, we will be talking more generally about the module pattern using IIFEs, which you will still see out in the wild. In a later lesson, we will cover using ES6 modules for similar purposes.
-
-
+#### IIFEs
Oftentimes, you do not need a factory to produce multiple objects - instead, you are using it to wrap sections of code together, hiding the variables and functions that you do not need elsewhere as private. This is easily achievable by wrapping your factory function in parentheses and immediately calling (invoking) it. This immediate function call is commonly referred to as an Immediately Invoked Function Expression (duh) or IIFE in short. IIFEs are quite literally just function expressions that are called immediately:
@@ -270,6 +264,16 @@ Oftentimes, you do not need a factory to produce multiple objects - instead, you
(() => console.log('foo'))();
```
+#### Using IIFEs to implement the module pattern
+
+
+
+#### ES6 modules
+
+ECMAScript 6 (released in 2015) introduced a new JavaScript feature called "modules", which are a set of syntax for importing and exporting code between different JavaScript files. For now, we will be talking more generally about the module pattern using IIFEs, which you will still see out in the wild. In a later lesson, we will cover using ES6 modules for similar purposes.
+
+
+
A more helpful use of IIFEs is the pattern of wrapping "private" code inside an IIFE: the module pattern. This is often done with factory functions:
```javascript
@@ -282,9 +286,9 @@ const calculator = (function () {
return { add, sub, mul, div };
})();
-calculator.add(3,5); // 8
-calculator.sub(6,2); // 4
-calculator.mul(14,5534); // 77476
+calculator.add(3, 5); // 8
+calculator.sub(6, 2); // 4
+calculator.mul(14, 5534); // 77476
```
In this example, we have a factory function creating some basic operations that we need only once. We can wrap it in parentheses and immediately call it by adding `()` - returning the result object that we store in `calculator`. In this way we can write code, wrapping away things that we do not need as private variables and functions inside our factory function and while they are tucked inside of our module, we can use the returned variables and functions outside the factory, as necessary.
@@ -323,7 +327,7 @@ The following questions are an opportunity to reflect on key topics in this less
- [What are private variables in factory functions and how can they be useful?](#private-variables-and-functions)
- [How can we implement prototypal inheritance with factory functions?](#prototypal-inheritance-with-factories)
- [How does the module pattern work?](https://dev.to/tomekbuszewski/module-pattern-in-javascript-56jm)
-- [What does IIFE stand for and what are they?](#the-module-pattern-iifes)
+- [What does IIFE stand for and what are they?](#iifes)
- [What is the concept of namespacing and how do factory functions help with encapsulation?](#encapsulating-with-the-module-pattern)
### Additional resources
From ab116c4e590d845692d890b099fed2b6245f34ac Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Sun, 8 Feb 2026 18:37:08 +0000
Subject: [PATCH 17/21] Make simple IIFE example clearer
---
.../factory_functions_and_module_pattern.md | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md b/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
index ea26000d87b..b48271e333d 100644
--- a/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
+++ b/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
@@ -260,8 +260,11 @@ function createPlayer(name, level) {
Oftentimes, you do not need a factory to produce multiple objects - instead, you are using it to wrap sections of code together, hiding the variables and functions that you do not need elsewhere as private. This is easily achievable by wrapping your factory function in parentheses and immediately calling (invoking) it. This immediate function call is commonly referred to as an Immediately Invoked Function Expression (duh) or IIFE in short. IIFEs are quite literally just function expressions that are called immediately:
```javascript
-// This is an IIFE! Though not particularly useful, of course.
-(() => console.log('foo'))();
+// This is a function expression
+() => console.log("foo");
+
+// This is now an IIFE! Though not particularly useful, of course...
+(() => console.log("foo"))();
```
#### Using IIFEs to implement the module pattern
From f0b9bd9ae71ee130723c0a612783269bfeef5629 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Sun, 8 Feb 2026 21:33:43 +0000
Subject: [PATCH 18/21] Amend calculator encapsulation example
Actually demonstrate privatisation and need for function rather than
just using an object literal directly.
Namespacing mention removed as it'll now be brought up in an earlier
lesson
---
.../factory_functions_and_module_pattern.md | 51 ++++++++++++-------
1 file changed, 32 insertions(+), 19 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md b/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
index b48271e333d..8de88ac757a 100644
--- a/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
+++ b/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
@@ -263,7 +263,8 @@ Oftentimes, you do not need a factory to produce multiple objects - instead, you
// This is a function expression
() => console.log("foo");
-// This is now an IIFE! Though not particularly useful, of course...
+// The function expression is now an IIFE!
+// Although this one is not particularly useful of course
(() => console.log("foo"))();
```
@@ -280,29 +281,41 @@ ECMAScript 6 (released in 2015) introduced a new JavaScript feature called "modu
A more helpful use of IIFEs is the pattern of wrapping "private" code inside an IIFE: the module pattern. This is often done with factory functions:
```javascript
-const calculator = (function () {
- const add = (a, b) => a + b;
- const sub = (a, b) => a - b;
- const mul = (a, b) => a * b;
- const div = (a, b) => a / b;
-
- return { add, sub, mul, div };
+const calculator = (() => {
+ let lastResult;
+
+ const add = (a, b) => {
+ lastResult = a + b;
+ return lastResult;
+ };
+ const subtract = (a, b) => {
+ lastResult = a - b;
+ return lastResult;
+ };
+ const multiply = (a, b) => {
+ lastResult = a * b;
+ return lastResult;
+ };
+ const divide = (a, b) => {
+ lastResult = a / b;
+ return lastResult;
+ };
+ const getLastResult = () => lastResult;
+
+ return { add, subtract, multiply, divide, getLastResult };
})();
-calculator.add(3, 5); // 8
-calculator.sub(6, 2); // 4
-calculator.mul(14, 5534); // 77476
+console.log(calculator.add(3, 5)); // 8
+console.log(calculator.subtract(6, 2)); // 4
+console.log(calculator.getLastResult()); // 4
+console.log(calculator.multiply(14, 5534)); // 77476
```
-In this example, we have a factory function creating some basic operations that we need only once. We can wrap it in parentheses and immediately call it by adding `()` - returning the result object that we store in `calculator`. In this way we can write code, wrapping away things that we do not need as private variables and functions inside our factory function and while they are tucked inside of our module, we can use the returned variables and functions outside the factory, as necessary.
-
-#### Encapsulating with the module pattern
-
-At first glance, this does not seem particularly useful. If we have some code that we use only once, why not write it in the main section of our JavaScript file itself? After all, the power of factory functions lies in being, well, a factory to make multiple objects, right?
+Here, we have a calculator with four basic arithmetic methods and a method to read the most recent calculation's result. We only want the one calculator object but we still use a factory function! Why not just use an object literal directly?
-This is where we encounter the word **encapsulation** - bundling data, code, or something into a single unit, with selective access to the things inside that unit itself. While it sounds general, this is what happens when we wrap, or encapsulate our code into modules - we don't expose everything to the body of our program itself. This encapsulation leads to an effect called **namespacing**. Namespacing is a technique that is used to avoid naming collisions in our programs.
+All object properties are public whether we like it or not. If we just made a calculator object literal, we'd have a `.lastResult` property that's public, meaning it allows the possibility of reassigning it directly (e.g. `calculator.lastResult = 111100105110`). We want to keep `lastResult` private and expose the value publicly for reading only. Reassignment should only happen internally on our terms. The only way we can truly hide the `lastResult` variable from anything that doesn't actually need it would be to put it inside a function, away from the outside scope, then create the object within the same scope and return it. A factory function... that we only need to call once!
-Take the calculator example into consideration. It's very easy to imagine a scenario where you can accidentally create multiple functions with the name `add`. What does `add` do - does it add two numbers? Strings? Does it take its input directly from the DOM and display the result? What would you name the functions that do these things? Instead, we can easily encapsulate them inside a module called `calculator` which generates an object with that name, allowing us to explicitly call `calculator.add(a, b)` or `calculator.sub(a, b)`.
+This is where we encounter the word **encapsulation**: bundling data, code, or something into a single unit, with selective access to the things inside that unit itself. While it sounds general, this is what happens when we wrap (or encapsulate) our code into modules. We don't expose everything to the body of our program itself, only what is needed for other things to interact with whatever's inside the "module".
#### Why the IIFE?
@@ -331,7 +344,7 @@ The following questions are an opportunity to reflect on key topics in this less
- [How can we implement prototypal inheritance with factory functions?](#prototypal-inheritance-with-factories)
- [How does the module pattern work?](https://dev.to/tomekbuszewski/module-pattern-in-javascript-56jm)
- [What does IIFE stand for and what are they?](#iifes)
-- [What is the concept of namespacing and how do factory functions help with encapsulation?](#encapsulating-with-the-module-pattern)
+- [How do factory functions help with encapsulation?](#using-iifes-to-implement-the-module-pattern)
### Additional resources
From e8410d831375f2da5438e0f1aa1ed9f9def1b506 Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Sun, 8 Feb 2026 21:36:31 +0000
Subject: [PATCH 19/21] Make lesson overview a list of topics rather than
objectives
Matches lesson style guide
---
.../factory_functions_and_module_pattern.md | 14 ++++++--------
.../object_constructors.md | 2 +-
2 files changed, 7 insertions(+), 9 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md b/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
index 8de88ac757a..f49dde785d5 100644
--- a/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
+++ b/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
@@ -6,14 +6,12 @@ We have discussed object constructors in the previous lesson. However, they are
This section contains a general overview of topics that you will learn in this lesson.
-- Describe the scope of a variable.
-- Explore what closures are.
-- Briefly consider the disadvantages of using constructors.
-- Discuss Factory functions with examples.
-- Discuss Private variables and functions concerning factory functions.
-- Showcase object inheritance with the help of factory functions.
-- Describe what module pattern and IIFEs are.
-- Discuss encapsulation and how the module pattern helps with namespacing.
+- Variable scope.
+- Closures.
+- Factory functions.
+- Private variables.
+- IIFEs and the module pattern.
+- Encapsulation.
### Scoopfuls of scopes
diff --git a/javascript/organizing_your_javascript_code/object_constructors.md b/javascript/organizing_your_javascript_code/object_constructors.md
index 94fe54da217..4303f6640aa 100644
--- a/javascript/organizing_your_javascript_code/object_constructors.md
+++ b/javascript/organizing_your_javascript_code/object_constructors.md
@@ -6,7 +6,7 @@ Now that you've got a basic understanding of *why* and *how* you might use objec
This section contains a general overview of topics that you will learn in this lesson.
-- How to write an object constructor and instantiate the object.
+- Instantiating objects using constructors.
- What a prototype is and how it can be used.
- Prototypal inheritance.
- Basic do's and don'ts of prototypal inheritance.
From f8b8c6d0e75d9335ad9bb32d3ac7d2165549e13e Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Sun, 8 Feb 2026 22:28:23 +0000
Subject: [PATCH 20/21] Soften wording around constructor "unpopularity"
May have been true in earlier times, but especially with classes coming
up later, I'd hesitate to use this language right now. I'd rather the
context just be presenting an alternative approach than thinking this
fully replaces something else because "bad"
---
.../factory_functions_and_module_pattern.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md b/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
index f49dde785d5..56759052087 100644
--- a/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
+++ b/javascript/organizing_your_javascript_code/factory_functions_and_module_pattern.md
@@ -100,11 +100,11 @@ One of the key arguments is how they *look* like regular JavaScript functions, e
Yet another issue stems from misusing `instanceof`. In other programming languages, the keyword is a reliable way to know the code with which an object was made; but in JavaScript, it checks the presence of a constructor's prototype in an object's *entire* prototype chain - which does nothing to confirm if an object was made with that constructor since the constructor's prototype can even be reassigned after the creation of an object.
-Because of that, constructors have become unpopular in favor of a pattern that is similar but addresses a ton of these problems by not relying on those troublesome features: Factory Functions.
+Because of that, some people (not all) disliked using constructors in favor of a pattern that is similar but addresses a ton of these problems by not relying on those troublesome features: Factory Functions.
### Factory functions 🏭
-These fancy-sounding functions work very similar to how constructors did, but with one key difference - they levy the power of closures. Instead of using the `new` keyword to create an object, factory functions set up and return the new object when you call the function. They do not use the prototype, which incurs a performance penalty - but as a general rule, this penalty isn’t significant unless you’re creating thousands of objects. Let's take a basic example to compare them to constructor functions.
+These fancy-sounding functions work very similar to how constructors did, but with one key difference - they levy the power of closures. Instead of using the `new` keyword to create an object, factory functions set up and return the new object when you call the function. They do not use the prototype, which does incur a performance penalty, but as a general rule, this penalty isn’t significant unless you’re creating thousands of objects. Let's take a basic example to compare them to constructor functions.
```javascript
function User(name) {
From 9399e43e155d9c400cde7393fdef9ebaa7cf6e8e Mon Sep 17 00:00:00 2001
From: mao-sz <122839503+mao-sz@users.noreply.github.com>
Date: Sun, 8 Feb 2026 22:32:58 +0000
Subject: [PATCH 21/21] Fix typo
---
.../organizing_code_with_objects.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
index c97a78f1e3e..69cc6779bfd 100644
--- a/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
+++ b/javascript/organizing_your_javascript_code/organizing_code_with_objects.md
@@ -121,7 +121,7 @@ const car = {
// a method is just a function assigned to a property
applyDiscount: function(discountPercentage) {
const multiplier = 1 - discountPercentage / 100;
- this.priceUSD *= multipler;
+ this.priceUSD *= multiplier;
},
// shorthand way to add a method to an object literal
getSummary() {