0

In the book: "Secrets of the JavaScript Ninja" the author demonstrates this code:

<script type="text/javascript">
    var outerValue = 'ninja' 
    function outerFunction() {
        assert(outerValue, "I can see the ninja");
    }
    outerFunction();
</script>

The output is : I can see the ninja.

What is assert for? Why not just use console.log?

1
  • The first parameter of assert is evaluated for truthiness. If it is, it prints the second parameter. If not, it prints nothing. This is useful because we can use it to have the program print something only when an assertion has been violating, alarming people to take action. Commented Jun 18, 2015 at 16:39

2 Answers 2

2

Javascript assert, The official explanation:

assert(value[, message])

The square brackets around message means the second parameter is optional.

javascript assert Tests if the first parameter (value) is truthy, if it is, it prints the second optional parameter to stdout.

assert(outerValue, "I can see the ninja");

Your variable outerValues has the string "ninja", javascript evaluates that for truthiness, it is truthy, so it outputs "I can see the ninja".

Source: https://nodejs.org/api/assert.html

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

4 Comments

Official from where?
from the node.js , url : nodejs.org/api/…
Nice, That is what I thought since I ran into a code where it says assert(!outerValue, " outer value is not here").
But then in the node.js url they say "If value is not truthy, an AssertionError is thrown with a message property set equal to the value of the message parameter."
1

"assert" is a non-standard function. Although all the major browsers appear to have it in some form or another.

It writes a value to the console if the assertion is true. In this case, outerValue equates to a true value (e.g. not false). It is useful for testing and is not recommended for production use. The fact that it first evaluates a boolean value to determine if it should print the message makes it different from console.log.

Mozilla Docs
Already answered here

1 Comment

But then in the Mozilla Docs they say "If the assertion is false, the message is written to the console."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.