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

175
Vistas
How to convert a numeric property of an object in a class to a number and add with other numbers in JS?

I want to add 2 values together at the method in the customer class. one of them is a number and the other is an object property stored in a new class, the send method(a-b) works well, but the receive method(a+b) doesn't work as a number because it's an object and it is like a string in js, what is the solution?

export class Customer {
  constructor(name, password, balance) {
    {
      this.name = name;
      this.password = password;
      this.balance = balance;
    }

    this.send = function (amount) {
      return (this.balance -= amount);
    };
    this.receive = function (amount) {
      return (this.balance += amount);
    };
  }
}

export let student = new Customer("alex", "alex", 200);
export let victim1 = new Customer("tom", "cat", 1000);
export let victim2 = new Customer("jerry", "mous", 500);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use unary plus operator to convert amount to number before use it

class Customer {
  constructor(name, password, balance) {
    {
      this.name = name;
      this.password = password;
      this.balance = balance;
    }

    this.send = function (amount) {
      return (this.balance -= +amount); // magic here
    };
    this.receive = function (amount) {
      return (this.balance += +amount); // and here
    };
  }
}

let student = new Customer("alex", "alex", 200);
let victim1 = new Customer("tom", "cat", 1000);

student.send(victim1.balance);
console.log(student.balance)
student.receive(victim1.balance);
console.log(student.balance)

student.send("500");
console.log(student.balance)
student.receive("100");
console.log(student.balance)

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