What does the return statement do? When do I use return statements?

Question

What does the return statement do? When do I use return statements?

Answer

return statements can be used inside functions to: 1. end function execution, which will stop any code under the return statement from running and 2. return a value when the function is called. return statements cannot be used outside of functions. The default return value is undefined when no return value is specified.
For example:

const myFunc = () => {
  console.log('hello'); //function that logs hello to the console, no return value is specified
}
console.log(myFunc()); //logging the function call executes the function and logs the return value as well, in this case no return value was specified so undefined also logs to the console
1 Like

though it would print hello if we just call the function like this: myFunc(); , right?

1 Like

That is the point made in the example. If the function logs something, then we do not log again at the caller.

4 Likes

const is often used when declaring a function using the shortcut function declaration method as seen in your example here:

Why is const keyword often used together with function shortcut method?

Can let keyword also be used in this case?

1 Like

First, it’s not a shortcut method but a variation that permits a concise function body with relaxed syntax rules.

Notice that it is an anonymous function expression assigned to a variable? We write const so that the function cannot be overwritten or changed.

Yes, we can use let but given that leaves the function vulnerable to change it should be in a carefully controlled setting.

5 Likes

I do get it now. Thanks.

1 Like

When declaring a constant variable, the only thing constant is the binding between the variable and its value. Many people think that constant variables cannot be mutated. This is not true. If we assigned an object to a constant variable, we can mutate it

const obj = {};

obj.foo = 2;
console.log(obj.foo); // 2

However, if we assign a primitive to a constant variable, or to a reassignable variable, it cannot be mutated. This is simply because primitives cannot be mutated

const str = "Hello";

str.foo = 2;
console.log(str.foo); // undefined

If you try to change the binding between the constant variable and its value, you will run into a type error

const num = 1;

num = 2; // TypeError: Assignment to constant variable
2 Likes