Why is Boolean([]) true in JavaScript? [duplicate] - javascript

This question already has answers here:
Why do empty JavaScript arrays evaluate to true in conditional structures?
(7 answers)
Closed 5 years ago.
I am going through JavaScript: The Definitive Guide. In it it says
Boolean([]) // => true
But I don't understand the logic behind this. Why is the boolean of an empty array true?

The ECMAScript specification defines how values are cast to booleans, per the abstract ToBoolean operation: https://www.ecma-international.org/ecma-262/6.0/#sec-toboolean
That operations includes a single entry for object input:
Object: Return true.
Thus, when you supply any object to Boolean, including an array (even an empty one), you'll get a true value back,

Array is considered as an object, even if it's empty. That's why the Boolean has a value, means it's true.
Only false, null or undefined are values which will return false.

JavaScript (and other languages) have a concept of 'truthy' and 'falsey' values.
You said you're from a C++ background, so we can make it analogous to something like this in C++:
if (ptr) { }
which is falsey if ptr is null, and truthy otherwise.
It just so happens that in JavaScript, arrays - even empty ones, among many other things - are considered to be truthy.

Related

Easiest way of checking the truthy of a value in javascript? [duplicate]

This question already has answers here:
Falsey values in JavaScript
(6 answers)
Convert truthy or falsy to an explicit boolean, i.e. to True or False
(2 answers)
Closed 3 years ago.
While programming with javascript, I come in some situations that I have a condition an wonder what values will pass that condition (if it will be truthy).
The solution I came up with is open the console in chrome and type if(foo) {true} and if the foo is truthy, it returns true, otherwise false.
An example of that is when I have some expression (foo) that won't return only true/false values. Inside the if it can return alot of things depending on the input (sometimes string, or number or maybe NaN).
But I fell that writing a if for that is too much.
Is there a easiest way of checking the truthy of a value in javascript?
Edit:
I'm looking for the easiest way of checking the truthy of a value, not just how to check and as I said in my question, I already do if(foo) {true} to check, but I'm looking for a easiest way
I would use a ternary operator to shorthand the if-statement.
The result is something like this:
const foo = true;
console.log(foo ? 'truthy' : 'falsy'); // returns truthy

Javascript: If([]) unexpected result [duplicate]

This question already has answers here:
Why if([]) is validated while [] == false in javascript?
(3 answers)
Closed 6 years ago.
I think in every language I know
if(a)
is the same thing as
if(a == true)
Turns out in JavaScript it isn't true, because:
if([])
Seems to act as if the condition is fulfilled, but:
if([] == true)
Does the opposite thing.
I can't really find any possible explanation, especially that this problem doesn't occur with empty string for example (which is == true, but isn't === true, same as empty array). Is this a bug in JavaScript or what?
In JavaScript, there is a concept of truthy and falsey values. if statements test the truthiness or falsiness of a given value rather than strict equality to true or false.
true is obviously truthy. false is obviously falsey. The rest can be a little tricky. MDN has possibly the clearest documentation about which values evaluate to falsey: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
In this case [] is a truthy value so the condition passes and the code is executed.

test if a variable is a primitive rather than an object? [duplicate]

This question already has answers here:
Check if a value is an object in JavaScript
(54 answers)
Closed 7 years ago.
Is it possible to test a variable to see if it is a primitive?
I have seen lots of questions about testing an variable to see if it is an object, but not testing for a primitive.
This question is academic, I don't actually need to perform this test from my own code. I'm just trying to get a deeper understanding of JavaScript.
To test for any primitive:
function isPrimitive(test) {
return test !== Object(test);
}
Example:
isPrimitive(100); // true
isPrimitive(new Number(100)); // false
http://jsfiddle.net/kieranpotts/dy791s96/
Object accepts an argument and returns if it is an object, or returns an object otherwise.
Then, you can use a strict equality comparison, which compares types and values.
If value was an object, Object(value) will be the same object, so value === Object(value). If value wasn't an object, value !== Object(value) because they will have different types.
So you can use
Object(value) !== value

Javascript Set: any way to override comparison between elements? [duplicate]

This question already has answers here:
user defined object equality for a set in harmony (es6)
(2 answers)
Closed 7 years ago.
A Set handles 2 empty objects as different, e.g.:
let s = new Set([ {} ]);
s.has({}); // false
This is expected, but it would be useful to compare based on their contents instead, as is possible in various other languages.
Is there any way to override the Set's internal comparison operator?
Is there any way to override the Set's internal comparison operator?
No. Set.prototype.has is defined like this:
23.2.3.7 - Set.prototype.has ( value )
The following steps are taken:
Let S be the this value.
If Type(S) is not Object, throw a TypeError exception.
If S does not have a [[SetData]] internal slot throw a TypeError exception.
Let entries be the List that is the value of S’s [[SetData]] internal slot.
Repeat for each e that is an element of entries,
If e is not empty and SameValueZero(e, value) is true, return true.
Return false.
Therefore, Set must compare using SameValueZero comparison, and you can't change that.
No, there isn't. The comparison used for Set instances is almost the same as the === operator, except that NaN can be put in a Set (once), meaning that NaN is treated as being === to itself for that purpose.

Why does `0 in [1]` evaluate to `true`? [duplicate]

This question already has answers here:
JavaScript 'in' operator for `undefined` elements in Arrays
(3 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 8 years ago.
Apparently 0 in [1] is not the right way to find out whether the array [1] contains the item 0. Is there a JS compatible way to do this without iterating the collection?
You'd think 0 in [3,1] would evaluate to false. But it evaluates to true. I think this is because null, false and zero are sometimes treated as equivalent.
No, you have a misunderstanding of what in does. It tests whether the object has a property with that name. Arrays are just objects with numeric properties:
> console.dir([3,1]);
Array[2]
0: 3
1: 1
length: 2
The array has an element at index 0, hence the test is true. 'length' in [3,1] returns true as well.
null, false and zero are sometimes treated as equivalent
null, false and 0 are all "falsy" values, i.e. they become to false when converted to a Boolean. This is consistent with other dynamically typed languages, such as PHP or Python.
JavaScript can have surprising behavior, especially when it comes to type conversion, but it is deterministic. It's recommended to simply avoid type conversion if possible.

Categories