How does toString work in Javascript?

Asked

Viewed 595 times

2

I really wanted to understand what it’s for and how to use the method toString, why I always search on websites and can’t understand the way they are talking and demonstrating, so if anyone can explain to me what this method serves, as well as what ways to use it will help me a lot.

I have the code below, showing the command I learned by classes around, but I don’t understand how the toString.

/* Objetivo: Desenvolver um programa em JavaScript que faça a leitura de 2 números Inteiros
   aplique a conversão de valores com parseInt e apresente o resultado da soma entre eles.
   Entrada de Dados por Formulário. */

/* Definição de Variáveis */
var js_n1;
var js_n2;
var js_soma;

/* Definição da função soma() para capturar dados, processar somatória e apresentar o resultado */
function soma() {
    /* Entrada de Dados */
    js_n1 = parseInt(document.MeuFormulario.f_n1.value);
    js_n2 = parseInt(document.MeuFormulario.f_n2.value);

    /* Processamento de Dados */
    js_soma = js_n1 + js_n2;

    /* Saída de Dados */
    window.alert('Resultado da Somatória = ' + js_soma.toString());
}
<h3>Somatória de dois números inteiros</h3>

<!-- Definição da área e dos elementos de um Formulário -->
<form name="MeuFormulario" action="" method="POST">
    Entre com o valor 1: <input type="text" name="f_n1"><p><p>
    Entre com o valor 2: <input type="text" name="f_n2"><p><p>
    <input type="button" name="btn_somar" value="Somar" onclick="soma()">
    <input type="reset" name="btn_apagar" value="Apagar">
</form>

2 answers

7


The toString is a method available in several Javascript objects. It has a different behavior depending on the object it is part of. However, it always has the same goal, that is, to create a string representation of the object that calls it.

In your case, the toString is part of the prototype of Number, and converts a number into a string following this specification.

Still in your example in question, call the toString in one number is unnecessary since the operator + will already do it for you. To learn more about this operator behavior +, read this other answer.

console.log('Exemplo ' + (1).toString());
console.log('Exemplo ' + 2);

In the case of Number.prototype.toString, an argument radix may be informed to form the representation of the number on another numerical basis, as binary (if received 2 in the argument Radix), hexadecimal (if received 16), etc..

For example:

const num = 123456;

// Quando não é informado um argumento radix, o padrão será 10.
console.log(num.toString()); // 123456
console.log(num.toString(10)); // 123456

// Valor mínimo do argumento radix (2):
console.log(num.toString(2)); // 11110001001000000

// Exemplo de converter um número para a sua representação em hexadecimal:
console.log(num.toString(16)); // 1e240

// Valor máximo do argumento radix (36):
console.log(num.toString(36)); // 2n9c

  • To which "comment" you refer?

  • 3

    @x7MKDeath7x if you want it to erase the reply, that’s not how the site works. Do the [tour]

  • Not quite so (// Number 2 is converted to string by the operator +.). What happens is that if you add a string to a number, you convert the number into its string equivalent.

  • @Leocaracciolo, yes, is it wrong? Above the code of this comment, there is a more detailed explanation. Basically, the binary operator is responsible for the conversion +.

  • I just wanted to help, what makes it clear in the sentence is that if you simply put the + sign before the number converts it into a string.

  • Yes, I understand, thank you. : ) I removed that comment from the code, leaving only the explanation (more detailed) above it.

Show 1 more comment

0

Well, the method toString() converts Javascript values to strings. In your case, return the sum value to string. For the value original is a number.

Examples

Using a boolean value

const valor = true
console.log(valor.toString()) // Retorna: "true"

Using in an array

const array = new Array("Olá", "mundo!")
console.log(array.toString()) // Retorna: "Olá mundo!"

Using in numbers

const numero  = 13
console.log(numero.toString()) //  Retorna: "13"

Learn more in MDN Web Docs

See you around!

  • const array = new Array("Olá", "mundo!"); console.log(array.toString()); does not return "Olá mundo!" this code will return "Olá,mundo!" where the result of the method implementation will be returned toString() for each comma-separated array element

Browser other questions tagged

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