0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.