Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does {} == false throw an exception?

Tags:

In IE and Chrome, typing this into the JavaScript console throws an exception:

{} == false   // "SyntaxError: Unexpected token ==" 

However, all of these statements are evaluated with no problem:

false == {}   // false  ({} == false) // false  var a = {}; a == false    // false 

Is this intentional behavior? Why does this happen?

like image 547
Jonn Avatar asked May 22 '14 01:05

Jonn


People also ask

Does throwing an exception return false?

Since it returns a boolean value, there would be no need of throwing an exception, simply return false.

How do you know if a method throws an exception?

The calculate method should check for an exception and if there is no exception, return the calculated value to the main function i.e. v1+v2 or v1-v2; Else if an exception exists then it should print the error statement and the value that is returned from the calculate method to the main method should be 0.0(Not ...

What does throw error do JavaScript?

Definition and UsageThe throw statement throws (generates) an error. The technical term for this is: The throw statement throws an exception. The exception can be a JavaScript String, a Number, a Boolean or an Object: throw "Too big"; // throw a text.

What's the difference between throw error (' MSG ') vs throw new error (' MSG ')?

throw new Error() Creating objects using ES6 classes requires the use of new and extending Error via a class is the only way to preserve stack traces. throw Error() is like a Javascript string, a number, a boolean, or an object. It returns specific errors as defined in the message value which is passed as an argument.


1 Answers

In the console, when you start a statement with {}, you are not creating an object literal, but a code block (i.e. the same block as you would make with an if statement or a loop body). A symbol like == is then obviously not expected afterwards.

If you think of a code block, you know that something like a = 5; could come after it:

if (some_condition) {     // do something } a = 5; 

You can then use this to test in the console, and find that it works just fine:

{} a = 5; 
like image 135
ajp15243 Avatar answered Sep 19 '22 19:09

ajp15243