Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic math not working right with numbers passed-in from process.argv[]. #42445

Closed
robherc opened this issue Mar 23, 2022 · 1 comment
Closed

Comments

@robherc
Copy link

robherc commented Mar 23, 2022

Version

17.8.1

Platform

Linux [my-computer-hostname] 5.13.0-35-generic #40~20.04.1-Ubuntu SMP Mon Mar 7 09:18:32 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

Subsystem

No response

What steps will reproduce the bug?

1: Assign numeric values from process.argv[] to variables declared with let (i.e. let x=process.argv[2]; let y=process.argv[3]; let z=process.argv[4]
2: Perform some basic arithmetic on those variables (i.e. let answer=x*(y+z);)
3: See ridiculous output (above answer would come out as x * y.concat(z);)

Testing code that I'm using:

let x   = process.argv[2];
let y   = process.argv[3];
let z   = process.argv[4];
console.log("Using values from process.argv[]:");
console.log(`x=${x} | y=${y} | z=${z}`);
console.log(`x-y=${x-y}\nx/y=${x/y}\nx*(y+z)=${x*(y+z)}`);

let a=1;
let b=2;
let c=3;
let answer=a*(b+c);
console.log("\n\nUsing values declared within the script:");
console.log(`a=${a} | b=${b} | z=${c}`);
console.log(`a-b=${a-b}\na/b=${a/b}\na*(b+c)=${a*(b+c)}`);

How often does it reproduce? Is there a required condition?

Always. Seems to be a variable type auto-detect error when using numeric values from process.argv[]

What is the expected behavior?

node mathbugtest.js 1 2 3 [Enter]
x=1 | y=2 | z=3
x-y=-1
x/y=0.5
x*(y+z)=5

What do you see instead?

node mathbugtest.js 1 2 3 [Enter]
x=1 | y=2 | z=3
x-y=-1
x/y=0.5
x*(y+z)=23

Screenshot_2022-03-23_11-47-30

Additional information

No response

@cjihrig
Copy link
Contributor

cjihrig commented Mar 23, 2022

The values coming from process.argv are strings. The + operator performs string concatenation or addition, depending on the type of the values being used, while the -, *, and / operators convert the values to numbers first.

This is not specific to Node.js. You can try it in a browser or Deno as well. Closing as working as intended.

@cjihrig cjihrig closed this as completed Mar 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants