I'm studying JavaScript combining functions. Supposed I have firstname
and lastName
as two arguments of my function. I want the console to display Doe
when lastname
is undefinded
. Here is my code but it printed out undefined. Any idea? Thank you!
let name = 'John'
function greetByDefault(firstname,lastname){
return 'Hi ' firstname ' ' lastname '!';
}
if (lastname === undefined){
return 'Doe';
}
console.log(greetByDefault('Jane', 'Doe'));
console.log(greetByDefault(name));
I want the console output to be:
Hi Jane Doe! Hi John Doe!
CodePudding user response:
you can do something like this using a default value
let name = 'John'
function greetByDefault(firstname,lastname = 'Doe'){
return 'Hi ' firstname ' ' lastname '!';
}
console.log(greetByDefault('Jane', 'Doe'));
console.log(greetByDefault(name));
console.log(greetByDefault(name, 'Smith'))
CodePudding user response:
You have to put everything in function
let name = 'John'
function greetByDefault(firstname,lastname){
if (lastname === undefined){
lastname = 'Doe';
}
return 'Hi ' firstname ' ' lastname '!';
}
console.log(greetByDefault('Jane', 'Doe'));
console.log(greetByDefault(name));
CodePudding user response:
let name = 'John'
function greetByDefault(firstname,lastname=''){
if (lastname== ''){
lastname = 'Doe';
}
return 'Hi ' firstname ' ' lastname '!';
}
console.log(greetByDefault('Jane', 'Doe'));
console.log(greetByDefault(name));