Why does ",,," == new Array(4) [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does “,,,” == Array(4) in Javascript?
In JavaScript why does
",,," == new Array(4)
It returns true in Chrome Developer Tools, and nodejs console.

console.log(new Array(4).toString()); // ",,,"
casted to string with above value making both equal.
",,," == ",,," // true
JS sees that on left hand is a string and on right hand side an array which is not good for comparison, it casts array to string and then does the comparison.
Notice that:
log(",,," === new Array(4));
would result in false since === checks not only for value but also type and types are different of course.

Because the new Array(4) is being implicitly cast to a string, which will equal ",,," (four empty elements, comma separated).

Because Array(4).toString() returns ",,," - 4 empty elements, so only the commas between them

An array in String form produces a comma separated list of the elements, ie 1,2,3,4. If there are no elements in the Array, it will show up as ,,,.
(new Array(4)).toString() produces ,,,.
Note that new Array(4) === ",,," returns false.

Related

Why `1 > undefined` evaluates to false? [duplicate]

This question already has answers here:
Why NaN is greater than any number in JavaScript? [duplicate]
(2 answers)
Closed 4 years ago.
I am trying to make some conditional statements while trying to solve a coding challenge. I have kept track of all the occurrences of letters of two strings in different objects. When I try to compare them by their counts if the count is undefined in the other object it evaluates to false even though the first value is truthy.
However;
1 > Boolean(undefined) evaluates to true. However 1 > undefined evaluates to false. Is there reason why the behavior is so ?
Javascript does a lot of funky casting when you compare things together that usually shouldn't be comparable.
1>undefined casts undefined to a NaN, and you can't compare a number to a Not a Number so any comparison will return false >,<,== etc
When you do 1>Boolean(undefined) undefined is cast to its boolean equivalent false, then when it's compared it will be cast to a 0, you can confirm this by doing Number(Boolean(undefined)) and since 1 is bigger than 0 it returns true.
In order to use the comparison operator >, both operands must be numeric. 1 already is, so Boolean(undefined) (which evaluates to false by the way) must be converted to a number. When it is, you get 0.
// First, convert undefined to a Boolean
let bool = Boolean(undefined)
console.log(bool);
// Then convert that to a number
let num = Number(bool);
console.log(num);
So, 1 > 0 is true.
Things to understand:
JavaScript is a "loosely" or "weakly" typed language. This means that data can, and often is, implicitly converted (coerced) into a different type category.
All data can be classified as "truthy" or "falsy", which means that if converted to a Boolean, would it convert to true or false. Things like null, undefined, "", 0, false, and NaN are all "falsy". And false in JavaScript (and most other languages) converts to the number 0, while true usually converts to 1.

What happens when we declare Array(4) in JavaScript? [duplicate]

This question already has answers here:
Javascript new Array and join() method
(5 answers)
Closed 6 years ago.
console.log(Array(4).join("hi"));
>> "hihihi"
I don't get what exactly is happening here?
join() is the opposite of split(). whereas split separates an array by the delimiting character you pass it, join will instead combine all the elements delimiting each one with whatever parameter you pass.
In this case the array is simply Array(4), so 4 undefined elements. combining these will yield "undefinedhiundefinedhiundefinedhiundefined".
Since js doesn't actually treat undefined as anything in this case, it turns it into an empty string and all you get is hihihi
edit: reference for my last statement from the join() documentation:
The string conversions of all array elements are joined into one string. If an element is undefined or null, it is converted to the empty string.

Why do all numbers except 0 pass an if statement in JavaScript? [duplicate]

This question already has answers here:
All falsey values in JavaScript
(4 answers)
Closed 7 years ago.
This is something that I've always wondered. According to MDN, in JavaScript "The if statement executes a statement if a specified condition is true". So then why does this pass the statement?
var a = 7;
if( a ) {
alert('true');
} else {
alert('false');
}
The variable is neither true nor false, so why does it alert "true" instead of just skipping the entire if statement?
"is true" means "an expression that evaluates to a true value" not "is exactly equal to the boolean object true".
The formal language can be found in the specification.
Let exprRef be the result of evaluating Expression. If
ToBoolean(GetValue(exprRef)) is true, then Return the result of
evaluating the first Statement. Else, Return the result of
evaluating the second Statement.
In Javascript following values are always falsy:
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.
If you want to compare with true without type conversion try a === true.
In JavaScript if(var) evaluates not just for boolean, but also for defined/initialized or non defined variables.
For example, if a var is undefined or null in that case if evaluates them to false
As stated by other before, it's performing a boolean test on the variable.
Boolean values are binary; that's to say, the only possible values are 0 and 1, where true = 1, and false = 0.
The value you hard-coded into the if-statement is 7 = 0111, and all it takes is one of those numbers being a '1' to make it pass the test.
It work the same way with letters, except the if statement will convert letters from ASCII to binary: "A" = 0100 0001 (registered as 65 in ASCII. http://www.asciitable.com/) On the other hand, no input will return a false statement.
In a computer, everything is a number. Boolean too, and usually are just one bit: 0 or 1.
But computer use more than one bit to store data, so Boolean are more than 0 or 1, but also 255, 42, or 25, while still having to pass a simple test.
So by convention, 0 is false, and any other value is true.

JavaScript Expression [duplicate]

This question already has answers here:
Why does ++[[]][+[]]+[+[]] return the string "10"?
(10 answers)
Closed 8 years ago.
Can anyone help me with this JavaScript expression?
+[[+!![]]+[+![]]+[+!![]]+[-~!![]+-~!![]-~!![]]+[-~!![]]+[+![]]+[+!![]]+[-~!![]+-~!![]]]
A friend sent it to me and asked me to copy and paste it in the browser console.
This is the result:
10162014
If anyone could explain this to me or at least point me to right references please. Thanks!
First break out your code to this: !![] which returns true (!! is to convert to boolean) and now + converts to number so +!![] returns 1.
![] converts to false so +![] returns 0.
~[] returns -1 and ~![] also returns -1.
~!![] returns -2.
Now, -~!![] returns 2 and -~![] returns 1.
So, combining them all returns 10162014.
All about you to know is ~, !, +, & -
![] = false; # as an expression, it's false due to the ! operatory
[] = true; # as an expression, it's defined, so it's true
+!![] = 1; because +true = 1;
+![] = 1; because +true = 0, because using a + operator in JS converts the boolean to an integer ref
So what he's done is basically constructed a numerical value using boolean to integer conversion, and some grouping.
[+!![]]+[+![]]+[+!![]]: [] is an empty array, which is truthy. ![] is thus false, !![] is true. +true forces it to a number, as 1. Similarly for +![] as 0 via false.
[-~!![]+-~!![]-~!![]]: ~ is a two's complement operator; ~1 is -2. Thus, this evaluates as -(-2)+-(-2)+-(-2), which is 6.
The remaining addends are analogous.
array + array will convert arrays to strings; thus [1]+[0]+[1]+[6]... will give the string "1016..."
The plus at start will convert it to a number.

Why does ",,," == Array(4) in Javascript?

Boot up your interpreter/console and try the comparison
> ",,," == Array(4)
True
Why? At first I thought maybe since you could think of ",,," as an array of four characters with a '\0' terminating slice, that might be why, but
> "..." == Array(4)
Returns "False". So... why? I know it's some idiosyncratic bit of duck typing in Javascript, but just curious what underlines this behavior. Gleaned this from Zed Shaw's excellent presentation here btw.
Because the right hand operand is converted to a string and the string representation of Array(4) is ,,,:
> Array(4).toString()
",,,"
If you use the array constructor function and pass a number, it sets the length of the array to that number. So you can say you have four empty indexes (same as [,,,]) and the default string representation of arrays is a comma-separated list of its elements:
> ['a','b','c'].toString()
"a,b,c"
How the comparison works is described in section 11.9.3 of the specification. There you will see (x == y):
8. If Type(x) is either String or Number and Type(y) is Object,
return the result of the comparison x == ToPrimitive(y).
(arrays are objects in JavaScript)
and if you follow the ToPrimitive method you will eventually find that it it calls toString.
Internally its going
",,," == Array(4).toString()
Try using ===. When using == in Javascript, it will attempt to cast the variables, thus leading to issues like this one. The console is casting Array(4) to the string representation (i.e. Array(4).toString), which is ",,,". The reason the commas are there is that the .toString() function adds them to separate items in an array.
See the snippet below:
document.write( Array(4).toString() );
This is because Array(4) initialises an array of 4 empty values, an == implicitly converts, so:
",,," == Array(4)
",,," == Array(4).toString()
",,," == ["", "", "", ""] // note 3 commas for 4 values
",,," == ["", "", "", ""].toString()
Are all similar.
== does implicit type conversions before comparing the values, which can result in unpredictable results. Use === to check the type and the value.
Comparing an Array to a string coerces the Array to a string before doing the comparison. Coercing an empty 4-element Array to a string yields that exact string.
I first thought it was something with the "prototype"... but after a little investigation I reached a sad conclusion...
Apparently it is an internal and more obscure js thing with not much logic...
Just try
Array(4)==Array(4)
and no coercion on types also...
Array(4)===Array(4)
and you'll get FALSE
you know that null==null, null===null and even undefined==undefined and undefined===undefined returns TRUE... so... it's a bit obscure...
Array(4)==[,,,] should be true also

Categories