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 trialJonathan Guerrero
Front End Web Development Techdegree Graduate 18,245 PointsI don't understand how to use the '[]' and when to use it.
Can somebody please explain this to me please? Thank You
2 Answers
Peter Vann
36,427 PointsHi 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:
I hope that helps.
Stay safe and happy coding!
Grace Marsh
Front End Web Development Techdegree Graduate 16,665 PointsHi 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
.
Jeff Muday
Treehouse Moderator 28,722 PointsJeff Muday
Treehouse Moderator 28,722 PointsThe '[]' 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 = [];