Let us clarify something first: There is no concept of "values" at the syntax level. You can write
Obj1.age = 29;
no matter what the actual value of Obj1
is. Of course whether or not the assignment will work at runtime will depend on the actual value. But syntactically this code is correct.
The reason we only use bracket notation (arr[0] = 42
) when dealing with arrays is not because the value is an array but because this is the only valid syntax when using numbers as property names. The actual value of arr
is irrelevant.
Here I'm using an object, but dot notation is still invalid:
var obj = {};
obj.0 = 42;
Bracket notation works:
obj[0] = 42;
See: JavaScript property access: dot notation vs. brackets? for more info.
However, because arrays are just objects, you can assign/access any other property to an array. E.g. a common way to "truncate" an array is to assign a new value to .length
:
var arr = [1, 2, 3];
arr.length = 0;
console.log(arr);
Aside from syntax, objects and arrays have a couple of methods to mutate properties:
You can use Object.defineProperty
on any object:
var arr = [];
Object.defineProperty(arr, 0, {value: 42, enumerable: true, configurable: true});
console.log(arr);
Arrays specifically also have the following mutation methods: copyWithin
, push
, pop
, splice
, unshift
.