Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
JavaScript arithmetic operations between strings of numbers

I'm wondering what happens behind the scenes when we either add, subtract or multiply two strings of numbers. Here is an example:

let strNum1 = "300";
let strNum2 = "22";

let multiply = function(num1, num2) {
    let product = num1 * num2;
    
    return `${product}`
      
};

multiply(strNum1, strNum2); //this will return ==> "6600"

Does the JS engine turns these into integers first and then performs the operations or does it know "magically" that they are numbers even though it's in a string form? The reason I'm asking is because of the long multiplication algorithm. For numbers bigger than 8 chars it becomes funky when multiplying with the operator vs using the algorithm.

This is a leetcode question btw.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can parse your values before and after operation:

let multiply = function(num1 = '', num2 = '') {
    const product = Number(num1) * Number(num2);
    
    return `${product}` // Or String(product)
};
about 4 years ago · Juan Pablo Isaza Relatório

0

To answer your question: The JS Engine turns those strings into integers before doing the arithmetic operation. It is called Implicit coercion.

You can read more about that in this You Don't Know JS Chapter.

about 4 years ago · Juan Pablo Isaza Relatório

0

In case of addition (+), When a number is added to a string, JavaScript converts the number to a string before concatenation but in case of other arithmetic operations like *, -, / JS engine implicitly convert the string into integer.

Demo :

let result;

// numeric string used with + gives string type

result = '3' + '2'; 
console.log(result, typeof result) // "32", "string"

// numeric string used with - , / , * results number type

result = '3' * '2'; 
console.log(result, typeof result) // 6, "number"

result = '3' - '2'; 
console.log(result, typeof result) // 1, "number"

result = '3' / '2'; 
console.log(result, typeof result) // 1.5, "number"

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda