Super Newbie Javascript function Question

Hey guys!
So i’ve been learning Javascript and i’m really a newbie so… I had this challenge to calculate bars of snickers per day for the rest of my life.

anyways, i then decided i want to try to make it ask me if i want to sell halve of the bars for a certain amount of $ per bar and return an answer of how many bars and cash i’ll have.

Anyways i don’t have any knowledge and thought i might be able to do it with just vars and a function but… im stuck.

function calculateSupply(age, perDay) {
  var maxAge = 100;
  var supply = (perDay * 365) * (maxAge - age);
  var message = 'You will need ' + supply + ' Snickers to survive untill the age of '
   + maxAge;

calculateSupply(34, 2);

var willYouSell = prompt('Will you sell half? True or False');
var barsSupply = calculateSupply;
if (willYouSell === true) {
  var barsLeft = calculateSupply / 2;
  var pricePerBar = prompt('Whats the price per bar? ')
  var cash = barsleft * pricePerBar;
  console.log('if you sell halve, you\'ll have' + barsLeft + ' And ' + cash + ' Cash if sold for ' + pricePerBar);
} else {
  console.log('You choose not to sell and have ' + barsSupply + ' Bars left');

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

I think what you want to do is store the result of calculateSupply(34, 2) in the barsSupply variable, like

var barsSupply = calculateSupply(34, 2);

1 Like

Got it! Sorry about that

@elfraim This is more a matter of style, but you might want to also ask whether message belongs inside the calculateSupply function. Tailoring functions to a very narrow purpose, or separating concerns, can help with readability and maintainability. For example,

 *  Calculate the number of bars required for a life expectancy of 100 from the individuals current age
 *  Returns: Number of bars
function calculateSupply(age, perDay) {
    var maxAge = 100;
    var supply = (perDay * 365) * (maxAge - age);
    return supply;

// Calculate the number of Snickers bars for a lifetime of an individual who is 34 years old
var totalSupply = calculateSupply(34, 2);'You will need ' + totalSupply + ' Snickers to survive untill the age of '  + maxAge);

This is a trivial point for this app, but you might find it to be a helpful practice as you scale up to more difficult exercises. Your code is very easy to read and I especially like the fact that you used descriptive variable names. Looks to me like you are off to a good start!


Thanks for the input and feedback!!
Have a great weekend :slight_smile: