Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use three prompt boxes to ask the user for three different words and then place them in an array. Use an alert box to display the array

So, I’m new to JS and currently taking courses. My instructor listed one solution, and the solution I came up with in my opinion is more ideal…I used push() method which I’d think is better. And I used Template literal inside my alert method to prevent the need to concat the string and variable…. Please let me know what the better code would be! Much appreciated!

//Instructor's solution:
const item1 = prompt('Item 1?');
const item2 = prompt('Item2?');
const item3 = prompt('Item3?');
const myArray = [item1, item2, item3];
alert("My shopping list is:"  + myArray);
//My solution:
let shoppingList = [];
shoppingList.push(prompt('Item 1?'));
shoppingList.push(prompt('Item 2?'));
shoppingList.push(prompt('Item 3?'));
alert(`My shopping list is: ${shoppingList}`);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This part is better in the instructor’s version

The instructor is storing the inputs separately, which is conventional. That gives them variable names, which is helpful for future programmers (since, in general, the prompt text may not be the perfect programmer-facing summary).

The array is created as a const, which is good practice when you know you are not going to reassign the whole array.

const item1 = prompt('Item 1?');
const item2 = prompt('Item 2?');
const item3 = prompt('Item 3?');
const myArray = [item1, item2, item3];

This part, I prefer in your version

You are using an easier-to-read layout with the template string.

And of course you have a better variable name!

alert(`My shopping list is: ${shoppingList}`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading