Academiphile
Academiphile

Reputation: 1484

Javascript returning out of a function inside a function

Given this code:

var x=5;
var fx=function(){
    console.log("hey");
    (function(){
        if (x==5){
            console.log('hi');
            return;
        }
    })();
    console.log('end');
};

fx();

How do I return in such a way that the final console.log is not executed when x==5?

I am new to javascript, so maybe I missed something...

Upvotes: 3

Views: 70

Answers (4)

Dyrandz Famador
Dyrandz Famador

Reputation: 4525

you can wrap your function to a condition

var x=5;
var fx=function(){
   console.log("hey");
   if( !(function(){
       if (x==5){
           console.log('hi');
           return true;
       }
    })() ){
       console.log('end');
    }
};

fx();

JSFIDDLE DEMO

Upvotes: 1

Jacob
Jacob

Reputation: 1004

you can either an if statement or else depending on hwta you're trying to do

if

var x=5; var fx=function(){
    console.log("hey");
    (function(){
        if (x==5){
            console.log('hi');
            return;
        }
    })();
    if(x != 5){
        console.log('end');
    } };

fx();

else

var x=5;
var fx=function(){
    console.log("hey");
    (function(){
        if (x==5){
            console.log('hi');
            return;
        } else {
            console.log('end');
        }
    })();
};

fx();

Upvotes: 0

orlland
orlland

Reputation: 1266

var x = 5;
var fx = function() {
  console.log("hey");

  if (x == 5) {
    console.log('hi');
    return;
  }

  console.log('end');
};

fx();

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can't return like that, instead you can use a flag or make the inner function to return a value like

var x = 5;
var fx = function() {
  snippet.log("hey");

  var flag = (function() {
    if (x == 5) {
      snippet.log('hi');
      return false;
    }
  })();
  //if the returned value is false then return
  if (flag === false) {
    return
  }
  snippet.log('end');
};

fx();
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 1

Related Questions