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 trialKevin Narain
11,379 PointsIs there a way to access the variables from other for loops inside another for loop?
In my, if-statement I want to compare the variables i and j but it doesn't work. Is there a way to access those variables?
for (let i = 0; i < 1000; i += 100) {
console.log(`${i}`);
}
for (let j = 0; j < 100; j += 10) {
console.log(`${j}`);
}
for (let k = 0; k < 10; k++) {
console.log(`${k}`);
if (i == 300 && j == 60 && k == 4) {
console.log('You found the number 364!');
}
}
1 Answer
Simon Coates
8,377 PointsIt might work with something like
let i,j;
for (i = 0; i < 300; i += 100) {
console.log(`${i}`);
}
for (j = 0; j < 60; j += 10) {
console.log(`${j}`);
}
for (let k = 0; k < 10; k++) {
console.log(`${k}`);
if (i == 300 && j == 60 && k == 4) {
console.log('You found the number 364!');
}
}
or
for (var i = 0; i < 300; i += 100) {
console.log(`${i}`);
}
for (var j = 0; j < 60; j += 10) {
console.log(`${j}`);
}
for (let k = 0; k < 10; k++) {
console.log(`${k}`);
if (i == 300 && j == 60 && k == 4) {
console.log('You found the number 364!');
}
}
Let and const variable declaration are different to the old style (var uses something called hoisting). So with the above, the variables are still in scope.