Reputation: 21
I need to implement the solution function such as running the following line:
console.log(solution('Hello You !'))
gives the following output (one word per line):
Hello
You
!
The input parameter is always a non-null character string. So i did that code:
function solution(input){
arr=input.split(" ");
for(var i=0;i<arr.length;i++) {
console.log(arr[i]);
}
}
input="Hello You !";
console.log(solution('Hello You !'));
But when i run it , i get the result:
Hello
You
!
undefined
Why the result of my code snippet displays "undefined"?
What is that "undefined"? how can i fix it?
Upvotes: 1
Views: 1107
Reputation: 1704
In your code, you are returning nothing (undefined) from the solution
function so you are getting undefined
at the end. I think a very succinct but still readable answer would be the following code if you are permitted to just invoke the solution
function without surrounding it in console.log
.
function solution(input){
input.split(" ").forEach(word=> console.log(word));
}
solution('Hello You !')
Upvotes: 0
Reputation: 97152
Because the return value of your function is undefined
.
You're not only logging to the console from within the function, but you're also logging the return value of your function.
Instead of:
console.log(solution('Hello You !'));
Just do:
solution('Hello You !');
If your requirements dictate that you have to invoke the function with console.log(solution('Hello You !'))
, you could consider splitting and joining:
const solution = (input) => input.split(' ').join('\n');
console.log(solution('Hello You !'));
Or use a replacement:
const solution = (input) => input.replaceAll(' ', '\n');
console.log(solution('Hello You !'));
Upvotes: 3
Reputation: 2268
You're not returning anything, you have to return the arr
function solution(input){
arr=input.split(" ");
for(var i=0;i<arr.length;i++) {
console.log(arr[i]);
}
return arr;
}
When you call a function, the value will be its return value. If no return value is specified, a function returns undefined.
Upvotes: 1