Neil Graham
Neil Graham

Reputation: 863

JavaScript: Converting expression to string

I am trying to find a way to cast an expression such as a condition statement to a string without having the expression being processed.

I tried using the .toString() method on the 'condition' parameter in the following 'assert' function.

const config = {
  usernme: 'username1',
  password: 'password1'
}

function assert(condition, message) {
  if (!condition) {
    message = message || `Assertion failed: ${condition.toString()}`;
    if (typeof Error !== "undefined") {
      throw new Error(message);
    }
    throw message; // Fallback
  }
}

assert('username' in config);

Actual error message: Assertion failed: false

Anticipated error message: Assertion failed: 'username' in config

Upvotes: 0

Views: 169

Answers (1)

IceMetalPunk
IceMetalPunk

Reputation: 5556

There's no way to do it like that; the expression is evaluated before your function is even called, and only its resulting value is passed to your function. You could supply the expression as a string to begin with, and evaluate it with eval(condition), but be warned that eval is frowned upon as it can be easy to accidentally introduce security vulnerabilities that way.

The way console.assert() handles this is that the expression is one argument, and then a custom label (as a string) is a second argument, so you can specify the label yourself, including just copy/pasting the expression and putting it in quotes for a string.

Upvotes: 1

Related Questions