Need help for return statement

I want to know the use of return statement .What if I don’t use the return statement ? What kind of problems will I be facing if I don’t use it?

If you don’t return from a function, it returns for you automatically when the last instruction in the function executes.

function foo() { console.log('foo') }
retval = foo()
console.log(`return from foo:  ${retval}.`)

Remember, you can run code like this in the console of your browser, and answer questions like this for yourself via some simple test code, or if you prefer, run it in a local javascript development environment, or online using a sandbox like codepen, jsfiddle, stackblitz, etc.

Nothing bad happens if a function does not return a value.

Some procedural languages (Pascal for example) actually have a specific name for a code unit that executes but does not return anything. You define it as a “procedure” rather than a function. Most computer languages that have functions will continue to execute even if a function is called that never returns a value.

Every function returns something. With traditional functions (using the function keyword to creatr them), a function with no explicit return simply returns undefined.

You don’t always need an explicit return, though as you get more comfortable with functions, you may find returned values more and more useful. And some functions that do return a value? You don’t always have to capture that value.

It won’t break anything if you don’t return a value, so long as you are expecting that.

so basically even if I don’t return something it shall remain same. What do you mean by undefined? what happens if I keep it undefined?

undefined is a data type in JavaScript, and it’s the default value in various situations, like when a function doesn’t have a return statement.
Keeping something as undefined on its own does nothing, but things break if a piece of code expect something and gets undefined instead

1 Like