Question:
Write a function hello having one parameter and returning 'Hello <parameter>!'. If hello is called without an argument, 'Hello world!' should be returned.
Example: hello('Nala') should return 'Hello Nala!'.
Answer:
function hello (p) {
if (p === undefined) {
return `Hello world!`;
} else {
return `Hello ${p}!`}
};
or
function hello (param) {
if (param) {
return 'Hello ' + param + '!' ;
} else {
return 'Hello world!'}
};
> we declare a function 'hello'
> it has one parameter - 'p'
> we open if / else statements to check
>> if the function 'hello' is called with a parameter 'p'
>> or it is called without a parameter
> if it is called with a parameter then we have to return a string
> this string will append the parameter 'p' to 'Hello' and return it
> in case the function is called without a parameter
> then we should simply return 'Hello world!'
> we can solve it in many ways
> we have two solutions here
> the first solution checks if the parameter 'p' is undefined
> like this: p === undefined
> if it is undefined then the function will return 'Hello world!'
> or else it will return `Hello ${p}!`
> the second solution checks if the parameter ' param' exists
> like this (param)
> if it exists then we get 'Hello ' + param + '!'
> if it does not exist then we shall be returned 'Hello world!'
No comments:
Post a Comment