Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Michael Smith
8,222 PointsJavascript function coming back as undefined.
I am trying to all this function in jquery with the variable number being the number that user enters in a form, however my function "divide" is being returned as undefined.
var divide = function(entry) { var entry = number;
for (var i = 1; i <= number; i++) {
if (i % 15 === 0) {
return "pingpong";
} else if ( i % 3 === 0) {
return "ping";
} else if (i % 5 === 0 ) {
return "pong";
} else {
return i;
}
} };
2 Answers
Tobias Helmrich
31,604 PointsHey Michael,
this happens because you have to assign the value of entry to the number variable and not the other way around.
You should write it like this:
var divide = function(entry) {
var number = entry;
Also note that in the current state your function will always return 1 because the execution of a function will always stop after a return statement. So right now the loop will start at 1 which means the else block will be executed and this will return i which is 1. After that the function will stop.
Tobias Helmrich
31,604 PointsAh, I see. If you want to achieve this you can just replace the current position in the array with the strings.
Here is an example:
// Some input from a user stored in an array
var userInput = [1, 2, 3, 5, 7, 9, 11, 12, 15, 17, 30];
function replaceNumbers(numbers) {
for(var i = 0; i < numbers.length; i++) {
if(numbers[i] % 15 === 0) {
numbers[i] = "ping pong";
} else if(numbers[i] % 5 === 0) {
numbers[i] = "pong";
} else if(numbers[i] % 3 === 0) {
numbers[i] = "ping";
}
}
}
// Array before executing the function
console.log(userInput);
// Console output: [1, 2, 3, 5, 7, 9, 11, 12, 15, 17, 30]
// Execute the function passing userInput as an example input by a user
replaceNumbers(userInput);
// Array after executing the function
console.log(userInput);
// Console output: [1, 2, 'ping', 'pong', 7, 'ping', 11, 'ping', 'ping pong', 17, 'ping pong']
I hope I can help you with my code.
Michael Smith
8,222 PointsMichael Smith
8,222 PointsThis gets me closer thanks. But what I am struggling to to is to accept input from the user as a string or array then loop through that array, replacing things divisible by 3 with ping, things divisible by 5 with pong and things divisible by 15 with ping pong.