How do i loop a function - javascript

I am learning javascript at the moment and i want to ask you about an exercise that i'm trying to finish. This is the quiz i should finish:
https://classroom.udacity.com/courses/ud803/lessons/a7c5b540-51a6-44dc-b2f2-515c9dd6ca4f/concepts/c746623a-eefd-4518-9890-2c5f320b0282
and here is my code. I just dont understand what im doing wrong . can someone explain me.
<html>
<head></head>
<body>
<script>
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "\n";
}
function buildTriangle(widest) {
var x = makeLine(1);
while(x <= widest){
return x;
x++;
}
}
document.write(buildTriangle(10));
</script>
</body>
</html>
I would like to know what i did wrong and how i can fix it, because i always get either "undefined" or nothing at all.
Also i know it's probably a simple mistake but i'm still a beginner so.

after a return statement, any instruction never executed

You have a few issues in function buildTriangle(widest).
var x = makeLine(1);
This will always set x to makeLine(1) doing x++ in the while loop will do nothing.
Further more the x++ is after a return statement so the code will never reach it.
Hope this helps a little.

It's how you actually write the * on your document. I've modified how your buildTriangle works and kept makeLine intact.
(function() {
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "<br/>";
}
function buildTriangle(widest) {
for(var x = 1; x <= widest; x++){
// Moved write inside the loop
// since you want to write each line here
document.write(makeLine(x));
}
}
buildTriangle(10);
})();
<html>
<head></head>
<body>
</body>
</html>

change your function to this
function buildTriangle(widest) {
var x = makeLine(1);
while(x <= widest){
// putting return here would make function execution to stop
// and return the value to the callee, thus not executing
// any statement after this.
x++;//this making this an unreachable code
}
return x;
}

You're almost there.
For the makeline() function, just remove \n so it looks like this:
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line
}
For buildTriange() you have a few issues: 1) var x = makeLine(1); means that x will always be equal to *, because that is was makeLine(1) will return; 2) the return statement makes x++ unreachable.
Consider this:
function buildTriangle(widest) {
var output = '';
var x = 1;
while(x <= widest){
output += makeLine(x) + '<br>';
x++
}
Now, it build an output. The x variable is a counter. While x is 1 it will add to the output the result of makeLine(1) + '<br>', then it will increase by 1 and run again until the value of x is the same as widest. Then it will return output.
Since document.write() writes html and not plain text. You have to use the line break, not a newline.

Related

Why does continue; statement freeze browser?

I'm making a small script that will iterate the numbers and skip the number 5. I want to achieve this with continue; statement/label.
Here is my code:
<p id="test"></p>
<script>
var i, text;
text = "";
i = 0;
for (;i<8;) {
if (i === 5) {continue;}
text += "The number is " + i + "<br>";
i++;
}
document.getElementById('test').innerHTML = text;
</script>
I'm failing to see any typo error, but coding for more than 12 hours now, maybe I'm overseeing something obvious. If so, I apologize.
This works when I want to stop at number 5 using break; statement.
<p id="test"></p>
<script>
var i, text;
i = 0;
text = "";
for (;i<8;) {
if (i === 5) {break;}
text += "The number is " + i "<br>";
i++;
}
document.getElementById('test').innerHTML = text;
</script>
if (i === 5) {continue;}
will never allow the control to go ahead and increment the i. Thus, it'll always go back when i becomes five.
Solution:
if (i === 5) {
i++; // Increament `i` first
continue;
}
OR, using for third argument.
for (; i<8; i++) {
^^^ // Increment `i` for each iteration
One more simple thing can be done using if condition.
for (; i < 8; i++) {
// If i is not 5, then only append to the string.
if (i !== 5) {
text += "The number is " + i + "<br>";
}
}
This is causing an infinite loop as your value is never being incremented. continue will move onto the next iteration, however since you haven't defined a statement to increment your value, this never occurs.
Consider refactoring your loop as follows as opposed to performing your incrementation within the body of the loop:
<script>
var text = "";
// This is the most common approach to defining a for-loop as it handles defining
// your iterator, defining a stop condition and handles how to increment your value
// after each iteration
for (var i = 0; i < 8; i++) {
if (i === 5) {break;}
text += "The number is " + i "<br>";
}
document.getElementById('test').innerHTML = text;
</script>
if (i === 5) {continue;}
When i is 5 it never gets a chance again to reach i++. So, i will ever be 5 and you will never exit the loop.

Getting 'undefined', can't figure out why

Working my way through 'Eloquent Javascript' and I'm hitting a bit of a roadblock in understanding how to properly use if with for statements in the language. I'm supposed to write a function that counts all instances of the uppercase 'B' in a given string. The code I've written thus far:
function countBs(s) {
var counter = 0;
for (i = 0; i < s.length; i++) {
if ('B' == s.charAt(i)) {}
counter += 1;
}
}
console.log(countBs("BBC"));
expected output: 2
actual output: undefined
Is my loop going wrong, or my 'if'?
You have two bugs
You are incrementing your counter outside of the if statement.
You have no return statement.
The following can be used:
function countBs(s){
var counter = 0;
for(i = 0; i < s.length; i++){
if ('B' == s.charAt(i)) {
counter += 1; // this needs to be inside the if statement
}
}
return counter;
}
Your function does not have a return statement.
A few issues.
function countBs(s) {
var counter = 0;
for (i = 0; i < s.length; i++) {
if ('B' == s.charAt(i)) {
++counter;
}
}
return counter;
}
document.write(countBs("BBC"));
You were not returning counter at the end of the function
Your if statement was opened, then immediately closed, so nothing happens if the character was B
Even if you returned counter and fixed the above 2 errors, the function still would have exited after 1 B was found. To fix this, move the return after the for ends.
If you're interested, the same problem can be solved with this one-liner:
function countBs(s) {
return s.match(/B/g).length;
}
document.write(countBs("BBC"));
Which finds all B characters (case-sensitive), puts them into an array, then returns how many items are in that array.

Javascript keep getting undefined after function - prompt

So I`m working ona simple JS code. We just started to learn about functions.
I need to make a function named "printStars".
I need to take a number from the user and accourding that number print "*".
This is what I did:
<script>
function printStars()
{
var n = Number(prompt("Insert number of stars:","0.."));
for (i = 0; i < n; i++)
{
document.write("*");
}
}
var stars = printStars();
document.write(stars);
</script>
In the end I get my result with a minus of getting "undefined".
I would love to get some help, and an explanation why is keep happening.
Thanks guys!
jsfiddle demo
function printStars(){
var n = prompt("Insert number of stars:","0..");
var stars='';
for (i = 0; i < n; i++){
stars+='*';
}
$('body').html(stars) //jsfiddle does not allow document.write()
//document.write(stars);
}
//call the function
printStars();
You don't need this
document.write(stars);
You just need this:
// This will make you function to be evaluated and
// the code in your function will be executed.
printStars();
function printStars()
{
var n = Number(prompt("Insert number of stars:","0.."));
for (i = 0; i < n; i++)
{
document.write("*");
}
}
printStars();

For loop in Javascript runs only once

Here is my code. I do not quite understand why the for loop runs only once, both inner and outer. nodeList.length and innerNodeList.length show appropriate values when I generate alert messages. I see that both i and j do not increment beyond 0. Kindly point out anything wrong with the code.
function getCategoryElements() {
var newCategoryDiv = document.getElementById("category");
var nodeList = newCategoryDiv.childNodes;
for (var i = 0; i < nodeList.length; ++i) {
var innerNodeList = nodeList[i].childNodes;
alert("innerNodeList Length" + innerNodeList.length.toString());
for (var j = 0; j < innerNodeList.length; ++j) {
if (innerNodeList[j].nodeName == "SELECT") {
alert("inside select Node value " + innerNodeList[j].nodeValue.toString());
document.getElementById("newCategories").value =
document.getElementById("newCategories").value + '<%=delimiter%>' + innerNodeList[j].nodeValue;
} else if (innerNodeList[j].nodeName == "TEXTAREA") {
document.getElementById("newCategoriesData").value =
document.getElementById("newCategoriesData").value + '<%=delimiter%>' + innerNodeList[j].nodeValue;
}
}
}
}
var newCategoryDiv, nodeList, innerNodeList, innerNode, i, j;
newCategoryDiv = document.getElementById("category");
nodeList = newCategoryDiv.childNodes;
for (i = 0; i < nodeList.length; ++i) {
innerNodeList = nodeList[i].childNodes;
alert("innerNodeList Length" + innerNodeList.length.toString());
for (j = 0; j < innerNodeList.length; ++j) {
innerNode = innerNodeList[j];
if (innerNode.nodeName === "SELECT") {
alert("inside select Node value " + innerNode.nodeValue.toString());
document.getElementById("newCategories").value += '<%=delimiter%>' + innerNode.nodeValue;
} else if (innerNode.nodeName === "TEXTAREA") {
document.getElementById("newCategoriesData").value += '<%=delimiter%>' + innerNode.nodeValue;
}
// Will this work?
alert('Does this alert appear');
}
}
I took the liberty to refactor your code and clean it up a little bit. In case you're not aware, all variables have function scope in Javascript, so no matter where you declare them within a single function, Javascript treats them as if the variable declaration is the first statement.
It appears that your code is syntactically correct, and so I think that the most logical place to look for a problem is that there could be an error occurring after the last alert function call.
In order to check this, try adding another alert function call to the end of the inner loop. If it doesn't run, you'll know this is the case.

Recursion, Sigma Notation (html/javascript)

my objective is to use recursion to get sigma notation working. top limit is n(input variable) bottom limit is i=1, and the function is (-i)^(i-1). i got it working with iteration but i cant get the recursion to work.
<!DOCTYPE html>
<head><title>Recursion</title></head>
<body>
<h1>Recursion</h1>
<script = "text/javascript">
var num
var i;
var n;
var total;
total = 0;
i=0;
var b;
b=0;
function formula(n)
{
(Math.pow((-i),(i-1)))
}
function recursion(n)
{
i=i+1;
if ((n-i) == 0)
{
document.writeln("done");
}
else
{
total = total + recursion(formula(n-i));
return total;
//total = total + (Math.pow((-i),(i-1)) + recursion(n-i));
}
}
num = window.prompt("pick a number");
recursion(num);
document.writeln(recursion(num));
//document.writeln(total);
</script>
</body>
</html>
Please avoid any global variables, that makes it very hard to read. Also, indent your code properly; and don't mix the output (document.write) into the computation. If you don't understand the recursion, just use a loop:
var total = 0;
for (var i=1; i<=n; i++)
total += formula(i);
return total; // the result
The same thing, done with recursion:
function sumFormulaUpTo (n) {
if (n <= 0) // the abort condition
return 0;
else
return sumFormulaUpTo(n-1) + formula(n);
}
sumFormulaUpTo(100);
You notice: there is no total variable, only the result of the recursively called function is used.
With an end recursion (more like the loop), it would look like this:
function sumFormulaFromTo(total, i, n) {
if ( i > n )
return total;
else {
var newtotal = total + formula(i);
return sumFormulaFromTo(newtotal, i+1, n);
}
}
sumFormulaFromTo(0, 1, 100);
If you had total and n declared statically outside the function, it would look more like yours. Yet, you forgot to return the result once the end condition is met (you just output something, but return undefined), and you somehow called the recursion with the result of formula - no idea where you got that from. This causes an infinite loop, according to #cbayram.

Categories

Resources