JavaScript Quiz #6

Assume that we have the following short JavaScript code:

<script>
	var result = [12 + 21]['valueOf']()['length'];
	alert(result); //What is the output of the alert?

	result = [12 + 21]['valueOf']['length'];
	alert(result); //What is the output of the alert? 
</script>

What is the output of each alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The result will be as follows 1 then 0. The first expression (the easy one) will be executed as follows:

var result = [12 + 21]['valueOf']()['length'];

The expression can be read as [33].valueOf().length which means that .length property will print the length of the valueOf() call to array [33] which is 1. Note that the [33].valueOf will return [33].

The second expression is the tricky part:

var result = [12 + 21]['valueOf']['length'];

The expression can be read as follows [33].valueOf.length. This is really completely different from the first expression because in this case the .length property will print the number of arguments of the valueOf method which is zero. This is because if the .length property is attached to a method then it will print the number of arguments of the method.