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.
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.
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.