Is an array an object, or a variable, or both?

Hello,

I’m trying to get a better handle on some basic definitions in JavaScript. I’m wondering about how to properly define an array. I’ve seen it defined differently on different sites. For example:

An array, “stores multiple values and elements in one variable.”

let array = ["John Doe", 24, true];

vs

An array, “is an object that can store multiple values at once.”

const words = ['hello', 'world', 'welcome'];

Obviously both definitions equate to the same thing pretty much. Depending on the context of the code, can a variable be an object and an object be a variable?

Picture 100 gifts stacked in the middle of a room, the whole thing would be the array and individual packages are the objects. I know this gets a little confusing at times because a true object in JavaScript is is similar to your example and this just one subject, the list goes on when arguments and parameters are used as the same thing when there not at all. By definition let is the keyword, array is the variable and the rest is an array with three objects inside. Good Luck

Thanks for your reply,

I guess I’m still a little confused as to whether something can be a variable, and an object simultaneously. Take these two lines of code for example:

var str = "HELLO"
var str1 = str.toLowerCase()

So I’ve declared the variable str and assigned it a value of HELLO. In the second line, I declare another variable and assign it a value of using the toLowerCase() method to make the str variable all lower case if that makes sense. But I thought a method could only be used on an object. So is str a variable in the first line of code, but becomes an object in the second line?

str is a variable. It stores something. You’ve assigned it the string HELLO so it becomes a string object, and you can use those methods.

You could store an array in that variable, which is also an object, an array object.

let array = ["John Doe", 24, true];

array is a variable here, and it’s assigned an array, a group or a list of elements. If it was all numbers you could say values. Now, it’s an array object, stored and accessed by the variable array.

So an array is an object, not a variable (both in this case it’s confusing because the name of the variable is array). A variable is the name you access the object by.

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

I would say most things in JS are objects, which means they have properties and methods. This might be more clear: https://www.freecodecamp.org/news/how-javascript-implements-oop/

This is often called “Boxing” (you have unboxing as well).

https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/types-grammar/ch3.md#automatic-objects

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.