Change the type of a variable in a statement of a line, change the type of variables that come and sequence, why?

Asked

Viewed 87 times

5

By declaring more than one variable of the same type on a line, I can subsequently perform arithmetic operations with these values. Ex.:

let num1 = 10, num2 = 5, num3= 10;

let resultado = num1 + num2 + num3;

console.log(resultado); //O resultado será 25

However, if I change the type of the first variable num1 to string and try to perform the same operation:

let num1 = "10", num2 = 5, num3 = 10;

let resultado = num1 + num2 + num3;

console.log(resultado); //O resultado será 10510

Why does this behavior occur? Why are all variables converted?

  • First remark: When a string variable starts,this happens,now if it is after no and some if it gives Nan.

  • 1

    https://answall.com/questions/126163/por-que-a-minha-fun%C3%A7%C3%A3o-est%C3%A1-concatenating-ao-Inv%C3%A9s-de-summing-os-n%C3%Bameros

  • 1

    I can give you an example: "2"+2="22"; 2+2+"2"="42"

  • 1

    I think it is worth mentioning that the fact that the variables are declared on the same line makes no difference, what matters is only the type of them.

2 answers

8


This is because when finding a text value, everything else is treated as text because the operating signal + becomes the concatenate operation.

But note that this only occurs when finding a text, see these examples that the operations before are performed, and the later ones (to the text) are all treated as text:

console.log(10+20+30+40);  // tudo somado
console.log(10+20+30+"40"); // 10+20+30 somado, depois concatenado
console.log(10+20+"30"+40); // 10+20 somado, depois concatenado
console.log(10+"20"+30+40); // tudo concatenado
console.log("10"+20+30+40); // tudo concatenado

4

Complementing the answer from Ricardo, the fact that variables are declared on the same line makes no difference. If so, it gives the same result:

let num1 = "10";
let num2 = 5;
let num3 = 10;

let resultado = num1 + num2 + num3;

console.log(resultado); // 10510

For what defines the + will be treated as "sum" or "concatenation" is the type of variables involved in the operation.

If you want to force num1 be a number, just use parseInt:

let num1 = "10";
let num2 = 5;
let num3 = 10;

let resultado = parseInt(num1) + num2 + num3;

console.log(resultado); // 25

  • 1

    good, and liked this link of the "variable types" good examples

  • @Ricardopunctual Javascript has some bizarres, right? What happens if add [] + {}? Is the same as {} + []? Answers: https://www.destroyallsoftware.com/talks/wat

  • 1

    it’s true, I think because it’s not well typed, the language allows these bizarre things, hence the most sinister bugs appear :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.