Why am I getting NaN when adding all arguments? - javascript

I am trying to create a function that adds all arguments together. I keep getting NaN. What am I doing wrong?
function sum() {
var n = arguments.length;
var total = 0;
for(var i = 0; i < n; i++) {
// code here
total += n[i];
}
return total;
}
sum(1,2,3,4);

You need to get value from arguments, where n is just a number holds the length of arguments and n[i] will be undefined. Addition with undefined results NaN.
function sum() {
var n = arguments.length;
var total = 0;
for (var i = 0; i < n; i++) {
// code here
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3, 4));

What is n[i]; ? As n should only contain length of arguments array, its not itself an array.
You need to replace total += n[i]; with total += arguments[i];

One of the classic disadvantage of javaScript is about NaN(Not a Number)'s underlying principle is.
NaN(Not equal to anything)-->When it occurs
i)Result of undefined or erroneous operations
ii)Toxic :any arithmetic operations with Nan as input will have NaN as a result.
So in your code:undefined(n[i])+number=NaN
<script>
function sum() {
var n = arguments.length;
var total = 0;
for (var i = 0; i < n; i++) {
// code here
total += arguments[i];
}
return total;//returns 10
}
sum(1, 2, 3, 4);
Hope this helps/serves the purpose

Related

Write a function which returns the sum of the values for each parameter it receives

I want the result to be the sum of every number, but instead, it only sums the first number with the rest. For example if the parameter were : 1,2,3,4,5
it should come out with 15 but instead, it became 3456. Where did i go wrong?
Thank u guys, i m new to this and thing were really complicated :((
function func1(sum) {
var result = '';
var i;
for (i = 1; i < arguments.length; i++) {
result += arguments[i] + sum;
}
return result;
}
Start with result being a number, not a string: var result = 0.
If you're iterating through arguments, you may as well skip the named first argument altogether.
Start iterating from 0, not 1.
function func1() {
var result = 0;
var i;
for (i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
console.log(func1(1, 2, 3, 4, 5));
This should work
function sum(value) {
let result = 0;
for(let i =0; i < value.length; i++) {
result +=value[i];
}
return result
}
let arry = [1,2,3,4,5]
console.log(sum(arry)) //15

How do I divide the sum with 2 after a loop

How do I divide the sum with 2 after a loop, so I get the value 38? I want to print out the answer in an alert box.
My Javascript code:
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
alert(sum);
Or if I have the values 1, 2, 3, 4, I want to get the sum (in this case 10) in the loop and divide it with 2 and print out it in an alert box.
//variable declaration and loop above
alert(sum/2);
You need to divide by 2 then...
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
sum /= 2;
alert(sum);
var nums = ['1','75'];
let sumDiv2 = (nums)=> {
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += Number(nums[i]);
}
return sum
}
alert(sumDiv2(nums)/2);
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
alert(sum/2);
This isn't complex to solve.
Using array reduce method you can do like below
var arr = ["1", "67"];
var divide = arr.reduce(function (acc, ele) {
return acc += +ele; // To convert element from string to array use +
}, 0) / 2;
console.log(divide);
You can do it on 1 line.
var nums = ['1','2', '3', '4'];
var result = nums.reduce((el, acc) => parseInt(el) + parseInt(acc), 0) / 2;
console.log(result);
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
alert(sum/2);
You can try this without any loop. Short, simple and stylish:
var arr=['1', '75'],
sum_2=arr.reduce(function(a,b){return a*1+b*1;},0)/2;
alert(sum_2);
console.log(['1','2'].reduce((p,c) => +p + +c, 0) / 2)
// ^ ^ ^ ^ ^
// | | | | |
// "p" as "previous"_| | |____| |_first "p" value
// | |
// "c" as "current"_| |_convert strings to integers
Run the snippet; what happens:
.reduce() starts on the ['1','2']
In the first call to the inner function ((p,c) => +p + +c) the value of p(revious) is 0, as the second argument passed to the .reduce(), and value of the c(urrent) is '1', the first array element; the 0 + +'1' executes, resulting in 1
In the second call to the inner function the value of p is 1 - from previous execution, and the value of c is '2'; the 1 + +'2' executes, resulting in 3
As here are no more items in the array, the final result of .reduce() call gives as 3, which is then divided by 2 in 3 / 2, resulting in 1.5
Unary operator + preceding string (+'1', '+'2'`) converts the string into integers.
You could divide the sum by 2.
BTW, while you have already integer values as strings, you could use an unary plus + for a conversion to number.
sum += +nums[i];
// ^
var nums = ['1', '75'],
sum = 0,
i;
for (i = 0; i < nums.length; i++) {
sum += +nums[i];
}
alert(sum / 2);

Getting the average returns NAN - JS

I am writing a function called "computeAverageOfNumbers".
Given an array of numbers, "computeAverageOfNumbers" returns their average.
Notes:
If given an empty array, it should return 0.
Here's my code:
function computeAverageOfNumbers(nums) {
var total = 0;
for (var i = 0; i < nums.length; i++) {
total += nums[i];
}
var avg = total / nums.length;
return avg;
}
var input = [];
var output = computeAverageOfNumbers(input);
console.log(output); // --> returns NaN instead of 0
As you can see my code returns NaN when you submit an empty array but works if you put regular array items like var input = [1,2,3,4,5];
If given an empty array, it should return 0.
Am I missing something?
Just do below
if( nums.length == 0 ) return 0;
in code
function computeAverageOfNumbers(nums) {
if (nums.length == 0) return 0;
var total = 0;
for (var i = 0; i < nums.length; i++){
total += nums[i];
}
var avg = total / nums.length;
return avg;
}
Just check if nums.length
function computeAverageOfNumbers(nums) {
if (nums.length === 0) {
return 0
} else {
var total = 0;
for (var i = 0; i < nums.length; i++) {
total += nums[i];
}
var avg = total / nums.length;
return avg;
}
}
var input = [];
var output = computeAverageOfNumbers(input);
console.log(output);
input = [2,5,9,13];
output = computeAverageOfNumbers(input);
console.log(output);
When your array is empty, nums.length = 0 and a if you divide a number by 0, it gives you NaN.
Just change
var avg = total / nums.length;
to
var avg = (nums.length)?total/nums.length:0
to solve your trouble
When you pass an empty array then this line:
var avg = total / nums.length;
Is a division by zero, so avg will be NaN. I would short circuit the function at the start with:
if (nums.length === 0)
return 0;
Bear in mind ideally you also want to do some type checking to confirm you've got an array, etc. but the above should give you the basics.

JavaScript end of loop NaN for a numerical addition

when I run this program I end up with NaN at the end; I'd appreciate some form of explanation, as I'm stumped! I have an odd feeling it has to do something with scope...
https://jsfiddle.net/Smuggles/evj46a23/
var array = []
var range = function(start, end) {
for (var count = start; count <= end; count++) {
array.push(start);
start += 1;
}
console.log(array);
}
var sum = function() {
var result = 0
var arrayLength = array.length
for (var count = 0; count <= arrayLength; count++) {
result += array[count]
console.log(result);
}
}
console.log(sum(range(1, 10)));
2 things:
You need to change the for loop in the sum function to be < arrayLength and not <= arrayLength. You are dealing with array lengths which start with a 0 index.
You need to return the result from the sum function
var array = [];
var range = function(start, end) {
for (var count = start; count <= end; count++) {
array.push(start);
start += 1;
}
};
var sum = function() {
var result = 0;
var arrayLength = array.length;
for (var count = 0; count < arrayLength; count++) {
result += array[count];
}
return result;
};
console.log(sum(range(1, 10)));
Given an array of [4,5,6], the indexes would be as follows:
0: 4
1: 5
2: 6
Therefore, when you use the length property of the array (3), you are referencing an index that does not exist, which returns undefined. It tries to do the math on the undefined, which causes a NaN. This is why you have to use < arrayLength.
The functional approach:
It would help to make those functions a bit more "pure". Instead of maintaining state outside of the functions (with var array = []), just return the values from the functions: See the following for example:
function range(start, end) {
var arr = [];
for (var i = start; i <= end; i++) {
arr.push(i);
}
return arr;
}
function sumArray(array) {
return array.reduce(function(a, b) {
return a + b;
});
}
console.log(sumArray(range(1, 10)));
Each function takes arguments, and simply returns the result. This way, you approach this a little more "functional".
Description in Comments of Code
var array = [];
var range = function(start, end) {
//simplified the loop to remove unnecessary variables
for (; start <= end; start++) {
array.push(start);
}
return array;
}
var sum = function() {
var result = 0;
// move length to scope of the loop
// change to < rather than <= due to zero index nature of arrays
for (var count = 0, length = array.length; count < length; count++) {
result += array[count];
}
// return the result from the function
return result;
}
// gets an array from 1-10
var arr = range(1, 10);
// print the array to the console
console.log(arr);
// print the sum to the console
console.log(sum(arr));

iterate over an array and sum up all values with JS

as the title says i'm trying to sum up using a for loop to iterate over an array.
can you give me some pointers as to where i'm going wrong here. i am returning the value NaN.
var total = 0;
function sum(input) {
for (idx=0; idx<=input; idx++) {
total += input[idx];
}
return total;
}
You actually don't need a loop to do this in modern browsers, you can use the Array.reduce function:
var sum = input.reduce(function(a,b){
return a+b;
}, 0);
You need ot declare total into function and also you need to declare idx. Another thing that instead of writing idx <= input.length you have to write idx <= input.length - 1. Since last index will be undefined.
Try
function sum(input) {
total = 0;
for (var idx = 0; idx <= input.length - 1; idx++) {
total += input[idx];
}
return total;
}
variable total is not declared!
function sum(input) {
var total = 0;
for (idx=0; idx <= input.length; idx++) {
total += input[idx];
}
return total;
}
You are using input both as an integer, and as an array of values. Probably you mean for( var idx = 0; idx < input.length; ++idx )....
Problem which result in NaN is because of your array traversing array till end, rather than from indices 0 to input.length-1
Try this:
http://jsfiddle.net/t9tfofxv/
var total = 0;
function sum(input) {
for (var idx=0; idx< input.length; idx++) {
total += input[idx];
}
return total;
}
var s=sum([1,2,3,4]);
alert(s);
Declare the variable total inside the function, and also use input.length-1 to define the loop's range:
function sum(input) {
var total = 0;
for (idx=0; idx <= input.length-1; idx++) {
total += input[idx];
}
return total;
}

Categories

Resources