Question about returning a new variable

Tell us what’s happening:
Describe your issue in detail here.
I’ll be honest, I’m not sure how to state my question. I’m doing my best to try and understand some of the more elegant solutions to the exercises. I often find I’ve added more lines of code than necessary, with utilizing “return” in particular.

I’m not sure what to research to learn about this. Can someone point me in the right direction? There is an example below.

The Code I Wrote
My return is just a single variable. This is how I usually write the code.


function spinalCase(str) {

let newStr = str.replace(/([a-z])([A-Z])/g, "$1 $2");
let newStr2 = newStr.replace(/(\s|\W|[_])/g, "-" ).toLowerCase();
return newStr2
}

Better - Statment after Return
Here return is used with a statement, alleviating the need for the second variable.

What is this idea called?

function spinalCase(str) {

let newStr = str.replace(/([a-z])([A-Z])/g, "$1 $2");

return newStr.replace(/(\s|\W|[_])/g, "-" ).toLowerCase();
}

console.log(spinalCase("AllThe-small_Things"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36

Challenge: Spinal Tap Case

Link to the challenge:

I’m not sure it’s called anything. I guess it is an immediately returned expression value.

All functions return a value, an explicit return value, or undefined. You can save the value in a variable before the return, or return the value an expression evaluates to immediately.

In an assignment, the right-hand side of the = is the value, that value can be returned instead of assigned to a variable.

1 Like

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