javascript - looping a triangle with a while loop -
i reading eloquent javascript book. there task build triangle this:
# ## ### #### ##### ###### #######
with loop.
i did loop.
for (var result = "#"; result.length <=7; result = result + "#") console.log(result);
but reason can't while loop.
var result = "#" while(result.length <=7 ){ console.log(result); result = result + "#"; } vm920:3 # vm920:3 ## vm920:3 ### vm920:3 #### vm920:3 ##### vm920:3 ###### vm920:3 ####### "########"
for reason getting line @ bottom 8 # symbols wrapped in quotes. why happening?
it's result of final expression in code. type in "5+5" in js console , you'll result. if put "5+5" @ end of script, same thing. that's what's happening here:
var result = "#" while(result.length <=7 ){ console.log(result); result = result + "#"; // <-- last statement executed, returned }
in contrast, last statement below logging statement, has no return value. result of script undefined
.
for (var result = "#"; result.length <=7; result = result + "#") console.log(result);
you can see more if try this:
for (var i=0; < 5; i++) { console.log(i); }
here, last expression i
. code prints each number 0-4 inclusive, prints 4 second time because final expression.
0 1 2 3 4 <-- final console.log() call 4 <-- final expression
Comments
Post a Comment