This JavaScript script simulates a Magic 8-Ball. It provides a greeting, handles a user's question (or a default text), and then offers a random 8-Ball answer.
- Personalized Greeting: Greets the user, using "stranger" as a default name if one is not provided.
- Question Input: Displays the user's question. If no question is entered, it shows an introductory message.
- Magic 8-Ball Response: Randomly generates one of several classic 8-Ball answers.
- Two Implementations: Demonstrates two ways to generate the 8-Ball answer:
- Using a
switch
statement. - Using an array of responses (refactored and preferred version).
- Using a
-
Setup (Optional):
- You can modify the
userName
anduserQuestion
variables at the beginning of the script if you wish to customize the greeting or the question.
let userName = ''; // Change to your name let userQuestion = ''; // Write your question
- You can modify the
-
Execution:
- Run the script in any JavaScript environment (e.g., Node.js or your web browser's developer console).
# If using Node.js: node your_script_name.js
-
Output:
- The script will print to the console:
- A greeting.
- Your question (or the default message).
- A random Magic 8-Ball answer.
- The script will print to the console:
The script includes two methods for determining the Magic 8-Ball's response:
switch
Method: An initial implementation using aswitch
statement based on a random number.- Array Method (Refactored): An improved version that stores possible answers in an array and selects one randomly. This approach is generally cleaner, easier to maintain, and more adaptable if the number of answers changes.
// Example of the refactored array version:
const eightBallAnswers = [
'Outlook not good',
'Signs point to yes',
// ... more answers
];
let randomNumberForArray = Math.floor(Math.random() * eightBallAnswers.length);
let eightBallResponseFromArray = eightBallAnswers[randomNumberForArray];
console.log(eightBallResponseFromArray);