YDKJS Chapter 1 Challenge

Get your copy here:

1.) Write a program to calculate the total price of your phone purchase. You will keep purchasing phones (hint: loop!) until you run out of money in your bank account. You’ll also buy accessories for each phone as long as your purchase amount is below your mental spending threshold.

2.) After you’ve calculated your purchase amount, add in the tax, then print out the calculated purchase amount, properly formatted.

3.) Finally, check the amount against your bank account balance to see if you can afford it or not.

4.) You should set up some constants for the “tax rate,” “phone price,” “accessory price,” and “spending threshold,” as well as a variable for your “bank account balance.”

5.) You should define functions for calculating the tax and for formatting the price with a “$” and rounding to two decimal places.



const TAX_RATE = 0.8;

const PHONE_PRICE = 99.99;

const ACCESSORY_PRICE = 9.99;


var bank_balance = 303.91;

var amount = 0;


function calculateTax(amount) {

return amount * TAX_RATE;



function formatAmount(amount) {

return "$" + amount.toFixed(2);



// keep purchasing phones

while (amount < bank balance) {

// buy new phone!

amount = amount + PHONE_PRICE;

// can we afford accessory?

if (amount < SPENDING_TRESHOLD) {      amount = amount + ACCESSORY_PRICE;    }  }    // pay taxes  amount = amount + calculateTax(amount);  console.log("Your purchase: " + formatAmount(amount));  // Total purchase: $334.76  // can you afford  if (amount > bank_balance) {

console.log("You can't afford this. :(");


Essential programming building blocks:

1.) You need operators to perform actions on.

2.) You need values and types to perform different kinds of actions like math on numbers or output with strings.

3.) You need variables to store data (aka state) during your program’s execution.

4.) You need conditionals like if statements to make decisions.

5.) You need loops to repeat tasks until a condition stops being true.

6.) You need functions to organize your code into logical and reusable chunks.

Simpson, Kyle. You Don’t Know JS: Up & Going O’Reilly Media. Kindle Edition.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.