0
0
Javascriptprogramming~15 mins

Module scope in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Module Scope in JavaScript
📖 Scenario: You are building a small JavaScript module to manage a user's profile data. You want to keep some data private inside the module and expose only what is necessary.
🎯 Goal: Create a JavaScript module that stores a user's name privately and exposes a function to get the user's name.
📋 What You'll Learn
Create a module using an immediately invoked function expression (IIFE).
Inside the module, create a private variable called userName with the value 'Alice'.
Add a function called getUserName inside the module that returns the value of userName.
Expose only the getUserName function to the outside of the module.
Print the result of calling getUserName() to the console.
💡 Why This Matters
🌍 Real World
Modules help keep code organized and protect data from being changed accidentally by other parts of a program.
💼 Career
Understanding module scope is important for writing clean, maintainable JavaScript code in real projects and working with libraries.
Progress0 / 4 steps
1
Create the module and private variable
Create a module using an immediately invoked function expression (IIFE). Inside it, create a private variable called userName and set it to 'Alice'.
Javascript
Need a hint?

Use (function() { ... })(); to create a module. Declare const userName = 'Alice' inside it.

2
Add a function to get the user name
Inside the module, add a function called getUserName that returns the value of userName.
Javascript
Need a hint?

Define function getUserName() { return userName; } inside the module.

3
Expose the getUserName function
Modify the module to expose only the getUserName function to the outside by returning an object with getUserName as a property.
Javascript
Need a hint?

Return an object with getUserName inside the IIFE and assign it to userModule.

4
Print the user name using the module
Use console.log to print the result of calling userModule.getUserName().
Javascript
Need a hint?

Call console.log(userModule.getUserName()) to show the user name.