Is there a way to force JavaScript to return a negative value in an alert box? [duplicate]












8















This question already has an answer here:




  • Adding two numbers concatenates them instead of calculating the sum

    20 answers




JavaScript is returning X - Y , where X and Y are Real numbers and their sum is negative, instead of just the negative sum.



I've tried an if else statement using



if (Math.sign(function)<0)
else


where the if statement just had a "-" in front of the value to concatenate the string "minus" character in front of the number and the else statement was just a regular print out



function velocity_final(initial_velocity, acceleration, time)
{
var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
var time = prompt('Please enter the time in seconds');
var final_velocity = initial_velocity + acceleration * time;
alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
}









share|improve this question









New contributor




Evan Howington is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











marked as duplicate by Salman A javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 20 at 8:20


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • for the prompts I put in 32, -9.81, 10 and it returns 32-98.100000 instead of just a negative number
    – Evan Howington
    Dec 20 at 3:51








  • 1




    Please do take the time to format your sample code and you do not have to follow up content on a comment, edit the post instead. You get unlimited edits on your post so feel free to use as much as you want.
    – Abana Clara
    Dec 20 at 3:53










  • it would be hilarious if JavaScript actually parsed any potential negative numbers in alerts and removed them
    – sudo rm -rf slash
    Dec 20 at 8:00
















8















This question already has an answer here:




  • Adding two numbers concatenates them instead of calculating the sum

    20 answers




JavaScript is returning X - Y , where X and Y are Real numbers and their sum is negative, instead of just the negative sum.



I've tried an if else statement using



if (Math.sign(function)<0)
else


where the if statement just had a "-" in front of the value to concatenate the string "minus" character in front of the number and the else statement was just a regular print out



function velocity_final(initial_velocity, acceleration, time)
{
var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
var time = prompt('Please enter the time in seconds');
var final_velocity = initial_velocity + acceleration * time;
alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
}









share|improve this question









New contributor




Evan Howington is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











marked as duplicate by Salman A javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 20 at 8:20


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • for the prompts I put in 32, -9.81, 10 and it returns 32-98.100000 instead of just a negative number
    – Evan Howington
    Dec 20 at 3:51








  • 1




    Please do take the time to format your sample code and you do not have to follow up content on a comment, edit the post instead. You get unlimited edits on your post so feel free to use as much as you want.
    – Abana Clara
    Dec 20 at 3:53










  • it would be hilarious if JavaScript actually parsed any potential negative numbers in alerts and removed them
    – sudo rm -rf slash
    Dec 20 at 8:00














8












8








8


2






This question already has an answer here:




  • Adding two numbers concatenates them instead of calculating the sum

    20 answers




JavaScript is returning X - Y , where X and Y are Real numbers and their sum is negative, instead of just the negative sum.



I've tried an if else statement using



if (Math.sign(function)<0)
else


where the if statement just had a "-" in front of the value to concatenate the string "minus" character in front of the number and the else statement was just a regular print out



function velocity_final(initial_velocity, acceleration, time)
{
var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
var time = prompt('Please enter the time in seconds');
var final_velocity = initial_velocity + acceleration * time;
alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
}









share|improve this question









New contributor




Evan Howington is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












This question already has an answer here:




  • Adding two numbers concatenates them instead of calculating the sum

    20 answers




JavaScript is returning X - Y , where X and Y are Real numbers and their sum is negative, instead of just the negative sum.



I've tried an if else statement using



if (Math.sign(function)<0)
else


where the if statement just had a "-" in front of the value to concatenate the string "minus" character in front of the number and the else statement was just a regular print out



function velocity_final(initial_velocity, acceleration, time)
{
var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
var time = prompt('Please enter the time in seconds');
var final_velocity = initial_velocity + acceleration * time;
alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
}




This question already has an answer here:




  • Adding two numbers concatenates them instead of calculating the sum

    20 answers








javascript






share|improve this question









New contributor




Evan Howington is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Evan Howington is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Dec 20 at 4:25









Alexander O'Mara

43.1k1396128




43.1k1396128






New contributor




Evan Howington is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Dec 20 at 3:50









Evan Howington

506




506




New contributor




Evan Howington is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Evan Howington is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Evan Howington is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




marked as duplicate by Salman A javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 20 at 8:20


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by Salman A javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 20 at 8:20


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • for the prompts I put in 32, -9.81, 10 and it returns 32-98.100000 instead of just a negative number
    – Evan Howington
    Dec 20 at 3:51








  • 1




    Please do take the time to format your sample code and you do not have to follow up content on a comment, edit the post instead. You get unlimited edits on your post so feel free to use as much as you want.
    – Abana Clara
    Dec 20 at 3:53










  • it would be hilarious if JavaScript actually parsed any potential negative numbers in alerts and removed them
    – sudo rm -rf slash
    Dec 20 at 8:00


















  • for the prompts I put in 32, -9.81, 10 and it returns 32-98.100000 instead of just a negative number
    – Evan Howington
    Dec 20 at 3:51








  • 1




    Please do take the time to format your sample code and you do not have to follow up content on a comment, edit the post instead. You get unlimited edits on your post so feel free to use as much as you want.
    – Abana Clara
    Dec 20 at 3:53










  • it would be hilarious if JavaScript actually parsed any potential negative numbers in alerts and removed them
    – sudo rm -rf slash
    Dec 20 at 8:00
















for the prompts I put in 32, -9.81, 10 and it returns 32-98.100000 instead of just a negative number
– Evan Howington
Dec 20 at 3:51






for the prompts I put in 32, -9.81, 10 and it returns 32-98.100000 instead of just a negative number
– Evan Howington
Dec 20 at 3:51






1




1




Please do take the time to format your sample code and you do not have to follow up content on a comment, edit the post instead. You get unlimited edits on your post so feel free to use as much as you want.
– Abana Clara
Dec 20 at 3:53




Please do take the time to format your sample code and you do not have to follow up content on a comment, edit the post instead. You get unlimited edits on your post so feel free to use as much as you want.
– Abana Clara
Dec 20 at 3:53












it would be hilarious if JavaScript actually parsed any potential negative numbers in alerts and removed them
– sudo rm -rf slash
Dec 20 at 8:00




it would be hilarious if JavaScript actually parsed any potential negative numbers in alerts and removed them
– sudo rm -rf slash
Dec 20 at 8:00












3 Answers
3






active

oldest

votes


















1














Prompt returns a string. Such that doing "1" +"-1" will result to "1-1" due to concatenation. Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers, if the evaluated strings contains a character, it gets concatenated instead. You need to explicitly cast the numbers.



You can use Number(), you can multiply each string to 1 to automatically convert them, you can use parseInt(), or you can use + preceding the returned values as shown by the other answers here. I would use the first one I mentioned in the example below.






function velocity_final()
{
var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
var time = prompt('Please enter the time in seconds');
var final_velocity = Number(initial_velocity) + Number(acceleration) * Number(time);
alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
}

velocity_final();








share|improve this answer























  • All good answers. Thank you for showing the Number part in the code. I had changed it to initial_velocity - ((-1)*acceleration*time) and that worked.. I changed to that because one of my other equations is almost identical except it utilizes subtraction and there were no issues. Previously I was just performing multiplication and division so this did not arise. I am converting my code from Python to JS, so I am learning on the fly. Thank you very much!
    – Evan Howington
    Dec 20 at 4:27












  • Every time I've tested it (which, admittedly, was a few versions ago), implicit casting has always been faster than explicit casting, for some reason. Of course, performance may not matter in this case, and you can call this more readable. But I tend to use a - -b to add strings as numbers.
    – trlkly
    Dec 20 at 6:11








  • 1




    "1" + "1" doesn't give 2, it gives "11". String concatenation always happens if one of the operands is a string (see step 7 in the addition operator evaluation)
    – Birjolaxew
    Dec 20 at 8:05










  • @Birjolaxew is absolutely correct, the sentence "Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers" does not reflect reality and is actually contradicting what you said before: "1" + "-1" does not get parsed, even though according to the quote it should. There is no logical reason for "1" + "-1" and "1" + "1" to produce two different types of results. It should be either treated as numeric in both cases or strings in both cases.
    – vlaz
    Dec 20 at 8:19










  • The statement following the quote "if the evaluated strings contains a character, it gets concatenated instead." is correct but I think you are misunderstanding the actual meaning. The result would be concatenation if any of the actual variables is a string - typeof someVar //"string" and not if the content of the variable can be parsed as numeric - someVar = "1". Also, another misconception here is that you consider - to be a "character" when "-1" is a string that can perfectly validly be parsed into a numeric and JS would tell you as much through Number().
    – vlaz
    Dec 20 at 8:24





















7














prompt always returns a string, not a number. Even if the person enters a number, it will be a string that represents that number, not a number itself.



You will need to cast the results of prompt to a number before you can preform addition on it. When used with string, + is the concatenation operator, rather then the addition operator.



Somewhat confusingly, you can actually use an unary + for this purpose.



var initial_velocity = +prompt('Please enter the Initial Velocity in Meters per Second');
var acceleration = +prompt('Please enter the acceleration in Meters per Second Squared');
var time = +prompt('Please enter the time in seconds');
var final_velocity = initial_velocity + acceleration * time;
alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');





share|improve this answer































    2














    The + operator can be both addition and string concatenation. When the prompt box returns, it gives you back a string. String + number = string, so it concatenates (joins) the two values together instead of adding them. To fix this, you can convert the string to a number using a single + operator (and some parentheses if you want) to convert the string to a number, like so:






    function velocity_final()
    {
    var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
    var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
    var time = prompt('Please enter the time in seconds');
    var final_velocity = (+initial_velocity) + (+acceleration) * (+time);
    alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
    }

    console.log(velocity_final());





    You could also convert the values as soon as the prompt returns a value, if you wanted.



    PS: I removed the function parameters, as you set them manually anyways rather than passing anything in. If you do end up passing in values later rather than asking the user for them, you'll need to add those back into the function statement for them to be properly passed in.






    share|improve this answer




























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Prompt returns a string. Such that doing "1" +"-1" will result to "1-1" due to concatenation. Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers, if the evaluated strings contains a character, it gets concatenated instead. You need to explicitly cast the numbers.



      You can use Number(), you can multiply each string to 1 to automatically convert them, you can use parseInt(), or you can use + preceding the returned values as shown by the other answers here. I would use the first one I mentioned in the example below.






      function velocity_final()
      {
      var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
      var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
      var time = prompt('Please enter the time in seconds');
      var final_velocity = Number(initial_velocity) + Number(acceleration) * Number(time);
      alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
      }

      velocity_final();








      share|improve this answer























      • All good answers. Thank you for showing the Number part in the code. I had changed it to initial_velocity - ((-1)*acceleration*time) and that worked.. I changed to that because one of my other equations is almost identical except it utilizes subtraction and there were no issues. Previously I was just performing multiplication and division so this did not arise. I am converting my code from Python to JS, so I am learning on the fly. Thank you very much!
        – Evan Howington
        Dec 20 at 4:27












      • Every time I've tested it (which, admittedly, was a few versions ago), implicit casting has always been faster than explicit casting, for some reason. Of course, performance may not matter in this case, and you can call this more readable. But I tend to use a - -b to add strings as numbers.
        – trlkly
        Dec 20 at 6:11








      • 1




        "1" + "1" doesn't give 2, it gives "11". String concatenation always happens if one of the operands is a string (see step 7 in the addition operator evaluation)
        – Birjolaxew
        Dec 20 at 8:05










      • @Birjolaxew is absolutely correct, the sentence "Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers" does not reflect reality and is actually contradicting what you said before: "1" + "-1" does not get parsed, even though according to the quote it should. There is no logical reason for "1" + "-1" and "1" + "1" to produce two different types of results. It should be either treated as numeric in both cases or strings in both cases.
        – vlaz
        Dec 20 at 8:19










      • The statement following the quote "if the evaluated strings contains a character, it gets concatenated instead." is correct but I think you are misunderstanding the actual meaning. The result would be concatenation if any of the actual variables is a string - typeof someVar //"string" and not if the content of the variable can be parsed as numeric - someVar = "1". Also, another misconception here is that you consider - to be a "character" when "-1" is a string that can perfectly validly be parsed into a numeric and JS would tell you as much through Number().
        – vlaz
        Dec 20 at 8:24


















      1














      Prompt returns a string. Such that doing "1" +"-1" will result to "1-1" due to concatenation. Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers, if the evaluated strings contains a character, it gets concatenated instead. You need to explicitly cast the numbers.



      You can use Number(), you can multiply each string to 1 to automatically convert them, you can use parseInt(), or you can use + preceding the returned values as shown by the other answers here. I would use the first one I mentioned in the example below.






      function velocity_final()
      {
      var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
      var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
      var time = prompt('Please enter the time in seconds');
      var final_velocity = Number(initial_velocity) + Number(acceleration) * Number(time);
      alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
      }

      velocity_final();








      share|improve this answer























      • All good answers. Thank you for showing the Number part in the code. I had changed it to initial_velocity - ((-1)*acceleration*time) and that worked.. I changed to that because one of my other equations is almost identical except it utilizes subtraction and there were no issues. Previously I was just performing multiplication and division so this did not arise. I am converting my code from Python to JS, so I am learning on the fly. Thank you very much!
        – Evan Howington
        Dec 20 at 4:27












      • Every time I've tested it (which, admittedly, was a few versions ago), implicit casting has always been faster than explicit casting, for some reason. Of course, performance may not matter in this case, and you can call this more readable. But I tend to use a - -b to add strings as numbers.
        – trlkly
        Dec 20 at 6:11








      • 1




        "1" + "1" doesn't give 2, it gives "11". String concatenation always happens if one of the operands is a string (see step 7 in the addition operator evaluation)
        – Birjolaxew
        Dec 20 at 8:05










      • @Birjolaxew is absolutely correct, the sentence "Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers" does not reflect reality and is actually contradicting what you said before: "1" + "-1" does not get parsed, even though according to the quote it should. There is no logical reason for "1" + "-1" and "1" + "1" to produce two different types of results. It should be either treated as numeric in both cases or strings in both cases.
        – vlaz
        Dec 20 at 8:19










      • The statement following the quote "if the evaluated strings contains a character, it gets concatenated instead." is correct but I think you are misunderstanding the actual meaning. The result would be concatenation if any of the actual variables is a string - typeof someVar //"string" and not if the content of the variable can be parsed as numeric - someVar = "1". Also, another misconception here is that you consider - to be a "character" when "-1" is a string that can perfectly validly be parsed into a numeric and JS would tell you as much through Number().
        – vlaz
        Dec 20 at 8:24
















      1












      1








      1






      Prompt returns a string. Such that doing "1" +"-1" will result to "1-1" due to concatenation. Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers, if the evaluated strings contains a character, it gets concatenated instead. You need to explicitly cast the numbers.



      You can use Number(), you can multiply each string to 1 to automatically convert them, you can use parseInt(), or you can use + preceding the returned values as shown by the other answers here. I would use the first one I mentioned in the example below.






      function velocity_final()
      {
      var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
      var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
      var time = prompt('Please enter the time in seconds');
      var final_velocity = Number(initial_velocity) + Number(acceleration) * Number(time);
      alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
      }

      velocity_final();








      share|improve this answer














      Prompt returns a string. Such that doing "1" +"-1" will result to "1-1" due to concatenation. Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers, if the evaluated strings contains a character, it gets concatenated instead. You need to explicitly cast the numbers.



      You can use Number(), you can multiply each string to 1 to automatically convert them, you can use parseInt(), or you can use + preceding the returned values as shown by the other answers here. I would use the first one I mentioned in the example below.






      function velocity_final()
      {
      var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
      var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
      var time = prompt('Please enter the time in seconds');
      var final_velocity = Number(initial_velocity) + Number(acceleration) * Number(time);
      alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
      }

      velocity_final();








      function velocity_final()
      {
      var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
      var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
      var time = prompt('Please enter the time in seconds');
      var final_velocity = Number(initial_velocity) + Number(acceleration) * Number(time);
      alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
      }

      velocity_final();





      function velocity_final()
      {
      var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
      var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
      var time = prompt('Please enter the time in seconds');
      var final_velocity = Number(initial_velocity) + Number(acceleration) * Number(time);
      alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
      }

      velocity_final();






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Dec 20 at 4:29

























      answered Dec 20 at 4:00









      Abana Clara

      1,511819




      1,511819












      • All good answers. Thank you for showing the Number part in the code. I had changed it to initial_velocity - ((-1)*acceleration*time) and that worked.. I changed to that because one of my other equations is almost identical except it utilizes subtraction and there were no issues. Previously I was just performing multiplication and division so this did not arise. I am converting my code from Python to JS, so I am learning on the fly. Thank you very much!
        – Evan Howington
        Dec 20 at 4:27












      • Every time I've tested it (which, admittedly, was a few versions ago), implicit casting has always been faster than explicit casting, for some reason. Of course, performance may not matter in this case, and you can call this more readable. But I tend to use a - -b to add strings as numbers.
        – trlkly
        Dec 20 at 6:11








      • 1




        "1" + "1" doesn't give 2, it gives "11". String concatenation always happens if one of the operands is a string (see step 7 in the addition operator evaluation)
        – Birjolaxew
        Dec 20 at 8:05










      • @Birjolaxew is absolutely correct, the sentence "Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers" does not reflect reality and is actually contradicting what you said before: "1" + "-1" does not get parsed, even though according to the quote it should. There is no logical reason for "1" + "-1" and "1" + "1" to produce two different types of results. It should be either treated as numeric in both cases or strings in both cases.
        – vlaz
        Dec 20 at 8:19










      • The statement following the quote "if the evaluated strings contains a character, it gets concatenated instead." is correct but I think you are misunderstanding the actual meaning. The result would be concatenation if any of the actual variables is a string - typeof someVar //"string" and not if the content of the variable can be parsed as numeric - someVar = "1". Also, another misconception here is that you consider - to be a "character" when "-1" is a string that can perfectly validly be parsed into a numeric and JS would tell you as much through Number().
        – vlaz
        Dec 20 at 8:24




















      • All good answers. Thank you for showing the Number part in the code. I had changed it to initial_velocity - ((-1)*acceleration*time) and that worked.. I changed to that because one of my other equations is almost identical except it utilizes subtraction and there were no issues. Previously I was just performing multiplication and division so this did not arise. I am converting my code from Python to JS, so I am learning on the fly. Thank you very much!
        – Evan Howington
        Dec 20 at 4:27












      • Every time I've tested it (which, admittedly, was a few versions ago), implicit casting has always been faster than explicit casting, for some reason. Of course, performance may not matter in this case, and you can call this more readable. But I tend to use a - -b to add strings as numbers.
        – trlkly
        Dec 20 at 6:11








      • 1




        "1" + "1" doesn't give 2, it gives "11". String concatenation always happens if one of the operands is a string (see step 7 in the addition operator evaluation)
        – Birjolaxew
        Dec 20 at 8:05










      • @Birjolaxew is absolutely correct, the sentence "Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers" does not reflect reality and is actually contradicting what you said before: "1" + "-1" does not get parsed, even though according to the quote it should. There is no logical reason for "1" + "-1" and "1" + "1" to produce two different types of results. It should be either treated as numeric in both cases or strings in both cases.
        – vlaz
        Dec 20 at 8:19










      • The statement following the quote "if the evaluated strings contains a character, it gets concatenated instead." is correct but I think you are misunderstanding the actual meaning. The result would be concatenation if any of the actual variables is a string - typeof someVar //"string" and not if the content of the variable can be parsed as numeric - someVar = "1". Also, another misconception here is that you consider - to be a "character" when "-1" is a string that can perfectly validly be parsed into a numeric and JS would tell you as much through Number().
        – vlaz
        Dec 20 at 8:24


















      All good answers. Thank you for showing the Number part in the code. I had changed it to initial_velocity - ((-1)*acceleration*time) and that worked.. I changed to that because one of my other equations is almost identical except it utilizes subtraction and there were no issues. Previously I was just performing multiplication and division so this did not arise. I am converting my code from Python to JS, so I am learning on the fly. Thank you very much!
      – Evan Howington
      Dec 20 at 4:27






      All good answers. Thank you for showing the Number part in the code. I had changed it to initial_velocity - ((-1)*acceleration*time) and that worked.. I changed to that because one of my other equations is almost identical except it utilizes subtraction and there were no issues. Previously I was just performing multiplication and division so this did not arise. I am converting my code from Python to JS, so I am learning on the fly. Thank you very much!
      – Evan Howington
      Dec 20 at 4:27














      Every time I've tested it (which, admittedly, was a few versions ago), implicit casting has always been faster than explicit casting, for some reason. Of course, performance may not matter in this case, and you can call this more readable. But I tend to use a - -b to add strings as numbers.
      – trlkly
      Dec 20 at 6:11






      Every time I've tested it (which, admittedly, was a few versions ago), implicit casting has always been faster than explicit casting, for some reason. Of course, performance may not matter in this case, and you can call this more readable. But I tend to use a - -b to add strings as numbers.
      – trlkly
      Dec 20 at 6:11






      1




      1




      "1" + "1" doesn't give 2, it gives "11". String concatenation always happens if one of the operands is a string (see step 7 in the addition operator evaluation)
      – Birjolaxew
      Dec 20 at 8:05




      "1" + "1" doesn't give 2, it gives "11". String concatenation always happens if one of the operands is a string (see step 7 in the addition operator evaluation)
      – Birjolaxew
      Dec 20 at 8:05












      @Birjolaxew is absolutely correct, the sentence "Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers" does not reflect reality and is actually contradicting what you said before: "1" + "-1" does not get parsed, even though according to the quote it should. There is no logical reason for "1" + "-1" and "1" + "1" to produce two different types of results. It should be either treated as numeric in both cases or strings in both cases.
      – vlaz
      Dec 20 at 8:19




      @Birjolaxew is absolutely correct, the sentence "Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers" does not reflect reality and is actually contradicting what you said before: "1" + "-1" does not get parsed, even though according to the quote it should. There is no logical reason for "1" + "-1" and "1" + "1" to produce two different types of results. It should be either treated as numeric in both cases or strings in both cases.
      – vlaz
      Dec 20 at 8:19












      The statement following the quote "if the evaluated strings contains a character, it gets concatenated instead." is correct but I think you are misunderstanding the actual meaning. The result would be concatenation if any of the actual variables is a string - typeof someVar //"string" and not if the content of the variable can be parsed as numeric - someVar = "1". Also, another misconception here is that you consider - to be a "character" when "-1" is a string that can perfectly validly be parsed into a numeric and JS would tell you as much through Number().
      – vlaz
      Dec 20 at 8:24






      The statement following the quote "if the evaluated strings contains a character, it gets concatenated instead." is correct but I think you are misunderstanding the actual meaning. The result would be concatenation if any of the actual variables is a string - typeof someVar //"string" and not if the content of the variable can be parsed as numeric - someVar = "1". Also, another misconception here is that you consider - to be a "character" when "-1" is a string that can perfectly validly be parsed into a numeric and JS would tell you as much through Number().
      – vlaz
      Dec 20 at 8:24















      7














      prompt always returns a string, not a number. Even if the person enters a number, it will be a string that represents that number, not a number itself.



      You will need to cast the results of prompt to a number before you can preform addition on it. When used with string, + is the concatenation operator, rather then the addition operator.



      Somewhat confusingly, you can actually use an unary + for this purpose.



      var initial_velocity = +prompt('Please enter the Initial Velocity in Meters per Second');
      var acceleration = +prompt('Please enter the acceleration in Meters per Second Squared');
      var time = +prompt('Please enter the time in seconds');
      var final_velocity = initial_velocity + acceleration * time;
      alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');





      share|improve this answer




























        7














        prompt always returns a string, not a number. Even if the person enters a number, it will be a string that represents that number, not a number itself.



        You will need to cast the results of prompt to a number before you can preform addition on it. When used with string, + is the concatenation operator, rather then the addition operator.



        Somewhat confusingly, you can actually use an unary + for this purpose.



        var initial_velocity = +prompt('Please enter the Initial Velocity in Meters per Second');
        var acceleration = +prompt('Please enter the acceleration in Meters per Second Squared');
        var time = +prompt('Please enter the time in seconds');
        var final_velocity = initial_velocity + acceleration * time;
        alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');





        share|improve this answer


























          7












          7








          7






          prompt always returns a string, not a number. Even if the person enters a number, it will be a string that represents that number, not a number itself.



          You will need to cast the results of prompt to a number before you can preform addition on it. When used with string, + is the concatenation operator, rather then the addition operator.



          Somewhat confusingly, you can actually use an unary + for this purpose.



          var initial_velocity = +prompt('Please enter the Initial Velocity in Meters per Second');
          var acceleration = +prompt('Please enter the acceleration in Meters per Second Squared');
          var time = +prompt('Please enter the time in seconds');
          var final_velocity = initial_velocity + acceleration * time;
          alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');





          share|improve this answer














          prompt always returns a string, not a number. Even if the person enters a number, it will be a string that represents that number, not a number itself.



          You will need to cast the results of prompt to a number before you can preform addition on it. When used with string, + is the concatenation operator, rather then the addition operator.



          Somewhat confusingly, you can actually use an unary + for this purpose.



          var initial_velocity = +prompt('Please enter the Initial Velocity in Meters per Second');
          var acceleration = +prompt('Please enter the acceleration in Meters per Second Squared');
          var time = +prompt('Please enter the time in seconds');
          var final_velocity = initial_velocity + acceleration * time;
          alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 20 at 4:25

























          answered Dec 20 at 3:56









          Alexander O'Mara

          43.1k1396128




          43.1k1396128























              2














              The + operator can be both addition and string concatenation. When the prompt box returns, it gives you back a string. String + number = string, so it concatenates (joins) the two values together instead of adding them. To fix this, you can convert the string to a number using a single + operator (and some parentheses if you want) to convert the string to a number, like so:






              function velocity_final()
              {
              var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
              var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
              var time = prompt('Please enter the time in seconds');
              var final_velocity = (+initial_velocity) + (+acceleration) * (+time);
              alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
              }

              console.log(velocity_final());





              You could also convert the values as soon as the prompt returns a value, if you wanted.



              PS: I removed the function parameters, as you set them manually anyways rather than passing anything in. If you do end up passing in values later rather than asking the user for them, you'll need to add those back into the function statement for them to be properly passed in.






              share|improve this answer


























                2














                The + operator can be both addition and string concatenation. When the prompt box returns, it gives you back a string. String + number = string, so it concatenates (joins) the two values together instead of adding them. To fix this, you can convert the string to a number using a single + operator (and some parentheses if you want) to convert the string to a number, like so:






                function velocity_final()
                {
                var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
                var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
                var time = prompt('Please enter the time in seconds');
                var final_velocity = (+initial_velocity) + (+acceleration) * (+time);
                alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
                }

                console.log(velocity_final());





                You could also convert the values as soon as the prompt returns a value, if you wanted.



                PS: I removed the function parameters, as you set them manually anyways rather than passing anything in. If you do end up passing in values later rather than asking the user for them, you'll need to add those back into the function statement for them to be properly passed in.






                share|improve this answer
























                  2












                  2








                  2






                  The + operator can be both addition and string concatenation. When the prompt box returns, it gives you back a string. String + number = string, so it concatenates (joins) the two values together instead of adding them. To fix this, you can convert the string to a number using a single + operator (and some parentheses if you want) to convert the string to a number, like so:






                  function velocity_final()
                  {
                  var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
                  var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
                  var time = prompt('Please enter the time in seconds');
                  var final_velocity = (+initial_velocity) + (+acceleration) * (+time);
                  alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
                  }

                  console.log(velocity_final());





                  You could also convert the values as soon as the prompt returns a value, if you wanted.



                  PS: I removed the function parameters, as you set them manually anyways rather than passing anything in. If you do end up passing in values later rather than asking the user for them, you'll need to add those back into the function statement for them to be properly passed in.






                  share|improve this answer












                  The + operator can be both addition and string concatenation. When the prompt box returns, it gives you back a string. String + number = string, so it concatenates (joins) the two values together instead of adding them. To fix this, you can convert the string to a number using a single + operator (and some parentheses if you want) to convert the string to a number, like so:






                  function velocity_final()
                  {
                  var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
                  var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
                  var time = prompt('Please enter the time in seconds');
                  var final_velocity = (+initial_velocity) + (+acceleration) * (+time);
                  alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
                  }

                  console.log(velocity_final());





                  You could also convert the values as soon as the prompt returns a value, if you wanted.



                  PS: I removed the function parameters, as you set them manually anyways rather than passing anything in. If you do end up passing in values later rather than asking the user for them, you'll need to add those back into the function statement for them to be properly passed in.






                  function velocity_final()
                  {
                  var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
                  var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
                  var time = prompt('Please enter the time in seconds');
                  var final_velocity = (+initial_velocity) + (+acceleration) * (+time);
                  alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
                  }

                  console.log(velocity_final());





                  function velocity_final()
                  {
                  var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
                  var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
                  var time = prompt('Please enter the time in seconds');
                  var final_velocity = (+initial_velocity) + (+acceleration) * (+time);
                  alert('The Final Velocity is '+ final_velocity + ' Meters Per Second');
                  }

                  console.log(velocity_final());






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 20 at 4:00









                  Feathercrown

                  1,70611021




                  1,70611021















                      Popular posts from this blog

                      "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                      Alcedinidae

                      RAC Tourist Trophy