Aim of the puzzle: Use specific instructions to complete a function.
Walk through of solution: This puzzle is the 1st in a series of lessons that will teach you how to break down word problems and real-world challenges and solve them with code.
For this puzzle, you will be getting specific instructions on how to write a function. In a future puzzle, you will be revisit this function and use it to solve a word problem, without being given specific instructions.
To complete this puzzle, complete the longer()
function so that it takes 2 strings and returns whichever string is longer.
Sample code solution:
There are multiple ways to solve the puzzle.
function longer(a, b) {
if (a.length > b.length) {
return a;
} else {
return b;
}
}
console.log(longer('signify','significant'));
Another Solution:
function longer(a, b) {
return a.length > b.length ? a : b;
}
console.log(longer('signify','significant'));
Javascript Concepts: Functions, .length
, Strings
5 Likes
Why in ternary code three is no return code and what is the different between code above with my code. I still confuse with usefull of return
1 Like
Hey there,
The return
keyword tells the function to return a value when it is called. In this case, the function will return whichever string is longest. We can call this function inside a console.log()
if we want to print the longer word, or we can store the longer word in a variable.
You function prints the longer word, but doesn’t return a value.
Hope this helps! Let me know if you have any questions.
Ben
7 Likes
A post was merged into an existing topic: The Longest Word explainer
Ben sir please help me to do this
1 Like
In the code block for the longer
function, you can either use an if...else
statement or return a
if a
is longer than b
. It can either go like this:
function longer (a, b) {
if (a.length > b.length) {
return a;
} else {
return b;
}
}
or
function longer (a, b) {
return a.length > b.length ? a : b;
}
Hope this helps! 
I don’t know how to do this. I use the code that the feedback messages tell me but it still didn’t work. So pls help.