Return statement

Tell us what’s happening:

function myFun() {
  return "World";

can anyone explain to me the main function of RETURN statement in this code? why is “world” not displaying in the console?

You need to use console.log if you want to print World to the console.
And it needs to be before the return statement or else it won’t get printed.

Or you may wrap the function call in the console.log()

Functions in JS return value when called. You can see it, if you assign to a variable, or log them directly:

function giveValue() {


console.log(giveValue())  // logs undefined

const returnedValue = giveValue()
console.log(returnedValue)  // logs undefined

Even the empty function i defined giveValue returns a value, but since i dont explicitely tell it to return anything specific, it just gives undefined.
Thanks to return statement, we can control what a function returns. One important specification is, once we return a value, the function stops any further code running in its body.

function myFun() {
  console.log("Hello");  // this will log on function call
  return "World";
  console.log("byebye")  // this wont be logged

const returnedValue = myFun()  // returnedValue === 'World'

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