Help, please. Struggling to to write a function that takes in a single optional parameter

I was tasked to write a function that takes in a single optional parameter. It should work like this:

task2("Sally") should print Hello Sally! task2("Tshepo") should print Hello Tshepo! task2() should print Hello Friend!

And I’m struggling. The last thing I tried are else/ if statements

function task2(Sally, Tshepo) {
    
    if (Sally) {
        return "Hello Sally!";

    } else if (Tshepo) {
        return "Hello Tshepo!";
        
    }
   
    console.log("Hello Friend!");
}
2 Likes

Are the variables Sally and Tshepo defined before you use them? If not then this isn’t going to work.

Please show us your entire function definition.

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

HI @Nqobile !

Welcome to the forum!

I would personally go with a different approach because this is a little limiting.

What if I wanted to have multiple function calls with different names for the arugments like this?

task2("Jess")
task2("Bruce")
task2("Nancy")
task2("Cole")
etc....

With your current code setup, you would need to write an if/else chain to accommodate all of those names.

I would suggest simplifying your approach.

You basically want to say if the function wasn’t called with any arguments passed in return “Hello Friend!”

If the function was called with an argument that is a string then return Hello, name(name represents the name passed into the function call)

You could try looking into aruguments object

If you don’t want to use the arguments object, then you can use a ternary to basically use the same logic I stated earlier but checking if name is undefined.

There is more than one way to approach this but that would be my approach.

Hope that helps!

(post deleted by author)

(post deleted by author)

Thank you, I’ll give it a try

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.