3

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...

2
  • 1
    I'm just curious as to why would you want this Commented Oct 7, 2015 at 7:38
  • This is just a case I made up, to use as an example for more complicated code I'm working on, but which follows a similar pattern. Commented Oct 7, 2015 at 7:42

4 Answers 4

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

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

  console.log('end');
};

fx();

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.