Active learning: Printing those products

Hello.

I’m requesting a view of my solution for the Printing those products exercise utilizing all learnings from the JavaScript First Steps section.

Thank you for your help.


CodePen Link:
https://codepen.io/jt_1/pen/OJrRJYR

Hi @jt_1

Well done. This works as expected. :+1:

You can make your code a bit simpler by using the split() method to create the new array:

const newArray = product.split(":");

and then assign the array elements to the name and price:

const productName = newArray[0];
const productPrice = newArray[1];

If you move this two line above total += ..., you can also reuse productPrice there.

I hope this helps. :slightly_smiling_face:

Have a nice day,
Michael

1 Like

Thanks @mikoMK for this feedback! I actually just noticed the solution button in the exercise. :grin: haha.

I see now that .split() would have been the cleaner approach!

And I learned something new with assigning the array elements like that - good to know for future reference.

Appreciate your help as always!

1 Like

Nice finding! Hint: For the “Test your Skills!” exercises there isn’t a solution button, but it’s also possible to get the solutions, if you search the right spots. :eyes:

There’s also a more advanced feature when assigning array (or object) values to variables. It’s called: Destructuring.
With this technique we can assign multiple values at once. Since we need to convert price to a number, we still need an additional line:

let [name, price] = product.split(':');
price = Number(price)
1 Like

@mikoMK Nice! Thanks for the restructuring tip. Even better! :sunglasses:
Added to my notes!

1 Like

destructuring* I meant!

1 Like

That’s what I guessed :sunglasses:

1 Like