The last challenge of Bytewiser: Array Buffers

The challenge is like that:

Array Buffers are the backend for Typed Arrays. Whereas Buffer in node is both the raw bytes as well as the encoding/view, Array Buffers are only raw bytes and you have to create a Typed Array on top of an Array Buffer in order to access the data.

When you create a new Typed Array and don't give it an Array Buffer to be a view on top of it will create it's own new Array Buffer instead.

For this challenge, take the integer from process.argv[2] and write it as the first element in a single element Uint32Array. Then create a Uint16Array from the Array Buffer of the Uint32Array and log out to the console the JSON stringified version of the Uint16Array.

Bonus: try to explain the relevance of the integer from process.argv[2], or explain why the Uint16Array has the particular values that it does.

The solution given by the author is like that:

var num = +process.argv[2]
var ui32 = new Uint32Array(1)
ui32[0] = num
var ui16 = new Uint16Array(ui32.buffer)
console.log(JSON.stringify(ui16))

I don't understand what does the plus sign in the first line means? And I can't understand the logic of this block of code either.

Thank you a lot if you can solve my puzzle.

Typed arrays are often used in context of asm.js, a strongly typed subset of JavaScript that is highly optimisable. "strongly typed" and "subset of JavaScript" are contradictory requirements, since JavaScript does not natively distinguish integers and floats, and has no way to declare them. Thus, asm.js adopts the convention that the following no-ops on integers and floats respectively serve as declarations and casts:

  • n|0 is n for every integer
  • +n is n for every float

Thus,

var num = +process.argv[2]

would be the equivalent of the following line in C or Java:

float num = process.argv[2]

declaring a floating point variable num.

It is puzzling though, I would have expected the following, given the requirement for integers:

var num = (process.argv[2])|0

Even in normal JavaScript though they can have uses, because they will also convert string representations of integers or floats respectively into numbers.