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 trialCarmen Chow
Full Stack JavaScript Techdegree Student 578 PointsWhat is the reason for assigning an empty string to a variable?
Hello,
Can someone help me understand why and when you would initialize a variable to an empty string? I have come across this happening twice in the first JS unit. Here are the examples: Why is "let items = ''???"
Music Playlist
function createListItems(arr) {
let items = '';
for (let i = 0; i < arr.length; i++) {
items += <li>${arr[i]}</li>
;
}
return items;
Pets Directory
function createListItems(arr) {
let items = '';
for (let i = 0; i < arr.length; i++) {
items += <li>${arr[i]}</li>
;
}
return items;
1 Answer
martinjones1
Front End Web Development Techdegree Graduate 44,824 PointsIf you do not set the value of the variable, then it will have the value undefined
;
Compare the two results below, this should help show the reason for setting the value to be an empty string;
Value set
const arr = [1, 2, 3];
let items = '';
for (let i = 0; i < arr.length; i++) {
items += `<li>${arr[i]}</li>`;
}
// items = '<li>1</li><li>2</li><li>3</li>'
Value not set
const arr = [1, 2, 3];
let items;
for (let i = 0; i < arr.length; i++) {
items += `<li>${arr[i]}</li>`;
}
// items = 'undefined<li>1</li><li>2</li><li>3</li>'