0
0
Javascriptprogramming~20 mins

this in functions in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding <code>this</code> in JavaScript Functions
📖 Scenario: Imagine you are building a simple app that keeps track of a user's name and can greet them. You want to understand how the keyword this works inside functions to access the user's name.
🎯 Goal: You will create an object representing a user with a name property and a function that uses this to greet the user by name.
📋 What You'll Learn
Create an object called user with a property name set to 'Alice'
Add a method called greet inside user that returns a greeting string using this.name
Call the greet method and print the result
💡 Why This Matters
🌍 Real World
Understanding <code>this</code> is important when working with objects and methods in JavaScript, which is common in web apps and interactive websites.
💼 Career
Many programming jobs require working with JavaScript objects and functions where <code>this</code> is used to access data inside objects, so mastering this concept helps you write better code.
Progress0 / 4 steps
1
Create the user object with a name property
Create an object called user with a property name set to the string 'Alice'.
Javascript
Need a hint?

Use const user = { name: 'Alice' }; to create the object.

2
Add a greet method using this.name
Add a method called greet inside the user object that returns the string `Hello, ${this.name}!` using this.name.
Javascript
Need a hint?

Define greet() as a function inside user that returns the greeting string using this.name.

3
Call the greet method and store the result
Call the greet method on the user object and store the result in a variable called message.
Javascript
Need a hint?

Use const message = user.greet(); to call the method and save the greeting.

4
Print the greeting message
Print the value of the variable message to the console.
Javascript
Need a hint?

Use console.log(message); to show the greeting in the console.