In terms of comparison, Javascript always sees a numeric string as a number. In your case, the number 2 is seen as a value to be compared, no matter if it is a string or not.
Except in cases of mathematical operations, Javascript will consider the type in case of sum, because of the sign +
which is also used in concatenation. Example:
pessoa = {
nome: 'leandro',
idade: '2'
}
console.log(pessoa.idade+1); // imprime 21
To sum the value would need to convert the string to number using, for example, parseInt()
:
pessoa = {
nome: 'leandro',
idade: '2'
}
console.log(parseInt(pessoa.idade)+1); // imprime 3
In the case of subtractions, divisions and multiplications, the value shall be considered an absolute number:
pessoa = {
nome: 'leandro',
idade: '2. '
}
console.log(pessoa.idade-1); // subtração: imprime 1
console.log(pessoa.idade/2); // divisão: imprime 1
console.log(pessoa.idade*3); // multiplicação: imprime 6
See what the value in idade
i put a dot and several spaces. Javascript will convert the string value to absolute value. Since point is the decimal separator and spaces are ignored, the absolute value of the string will be only 2
.
vlw mano I’m starting a couple of weeks still am adapting to the JS
– Leandro Lobo