1

consider

const a = [1,2,3]
console.log(a[5]) // returns undefined

I am a C and Fortran programmer, and I expected that segfault will take place. How is the memory being managed here ? Node is the environment.

mozpider
  • 366
  • 2
  • 12
  • 3
    because it is not. :) – epascarello Oct 02 '19 at 16:11
  • 3
    Arrays are exotic objects, which are internally often optimized to be actual C arrays. However, at the core, they are objects, so the engine will fallback to object behavior for properties, if needed. It's similar to `({})[5];`. – ASDFGerte Oct 02 '19 at 16:13
  • 1
    https://stackoverflow.com/questions/1510778/are-javascript-arrays-sparse – epascarello Oct 02 '19 at 16:14
  • 2
    As a sidenote: in C, i don't think this code will always produce a segfault. It depends on your memory layout, and permissions of the executed code ;) – ASDFGerte Oct 02 '19 at 16:18
  • Memory management is completely abstracted away in Javascript and as such, it's inconsequential to userland code (apart from maybe some edge cases) and the specifics of it depends on the engine. Node uses the V8 engine. – Lennholm Oct 02 '19 at 16:36

1 Answers1

1

In Javascript a[n] is a number of layers of abstraction that resolve to something resembling:

struct JsType *array_get(struct JsType *a, struct JsType *n) {
  struct JsArray *array = coerceTo(a, TYPE_ARRAY);
  struct JsInt *index = coerce(n, TYPE_INTEGER);
  if (array->length > index || index < 0) {
    return (struct JsType *) JSTYPE_UNDEFINED;
  }
  return array->contents[index->value];
}

Where:
coerceTo is a function that either converts a potentially similar value into a usable value such as a string into an integer (which means you can use stringified integers as array indexes) or returns the value given to it if it already has the type we wanted.
JSTYPE_UNDEFINED is a global constant for Javascript's undefined
struct JsType is a struct from which all types used in Javascript are composed and can be cast to.

0x777C
  • 993
  • 7
  • 21
  • Actually `a[n]` is the same as `o[p]`, the syntax to access any object's property. So on top of the `array_get` there would be an `object_get` that coerces the first operand to an objects, checks its type and what string the other operand can be coerced to, then specialises to `array_get` for array objects. – Bergi Oct 02 '19 at 21:35