Learn how to write a function that changes any string into snake_case format, and understand how arguments and return values work inside that function.
Snake case means writing all words in lowercase and separating them with underscores. Itβs often used for file names and variable names, like:
"Hello World" β "hello_world"
A function is a small, reusable piece of code that performs a specific job. We give it input to work with, and it gives us output back.
function name(argument) {
// do something
return result;
}
In our case, the function will:
An argument is the value you pass into a function so it has something to work on.
For example:
toSnakeCase("Hello World")
Here, "Hello World" is the argument.
Inside the function, you might refer to it as a parameter like text.
Thatβs just the name of the value while the function is running.
Arguments let functions handle many different inputs without rewriting code each time.
A return value is what the function gives back when it finishes.
If a function doesnβt return anything, it wonβt produce a usable result.
For example, after we process "Hello World", the function should return "hello_world".
Returning a value makes the function reusable:
let newText = toSnakeCase("JavaScript Is Fun");
// now newText holds "javascript_is_fun"
To make this conversion, weβll use two built-in string methods:
.toLowerCase() β turns all letters into lowercase..replace() β swaps one set of characters for another (like spaces β underscores).These methods help us transform the input step by step.
.toLowerCase() to make everything lowercase..replace() or .replaceAll(" ", "_") to swap spaces for underscores.This is how your function takes an argument, processes it, and provides a return value.
Once youβre comfortable with snake case, you can explore other formats using new methods:
.split(" ") β breaks a string into an array of words..join("_") β joins words together with a chosen symbol.These will be useful for more complex conversions later.
Kebab Case:
Replace underscores with dashes β "Hello World" β "hello-world"
Camel Case:
Join words without symbols and capitalize each word except the first β "Hello World" β "helloWorld"
| Concept | Description | Example |
|---|---|---|
| Argument | The input we give to the function | "Hello World" |
| Return Value | The new value the function gives back | "hello_world" |
| String Methods Used | .toLowerCase(), .replace() |
Β |
| Next Step | Practice writing your own toSnakeCase function, then adapt it for kebab or camel case |
Β |
Ready to organize your code? Learn how to import and use your toSnakeCase function in other files:
π Importing Functions with Node.js
This lesson was created with assistance from GPT-5.