// Write your function here:
const howOld=(age,year)=>{
const currentyear=2023
const yeardiff=year-currentyear;
const newage=age+yeardiff;
if(newage < 0){
return
`The year ${year} was ${-newage} years before you were born`
}
else if (newage > age){
return
`You will be ${newage} in the year ${year}`
}
else {
`You were ${newage} in the year ${year}`
}
}
console.log(howOld(90,2077));
// Once your function is written, write function calls to test your code!
Hello, I dont get it, wt you mean two returns?
There are total 2 . One is on the beneath of if, the other one is else if.
Also, I changed return on the same line, but still shows undefined.
// Write your function here:
const howOld=(age,year)=>{
const currentyear=2023
const yeardiff=year-currentyear;
const newage=age+yeardiff;
if(newage < 0){return
`The year ${year} was ${-newage} years before you were born`
}
else if (newage > age){return
`You will be ${newage} in the year ${year}`
}
else {`You were ${newage} in the year ${year}`
}
}
console.log(howOld(90,2077));
return must be followed by an expression, on the same line. Line breaks in the expression are allowed, but not immediately after the keyword.
More importantly, return does not have an else clause, nor any logic that is not in expression form. We can return a ternary, but not an if-else. When properly constructed there will be two returns; one after the if, and the other after the else.
Thanks for answering, but I do not understand.
The solution is showing return after else.
Also, eventhough I changed the code to the same line as above. It is still showing undefinded.
Please forgive me as my first language is not English.
If you can, please correct my code directly.
Thx in advance !!!
// This will return undefined because the value being returned is not
// on the same line as the return keyword. The compiler has no way of knowing
// that you meant to return the string on the next line. As soon as the return
// statement is reached, the function will return undefined.
if (3 > 2) {
return
"Some string"
}
// This will return the string "Some string"
if (3 > 2) {
return "Some string"
}
// This will also return the string "Some string", because the opening parenthesis
// is on the same line as the return keyword.
if (3 > 2) {
return (
"Some string"
)
}
Furthermore,
// This works.
if (3 < 2) {
return "abc"
} else {
return "xyz"
}
// This doesn't work as expected, though no error will be thrown.
if (3 < 2) {
return "abc"
} else {
"xyz"
}
// This won't work and a SyntaxError will be thrown.
if (3 < 2) {
return "abc"
else "xyz"
}
// This won't work and a SyntaxError will be thrown.
return if (3 < 2) {
"abc"
} else {
"xyz"
}