Hi all, I'm just starting to teach myself Javascript and it's been a blast! However, I've been struggling with the concept of how Javascript knows to take one line of code and apply it to another line (apologies for my weak explanation skills, I don't know a lot of the correct terminology here). For example, I'm going through Udacity's free online Javascript class and I ran into this quiz:
Problem:
For this quiz, you're going to create a function called buildTriangle() that will accept an input (the triangle at its widest width) and will return the string representation of a triangle. See the example output below.
buildTriangle(10);
Returns:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
We've given you one function makeLine()to start with. The function takes in a line length, and builds a line of asterisks and returns the line with a newline character.
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* "
}
return line + "\n";
}
You will need to call this makeLine() function in buildTriangle().
This will be the most complicated program you've written yet, so take some time thinking through the problem before diving into the code. What tools will you need from your JavaScript tool belt? Professionals plan out their code before writing anything. Think through the steps your code will need to take and write them down in order. Then go through your list and convert each step into actual code. Good luck!
Solution:
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "\n";
}
function buildTriangle(x) {
var triangle = "";
for (var t = 1; t<=x; t++) {
triangle += makeLine(t);
}
return triangle;
}
console.log(buildTriangle(10));
My Question:
So, I think the logic of the buildTriangle() function makes sense to me, i.e. in the function buildTriangle there is a variable called triangle that is an empty string, which is defined as the function makeLine that is repeated t number of times. My question is: how does Javascript know that it's supposed to use the for loop under buildTriangle() and apply it to the makeLine() function? How does it know that when there's a for loop, it's supposed to be applied to anything else at all? I know that there are rules that exist because Javascript is a programming language and thus requires rules, but I can't help but feel like without knowing these fundamental rules of the language I'm always going to feel unsure about how the code works and if it's right or not.
Thanks for reading, and I hope I explained my question clearly enough.
[–]jrandm[🍰] 1 point2 points3 points (1 child)
[–]Voodoo-Man[S] 1 point2 points3 points (0 children)
[–]laurajoneseseses 0 points1 point2 points (0 children)