Skip to main content

Buffer vs array

1. How to create a new Buffer

Node.js offers several ways to create a buffer:

Buffer.from()

Creates a buffer from existing data (a string, an array of bytes, another buffer):

javascript
const buf1 = Buffer.from('Hello', 'utf8'); // from a string const buf2 = Buffer.from([72, 101, 108, 108, 111]); // from an array of numbers

Buffer.alloc(size)

Creates a new buffer of a given size, filled with zeros:

javascript
const buf3 = Buffer.alloc(10); // 10 bytes, all 0

The safe option, it clears the memory before use.

Buffer.allocUnsafe(size)

Creates a buffer of the given size, but without zeroing the memory (it may contain "garbage" left over from previous data):

javascript
const buf4 = Buffer.allocUnsafe(10);

Used when maximum speed matters, and you're certain you'll write every byte manually.

Buffer.concat(list)

Joins several buffers into one:

javascript
const part1 = Buffer.from('Hello '); const part2 = Buffer.from('World'); const buf = Buffer.concat([part1, part2]); console.log(buf.toString()); // "Hello World"

2. How Buffer differs from a regular array

CriterionBufferArray
Data typeStores bytes (numbers 0-255)Can store any value (numbers, strings, objects, etc.)
SizeFixed, its length can't change after creationDynamic, elements can be added and removed
PerformanceRuns at the C++ level, very fast for binary operationsSlower, since it's implemented at the JS level
PurposeFor binary data (files, network, streams)For logical data and structures in JS
MemoryLives in unmanaged memory (outside the V8 heap)Lives in V8's managed memory
EncodingSupports reading/writing strings in different encodings (utf8, hex, base64)Has no direct encoding support
MethodsHas low-level methods (readUInt8, writeUInt16LE, slice, toString)Regular array methods (map, forEach, push)

An example of the differences:

javascript
const arr = [72, 101, 108, 108, 111]; const buf = Buffer.from(arr); console.log(arr); // [72, 101, 108, 108, 111] console.log(buf); // <Buffer 48 65 6c 6c 6f> console.log(arr.map(x => String.fromCharCode(x)).join('')); // "Hello" console.log(buf.toString('utf8')); // "Hello"

Both hold the same numbers, but Buffer is optimized for working with bytes, while Array is for logic at the JS level.

Summary

Buffer is a special type for storing and processing binary data, created via Buffer.from(), Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.concat().

It differs from a regular array in that it:

  • stores only bytes (0-255),
  • has a fixed size,
  • runs faster and closer to the hardware,
  • is used in every I/O operation in Node.js.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.