-1

Hello I'm new to JS and object-oriented programming in general. I have two questions considering this

let arr = [1,2,3]
let a = 'hi'

When I run typeof(), arr is 'object' and a is 'string' right?

So my question is ,

  1. When using arr.length to get the length of the array, what's the principle behind it? To be specific, I don't understand how I could get the length property though I've never initialized it. Does JS automatically set a length property value when we generate an object? How does it work?

  2. Doesn't property only exist in objects? But why can we get the length of variable a using a.length? I thought objectname.property thing was for objects.

Hanrabong
  • 35
  • 4
  • Please read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length – Nitheesh Feb 09 '22 at 03:28
  • The linked question is for your second question. To the first question: please familiarize yourself with the fundamentals of [OOP](//en.wikipedia.org/wiki/Object-oriented_programming), and how they relate to JS. See [Property accessors](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). – Sebastian Simon Feb 09 '22 at 03:36

1 Answers1

0

When you declare [1,2,...] you are declaring an object of class Array, which, in it's prototype, has a "length" property. Think of it as a variable that gets updated when you add or remove elements from the array.

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/length Strings are also objects in Javascript, and a string is also considered an array of characters, thus having the "length" property as well.

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

Aleksandrus
  • 1,589
  • 2
  • 19
  • 31