Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why an array's length property's value changes even when set as read-only in javascript?

Tags:

javascript

I tried the following code in chrome's console

var a = new Array(1,2,3,4);
a.length

This shows length as 4 as expected. Now I tried setting length property as writable: false

Object.defineProperty(a, "length", {writable: false});
a[4] = 5;
a.length

This results in 5 even though the property is set to writable:false. How did that happen? Shouldn't it have remained the same as it is set to read-only(writable:false)?

like image 257
zzat Avatar asked Jun 06 '13 09:06

zzat


1 Answers

Object.defineProperty(a, "length", {writable: false}); only affect the way you assign the value directly to the .length property.

var a = [1,2,3,4];

Object.defineProperty(a, "length", {writable: false});

a.length = 0;

console.log(a.length); // still be 4
like image 111
xdazz Avatar answered Oct 25 '22 11:10

xdazz