Skip to content

Why I got Illegal arguments error with simple hash function?

This is my code

const bcrypt = require('bcryptjs');
const salt = bcrypt.genSalt(11);

const user = {
    first: "Donald",
    last: "Trump",
    password : bcrypt.hash(this.password, salt),
    greetUser(password) {
      console.log(`Hi, ${this.first} ${this.last} ${this.password}`);
    },
  };
  
  let password = 'secondhand01';
  user.greetUser(password);

I run

node --trace-warnings index.js

Hi, Donald Trump [object Promise]
(node:15222) UnhandledPromiseRejectionWarning: Error: Illegal arguments: undefined, object

I expected hashed password. Why does terminal point to illegal arguments?

Answer

In an object literal, password : bcrypt.hash(this.password, salt) calls bcrypt.hash and assigns its return value to the password property. In the code you’ve shown, this doesn’t refer to the object being created, it refers to the same thing this refers to where the object literal is being created (the top level of the module). Since that doesn’t have a password property, you’re passing undefined to the function.

bcrypt.hash also returns a promise, as you can see from the output you get before the unhandled promise rejection.

Your user object is being populated with hardcoded values, so you may have meant to do something like this:

const bcrypt = require('bcryptjs');
const salt = bcrypt.genSalt(11);

bcrypt.hash("secondhand01", salt) // <=== Encrypt the password
.then(hashedPassword => {
    // You have it now, you can build and use the object
    const user = {
        first: "Donald",
        last: "Trump",
        password : hashedPassword,
        greetUser() { // Note I removed the parameter you weren't using here
          console.log(`Hi, ${this.first} ${this.last} ${this.password}`);
        },
    };
      
    user.greetUser(); // Note I removed the unused argument here
})
.catch(error => {
    // Handle/report the error...
});