Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript DOM Scripting By Example Improving the Application Code Refactor 2: Readable Branching Logic

I don't understand how to use the '[]' and when to use it.

Can somebody please explain this to me please? Thank You

Jeff Muday
Jeff Muday
Treehouse Moderator 28,722 Points

The '[]' connotes an empty list (or array) in JavaScript. It is usually used to initialize an array but can be used anytime you need to start a empty (blank) array or reset an list.

let myArray = [];

2 Answers

Hi Jonathan!

[] just initializes an empty array.

Like this:

let myArr = [];

And then you can add elements like this:

myArr.push('itemOne');
myArr.psuh('itemTwo');
myArr.push('itemThree');

You can also do it this way:

var myArr = new Array();

And there are pros/cons of each approach.

This explains in way more detail than I ever could:

https://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar

I hope that helps.

Stay safe and happy coding!

Grace Marsh
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Grace Marsh
Front End Web Development Techdegree Graduate 16,665 Points

Hi Jonathan,

In addition to being used for arrays, I thought that perhaps this excerpt from a Treehouse question may assist you with how square brackets are used: Given this code:

 function createElement( elementName, property, value ){
     const element = document.createElement(elementName);   
     element[property] = value;
}

The brackets dynamically access the property of element using the string contained in property.