Getting a NaN error in Javascript Add function - javascript

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

Related

I am running this javascript code but it is giving me an.. error please tell me what is wrong because I think the code is correct?

let marks_of_students = [100,100,40]
function FindGrade(marks) {
let sum = 0;
for (let i = 0;i <= marks.length; i++) {
sum += marks[i];
console.log(sum);
}
return sum;
}
console.log(FindGrade(marks_of_students));
I don't know why I'm seeing this NaN printing along side the sum. Someone please help what did I do wrong?
You are trying to loop over the mark_of_students array with a condition i <= marks.length which means the loop will try to find marks[3] in the last iteration which doesn't exist. You need to change the condition to i < marks.length to get the desired result.
let marks_of_students = [100, 100, 40]
function FindGrade(marks) {
let sum = 0;
for (let i = 0; i < marks.length; i++) {
sum += marks[i]
}
return sum
}
console.log(FindGrade(marks_of_students))
try to convert a object into a integer by command parseInt(object) to sum.
Im javascript concatenates, NaN is not a number;
Try to do this:
parseInt("1") + parseInt("1")
instead of 1 + 1

Getting "typeError" "is not a function" when using .length

Here is my code:
function permAlone(string) {
if (string.length < 2) return string; // This is our break condition
var permutations = []; // This array will hold our permutations
for (var i = 0; i < string.length; i++) {
var character = string[i];
// Cause we don't want any duplicates:
if (string.indexOf(character) != i) // if char was used already
continue; // skip it this time
var remainingString = string.slice(0, i) + string.slice(i + 1, string.length); //Note: you can concat Strings via '+' in JS
for (var subPermutation of permAlone(remainingString))
permutations.push(character + subPermutation);
}
var permutationsFinal = [];
for (var j = 0; j < (permutations.length); j++) {
if (!(permutations[j].match(/([a-zA-Z])\1/))) {
permutationsFinal.push(permutations[j]);
}
}
return (permutationsFinal.length);
// ^^^^^^^^ if I add this, the error is thrown
}
permAlone('abc');
If I replace:
return (permutationsFinal);
by:
return (permutationsFinal.length);
I get this error in the console:
TypeError: permAlone is not a function
Why?
Thanks for your help! :)
It is a recursive function, if you return anything other than what is expected by the function itself then you will break the recursive loop.
To remove an answer from comment:
for (var subPermutation of permAlone(remainingString)) iterates over the return value of the function (called recursively). It's the line number of the error. Numbers are not iterable, so when you return a number instead of an array it throws an error.
Not sure what browser you are using, but FireFox reports the error as
TypeError: permAlone(...) is not iterable
which is more or less self explanatory. If the error message reported in your browser is for the code posted, it is arguably not just misleading but factually incorrect.

setting the length of an array's string element to a variable in a for loop in javascript

I have this code. and for some reason i get the error: Uncaught TypeError: Cannot read property 'length' of undefined. I can't seem to figure out why.
function findShort(s) {
var c = s.split(' ');
var l = c[0].length;
var wordlength;
for (var i = 1; c.length; i++) {
console.log(c[i].length);
wordlength = c[i].length;
if (l < wordlength) {
l = wordlength;
}
}
return l;
}
console.log(findShort("hello dog cat 12 asdsad wuidhuiwqhd"));
the error is with the line wordlength = c[i].length;
When i console.log it, it shows the length of each string in the array. However, when i try to store that length it says it's undefined.
You need to change this line
for ( var i = 1; c.length; i++ ) {
to
for ( var i = 1; i<c.length; i++ ) {
The second componenet of a for loop is a boolean condition that is checked for every round of the loop to determine if the loop should continue or not. By putting c.length, you are giving a constant value which will make the loop to either never run (if c.length is 0), or to run forever (if c.length not 0).
You should also be careful with the following line:
var l = c[0].length;
It might cause a problem too as it is not guaranteed that c will have at least one element.

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.

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