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 :
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}`);