Home > Software design >  Javascript, what happens when we assign value to read-only data property such as string length?
Javascript, what happens when we assign value to read-only data property such as string length?

Time:10-31

Suppose we have a string, length is read-only data property of string. What happen if we unintentionally assign value to length property of string? Why javaScript return those value as a result?

for example if we run this part of code:

var str="test";
console.log(str.length)
console.log(str.length=3)

output should be like this:

4
3

the third line of code returns 3, My question is why assignment in javaScript returns right side of operand not left side of it?

CodePudding user response:

The assignment operator always returns the right-hand value. Hence, passing the expression inside the console.log function returns the right-hand value, in your case 3.

Assigning any value to the length property of a string has no effect.

let myString = "Hello,World!";

myString.length = 4;

console.log(myString);
// expected output: "Hello,World!"

console.log(myString.length);
// expected output: 12

  • Related