Question

Looking at the spec, the following behavior doesn't seem to be defined clearly :

var array = new Uint8Array( 1 );
var result = ( array[ 0 ] = 0x100 );

// Is result === 0x100 or 0 ?

Chrome is returning 0x100 instead of 0, but can I trust this result to be consistent ?

Was it helpful?

Solution

What you are doing here:

var result = ( array[ 0 ] = 0x100 );

is actually the same (a short-hand) as setting both array and result with the same value at the same time (the parenthesis does not matter as 0x100 is the one being evaluated and passed to result):

var result = array[ 0 ] = 0x100;

or expanded:

array[ 0 ] = 0x100;
var result = 0x100;

so obviously result would in this case be 0x100 (256).

But the content of the array is 0 as you can see if you log it directly:

console.log(array[ 0 ]);

(if you used Uint8ClampedArray instead the value would be 0xff or 255).

Fiddle

So in that case the result will be consistent but by-passing the array in relation to the result variable and the value set. Array will be set too, but the value is fit to the unsigned byte range while the value is as-is for the result var.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top