feat(curriculum): Add interactive examples to What Is the Difference Between Functions and Object Methods (#63310)

Co-authored-by: Ilenia <26656284+ilenia-magoni@users.noreply.github.com>
This commit is contained in:
Clarence Bakosi
2025-10-30 12:16:00 +01:00
committed by GitHub
parent c7c11fa09a
commit 3efacddb00

View File

@@ -5,12 +5,14 @@ challengeType: 19
dashedName: what-is-the-difference-between-functions-and-object-methods
---
# --description--
# --interactive--
In JavaScript, functions and object methods are both ways to encapsulate reusable code, but they have some key differences in how they are defined, used, and the context in which they operate. Understanding these differences is crucial for writing effective and organized JavaScript code.
As you learned in earlier modules, functions are reusable blocks of code that perform a specific task:
:::interactive_editor
```js
function greet(name) {
return "Hello, " + name + "!";
@@ -18,8 +20,12 @@ function greet(name) {
console.log(greet("Alice")); // "Hello, Alice!"
```
:::
Object methods, on the other hand, are functions that are associated with an object. They are defined as properties of an object and can access and manipulate the object's data. Here's an example of an object with a method:
:::interactive_editor
```js
const person = {
name: "Bob",
@@ -32,6 +38,8 @@ const person = {
console.log(person.sayHello()); // "Hello, my name is Bob"
```
:::
In this example, `sayHello` is a method of the `person` object. The `this` keyword allows the `sayHello` method to access the properties of the object named `person`. You will learn more about the `this` keyword in future lessons.
A difference between functions and methods is how they are invoked. Functions are called by their name, while methods are called using dot notation on the object they belong to. For example, we call the `greet` function as `greet("Alice")`, but we call the `sayHello` method as `person.sayHello()`.