Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a boolean literal and a boolean value?

I can't seem to find a clear explanation as to what the difference is between these two. I'd also like to point out that I don't really understand the difference between literals and values either.

Do boolean literals use the Boolean object?

like image 882
Joesph Neplton Avatar asked May 01 '13 22:05

Joesph Neplton


1 Answers

A literal is a value you literally provide in your script, so they are fixed.

A value is "a piece of data". So a literal is a value, but not all values are literals.

Example:

1; // 1 is a literal
var x = 2; // x takes the value of the literal 2
x = x + 3; // Adds the value of the literal 3 to x. x now has the value 5, but 5 is not a literal.

For your second part of the question you need to know what a primitive is. It's a little more complicated than this, but you can view them as "all types that aren't an object". Javascript has 5 of those, including boolean and number. So those aren't usually an object.

Why then can you still do (152).toString() in Javascript? This is because of a mechanism called Coercion (in other languages also called auto-boxing). When required the Javascript engine will convert between a primitive and its object wrapper, e.g. boolean and Boolean. Here is an excellent explanation of Javascript primitives and auto-boxing.

Not that this behaviour isn't really what you'd expect sometimes, especially with Boolean

Example:

true; // this is a `boolean` primitive
new Boolean(true); // This results in an object, but the literal `true` is still a primitive
(true).toString(); // The literal true is converted into a Boolean object and its toString method is called
if(new Boolean(false)) { alert('Eh?'); }; // Will alert, as every Boolean object that isn't null or undefined evaluates to true (since it exists)
like image 117
dtech Avatar answered Sep 18 '22 22:09

dtech