+ 1

Assign and use javascript property and keyword as a variable

Suppose, a = "aaa" l = length a.length //gives 3 a.l //gives undefined but, c = console.log c(a) //gives aaa How can I do this for .length property also?

2nd Jan 2021, 5:29 PM
Bibek Oli
Bibek Oli - avatar
4 ответов
+ 2
You can destructure the length property: var a = "aaa" var { length: l } = a; console.log(l); // 3 But the value is not dynamically linked: a += "aa"; console.log(l); // 3 You need to refresh its value: ({ length: l } = a; console.log(l); // 5 ... Anyway, you could access dynamically and simply by doing: var a = "aaa", b = "bbbbb"; var l = "length"; console.log(a[l]); // 3 console.log(b[l]); // 5 a += b; console.log(a[l]); // 8 Obviously, you could also define a getter on the String prototype as an alias of the original length property, but it's widely unadvised to alter builtin prototype...
3rd Jan 2021, 4:44 AM
visph
visph - avatar
+ 1
You can do : const l = a.length
2nd Jan 2021, 5:33 PM
Med Amine Fh
Med Amine Fh - avatar
+ 1
Med Amine Fh but I have lot of strings to use .length.. So, I want to do this to reduce code size.
2nd Jan 2021, 5:42 PM
Bibek Oli
Bibek Oli - avatar
+ 1
Create a function that returns or console log the length like so : function len(x){ //console.log(x.length) return x.length } and you can store the returned value like so : const lengthA = len(a)
2nd Jan 2021, 5:54 PM
Med Amine Fh
Med Amine Fh - avatar