Skip to content
Advertisement

Javascript function solution

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement