How do the semicolons work in the for loop? - javascript

I am writing a function that raises a value to another value without using the exponent operator. I understand the syntax of these kinds of loops as being that initialised values go before the first semicolon, a condition goes between the first and the second semicolon, and after the second semicolon is the looping operations.
I am confused because I think this code should be broken, but it appears to return the correct value. When I put result *= base after count++ inside the parenthesis, then the code does not return the correct value. Why is this?
//Power function
function power(base, exponent) {
var result = 1
var count = 0
for (; count < exponent; count++)
result *= base
return result;
}
print(power(5, 2));

The blank ; just acts as a placeholder in this case. Because you declared count = 0 above this for loop, this ; is just there so that declaration isn't overwritten:
var count = 0;
for(/*var count=0*/; count < 4; count++){
document.write(count);
}
P.S. I commented out var count = 0 because that is essentially what the code is representing (because you called that earlier).

It is possible to do what you want in javascript. I think the only problem is that you didn't use brackets. This will work.
//Power function
function power(base, exponent){
var result = 1;
var count = 0;
for (; count < exponent; count++, result *= base) {}
return result;
}
document.write(power(5, 2));
//returns 25
But this won't because even if you don't indent return, it will be executed in the for loop and return during the first iteration. I ran in this issue when I tried your code snipplet so I think it is your issue :
//Power function
function power(base, exponent){
var result = 1;
var count = 0;
for (; count < exponent; count++, result *= base) //notice the missing brackets
return result;
}
document.write(power(5, 2));
//returns 25

Related

Multiplication Loop not multiplying

Trying to loop the arguments entered and return the arguments as the total multiplication:
let lightCode = { //Creates Object.
Multiply: function() { //Multiplys all arguments.
const total = 0;
for(const i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
total *= arguments[i];
}
return total;
}
}
lightCode.Multiply(12, 16)
You have two problems, one of which is that you can not reassign a value to a constant. Second you're setting total = 0 first. By doing that you'll be multiplying everything by 0.
So in order to solve your problem you need a if conditional to check if total is 0, if is 0 you assign the property total to the argument in the loop, if not you multiply it.
let lightCode = { //Creates Object.
Multiply: function() { //Multiplys all arguments.
let total = 0;
for(let i = 0; i < arguments.length; i++) {
if(total === 0) total = parseFloat(arguments[i]);
else total *= parseFloat(arguments[i]);
}
return total;
}
}
console.log(lightCode.Multiply(12, 16));
I recommend you to read about const, let, var and when to use them. There are (at least) two mistakes in your code:
const total = 0 => since total is declared using the const identifier, it means that its value is going to be constant during your program. And what does constant mean? That it stays the same. But the line total *= arguments[i]; wants to change it, resulting into an error. Also, initializing the total with 0 makes the final results to be 0 (remember that the multiplication identity element is 1).
const i = 0 => same thing; i++ wants to increment the value of i, but you declared it as const.
Running your code and opening the console you can clearly say an error message: "Uncaught TypeError: Assignment to constant variable.".
Cheers!
let lightCode = {
Multiply: function() {
var total = 1;
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
total *= arguments[i];
}
return total;
}
}
lightCode.Multiply(12, 16)
As pointed in the comments, there is more than one error in the code, first you are assigning the variables as const which is not correct in this case, the rule of thumb is to use let every time you need to reassign a variable (meaning, when you need to use the =symbol again), otherwise use const. Also as pointed in the comments you should not initialize the variable with zero, otherwise the loop will always return zero.
Here is a working snippet:
const lightCode = { //Creates Object.
Multiply: function() { //Multiplys all arguments.
let total = 1; // can not be zero, otherwise the loop will always return zero
for(let i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
total *= arguments[i];
}
return total;
}
}
lightCode.Multiply(12, 16)
Notice how I am using const for the lightCode variable, because this object is never reassigned (meaning, you won't use the = to assign a new value again) and instead for total I'm using let, because is reassigned on every loop interaction.

Getting a NaN error in Javascript Add function

Getting a NaN error in this addition function for script code, although there is no type conversion from string to int: Any suggestions?
var add = function(a, b) {
var i = 0,
sum = 0;
for (i = 0; i <= arguments.length; i++) {
sum += arguments[i];
}
return sum;
};
console.log(add(10, 20, 30, 40, 50));
For loop condition part should be i < arguments.length
arguments.length[arguments.length] will be undefined
In the last iteration of the for loop, code was trying to add 150 + undefined which resulted in NaN
Best way to figure out these type of problems is by debugging
Following are some debugging method
Use console statements and check what is happening
Use a debuggers and check line by line what is happening in your code
I personally use node debugger.
You check line by line what is happening in your code and check values
of variable on the fly
Following is working code
var add = function (a,b) {
var i = 0,
sum = 0;
for (i = 0 ; i < arguments.length ; i ++) {
sum += arguments[i];
}
return sum;
};
console.log(add(10,20,30,40,50));
You are setting the for loop's condition field incorrectly.
It should be:
(i = 0; i < arguments.length; i++)
(Notice the use of < instead of <=)
The problem is that you tried to add arguments[5] (because the length is 5, but arrays start at 0) which is undefined.
Number + undefined = NaN

Javascript Averages

I am trying to learn Javascript. I've built the following code to find the average from an array of numbers. It works except the last returned value is always NaN. I cannot figure out why. If I move this piece outside of the block it seems to forget altogether what the variable sum is supposed to be equal to. Is there some kind of global-variable type equivalent I'm supposed to be using for JS?
var average = function(myarray) {
sum = 0;
for (counter = 0; counter <= myarray.length; counter++) {
sum = sum + myarray[counter];
average = sum / myarray.length;
console.log(average);
};
}
average([1, 2, 3])
Change
counter <= myarray.length
to
counter < myarray.length
because indexes start at 0.
Full example:
var average = function(myarray) {
var sum = 0;
for (var counter = 0; counter < myarray.length; counter++) {
sum += myarray[counter];
}
return sum / myarray.length;
}
console.log(average([1,2,3]));
JSBin Demo: http://jsbin.com/siyugi/1/edit
myarray[myarray.length] is undefined, which intoxicates your computation with NaN(Not A Number).
Just change it to
for(counter = 0; counter < myarray.length; counter ++) {
// ...
}
Since you are just learning you should know it is good practice to not use .length in a for loop like that. It causes the code to have to check the length of your array on each loop. And remember that .length is returning the number of elements in the array; but array index starts at 0.
for(var counter = 0, length = myarray.length; counter < length; counter++){
}
Would be the proper way to do it.
Don't use variables without declaring them with var keyword, otherwise they will become global properties.
The JavaScript Arrays are zero index based arrays. So, if the size of the array is 3, then the first element will be accessed with 0 and the last with 2. JavaScript is very forgiving, so when you access an element at an invalid index in the array, it will simply return undefined.
In the iteration, you are replacing the current function object with the average value. So, subsequent calls to average will fail, since average is not a function object any more.
It is a good practice to have a function return the computed value, instead of printing the value, so that it will not violate the Single Responsibility Principle.
In your case,
for (counter = 0; counter <= myarray.length; counter++) {
The counter runs till the last index of the array + 1. Since it returns undefined in the last iteration, JavaScript returns NaN in the arithmetic operation.
console.log(1 + undefined);
# NaN
So, you need to change the code, like this
function Average(myarray) {
var sum = 0, counter;
for (counter = 0; counter < myarray.length; counter++) {
sum = sum + myarray[counter];
}
return sum / myarray.length;
}
If you are interested, you can compute the sum with Array.prototype.forEach, like this
function Average(myarray) {
var sum = 0;
myarray.forEach(function(currentNumber) {
sum += currentNumber;
});
return sum / myarray.length;
}
Even better, you can calculate the sum with Array.prototype.reduce, like this
function Average(myarray) {
return myarray.reduce(function(sum, currentNumber) {
return sum + currentNumber;
}, 0) / myarray.length;
}
You can calculate the average of an array of numbers as follows:
var avg = c => c.reduce((a,b) => a +b) / c.length;
avg([1,2,3])

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.

calculating average using for loop in javascript

function averageCalculator (numvalues) {
for(i=0, i <= numvalues, i++>) {
var score = prompt("input the score")
result1 += score;
}
alert(result1 / 3);
}
this function is later triggered by a button with onclick="averageCalculator (2)
<input type="button" value="Click for the average" onclick="averageCalculator (2)">
any ideas why its not working? it should prompt you for 2 values and then alert you with the average. not sure whats wrong.
Your code has multiple issues. The for loop is not well formatted and you need to terminate statements with a semi-colon. Also you need to declare variables. And your loop will run numvalues+1 times which is why i removed the = in your loop. Also if you want to calculate an average you want to divide by numvalues.
function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {
var score = prompt("input the score");
result1 += score;
}
alert(result1 / numvalues);
}
On top of the invalid syntax you will run into a common "problem" with javascript here. The inputs are treated as strings and instead of being added they will be concatenated. Providing 2 and 2 as scores will result in 11. 2 concatenated with 2 = 22 / 2 = 11. You need to cast the value to a number explicitly before adding them together:
function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {
var score = prompt("input the score");
result1 += Number(score);
}
alert(result1 / numvalues);
}
Above code will correctly return 2
The syntax of your for-loop is wrong:
for(i=0, i <= numvalues, i++>) {
should be
for(i=0; i <= numvalues; i++) {
Tip: Also, it's better to use
for(var i=0; i <= numvalues; i++) {
since then i will be a local variable instead of a global one.
Try like this
for(var i=0; i <= numvalues; i++){}
An alternative solution (using a functional programming libary, like Underscore.js):
function averageCalculator(numValues) {
var numbers = _.map(_.range(numValues), function(element) {
return +prompt('input the score');
});
var result = _.reduce(numbers, function(memo, number) {
return memo + number;
}, memo);
alert(result / 3);
}
While a little bit more complicated (and less efficient), you'll get rid of loops altogether.
EDIT
The +prompt('input the score') does effectivly the same as Number(prompt('input the score')).

Categories

Resources