Skip to content
Advertisement

JavaScript Accessing literal object property

I’m trying to make this function that tells me which guitar I can purchased based on the budged. My issue is that I created a literal object and all outputs are giving the same answer (Except condition one) because I am trying to access the properties inside.

What would be the best way to access the property that has the name of the item? Also, please correct any wrong terminology I use.

JavaScript

Advertisement

Answer

There are two main issues with your program:

prompt() returns a string

prompt() returns a string but you want to do comparisons on numbers so you need to convert the string to a number first using Number.parseFloat(). Otherwise you will just be checking on a lexicographic basis which could potentially give you unexpected results.

Order of else ifs

You need to arrange your else if statements in a way that every else if could actually be reached otherwise there is no point defining those other cases as only ever one can be triggered. So arrange them from most money to least money when using <=.

Just a remark: Try to use const instead of let whenever you are not changing the value which is (or should be) almost always.

JavaScript

For reason of simplicity I have wrapped the program in an infinite loop when an invalid input is entered that cannot be converted to a number. To exit the program despite the infinite loop I have added an exit command. The program will also exit when Cancel is pressed (i.e. prompt() returns null). The actual logic to tell the user which guitar to buy was factored out into another method tellGuitar() which receives the money as a number.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement