Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

145
Vistas
Output of string in function gives an object

I tring to print to string but it's for some reason gives an object..

I want to get (example 20220515) as string and then slice it, to get two first digits.

// Button
const birthDate = document.querySelector('#dateSubmit');

// Date input
birthDate.onclick = function() {
    let in1 = document.querySelector('#birthday');
    let birthDate = (in1.value).replaceAll("-", "");
    let dateNow = 20220515;
    let old = dateNow - parseInt(birthDate); // 320411
    let result = toString(old);

    console.log(result);  // [object Undefined] ?

    console.log(typeof result);  // string 
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

This is basically a typo, you want old.toString(), not toString(old) (and you can't use those date-like numbers like that, more below¹). But then the question is: What is this global toString function and why, when you call it, do you get the string "[object Undefined]"?? Example:

console.log(toString());      // "[object Undefined]"
console.log(toString(42));    // "[object Undefined]"
console.log(toString("hi"));  // "[object Undefined]"

The answer lies in the complex nature of the JavaScript global environment. The global environment closes over the global object (see the spec here and here). That means that all properties of the global object are accessible as globals. The global object inherits from Object.prototype, which defines toString, so the global toString is Object.prototype.toString:

console.log(toString === Object.prototype.toString); // true

Okay, so far so good. But why does calling toString give us "[object Undefined]"?

Because Object.prototype.toString is defined as a strict mode function, which means freestanding calls to it like toString() get the value undefined as this. Object.prototype.toString is defined as returning "[object Undefined]" when you call it with this set to undefined.


¹ So about those date-like numbers, 20220515 and such. You can't usefully do date math with those numbers. Instead, use Date instances and milliseconds-since-The-Epoch, the number value (the number of milliseconds since Jan 1st 1970 at midnight GMT) that underlies dates. (Or you might look at using the upcoming Temporal stuff.) For example:

const dateNow = new Date();
const birthDate = new Date(in1.value); // **ONLY** if it's in the right format
const millisecondsSinceBirth = birthDate - birthday;

From those milliseconds you can work out years, months, days, etc.

new Date only knows how to parse a very specific format, see this question's answers for parsing suggestions for other formats.

about 4 years ago · Juan Pablo Isaza Denunciar

0

The function toString() does not pass a variable to it, its general formula:

Number.prototype.toString()

it is like this to convert the number to text,

modify the code as follows:

// Button
const birthDate = document.querySelector('#dateSubmit');

// Date input
birthDate.onclick = function() {
let in1 = document.querySelector('#birthday');
let birthDate = (in1.value).replaceAll("-", "");
let dateNow = 20220515;
let old = dateNow - parseInt(birthDate); // 320411
let result = old.toString();

console.log(result);  // 320411

console.log(typeof result);  // string 
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

I should have used "String()" instead "toString()"

// Button
const birthDate = document.querySelector('#dateSubmit');

// Date input
birthDate.onclick = function() {
    let in1 = document.querySelector('#birthday');
    let birthDate = (in1.value).replaceAll("-", "");
    let dateNow = 20220515;
    const num = dateNow - parseInt(birthDate); // 320411

    const first2Str = String(num).slice(0, 2); // 👉️ '13'
    const first2Num = Number(first2Str); // 👉️ 13

    console.log(first2Num);

}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda