Bird
0
0

Why does this code throw an error?

medium📝 Debug Q7 of 15
Node.js - Worker Threads
Why does this code throw an error?
const sab = new SharedArrayBuffer(4);
const int16 = new Int16Array(sab);
int16[2] = 10;
ASharedArrayBuffer cannot be used with Int16Array.
BInt16Array requires 8 bytes minimum.
CIndex 2 is out of bounds for Int16Array of 4 bytes.
Dint16 array must be created with new keyword.
Step-by-Step Solution
Solution:
  1. Step 1: Calculate Int16Array length

    SharedArrayBuffer is 4 bytes; Int16Array uses 2 bytes per element, so length is 2.
  2. Step 2: Check index access

    Index 2 is out of bounds (valid indices: 0 and 1), causing an error.
  3. Final Answer:

    Index 2 is out of bounds for Int16Array of 4 bytes. -> Option C
  4. Quick Check:

    Index bounds error = B [OK]
Quick Trick: Typed array length = buffer size / element byte size [OK]
Common Mistakes:
  • Assuming index 2 is valid
  • Thinking SharedArrayBuffer incompatible
  • Confusing new keyword usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes