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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Mozein
  • 787
  • 5
  • 19
  • 33
  • 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. – Eric Leschinski Jun 18 '15 at 16:39

2 Answers2

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

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
qianjiahao
  • 399
  • 1
  • 3
  • 10
  • 1
    Official from where? – j08691 Apr 19 '15 at 03:56
  • from the node.js , url : https://nodejs.org/api/assert.html#assert_assert_throws_block_error_message – qianjiahao Apr 19 '15 at 03:58
  • Nice, That is what I thought since I ran into a code where it says assert(!outerValue, " outer value is not here"). – Mozein Apr 19 '15 at 03:58
  • 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." – Robert Sep 15 '16 at 20:40
2

"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

Community
  • 1
  • 1
sarme
  • 1,337
  • 12
  • 19
  • But then in the Mozilla Docs they say "If the assertion is false, the message is written to the console." – Robert Sep 15 '16 at 20:38