3

How can I early exit from a function in my TypeScript file?

checkIfFollowed(){
    
    this.currentUserInfos.followed.forEach(element => {
        if(18785 == 18785){
            console.log('its true');                
            this.alreadyFollowed = true;
            return; // Exit checkIfFollowed() here
        }

    });

    this.alreadyFollowed = false;
    console.log('the end');
    return;
}

When I'm running it, it's executed completely, but it should exit after the first:

'its true'

But in my console, I get:

its true

its true

the end

Foreach loops 2 times as expected, but why the method doesn't stop after hitting a "return"?

I'm not trying to get out of the forEach, but ending the method 'checkIfFollowed' in the foreach.

'the end' should not be printed.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Toodoo
  • 8,570
  • 6
  • 35
  • 58

3 Answers3

7

Another approach, with for loop:

checkIfFollowed() {
  for (let i = 0; i < this.currentUserInfos.followed.length; ++ i) {
    if (18785 == 18785) {
      console.log('its true');                
      this.alreadyFollowed = true;
      return; // exit checkIfFollowed() here
    }
  }

  this.alreadyFollowed = false;
  console.log('the end');
  return;
}
gsc
  • 1,559
  • 1
  • 13
  • 17
  • It works. Weird, why it doesn't work with forEach approach ? Many thanks. – Toodoo Apr 03 '17 at 09:14
  • 3
    Because using `forEach`, you are entering a new function (`.foreach(function (e) {…})`) and calling `return` there stops that new function and not the parent (`checkIfFollowed`) one. You are welcome! – gsc Apr 03 '17 at 09:15
5

Try this instead of forEach

.every() (stops looping the first time the iterator returns false or something falsey)

With every():

checkIfFollowed(){

        this.currentUserInfos.followed.every(function(element, index) {
            // Do something.
            if (18785 == 18785){
                console.log('its true');                
                this.alreadyFollowed = true;
                return false;
            }
        });
        if(this.alreadyFollowed) 
        {
            return ;
        }
        this.alreadyFollowed = false;
        console.log('the end');
        return;
}  
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
2

You could also not fight foreach :) and do it this way:

checkIfFollowed(){

    const filtered = this.currentUserInfos.followed
       .filter(el => el.id === 18785) // or some other condition
       .forEach(element => {
         // maybe you don't need to do anything here
         // or you can continue processing the element and you know you only have 
         // items that you want
      });

   this.alreadyFollowed = filtered.length > 0;
   console.log('the end');
//    return; // no need for an empty return at the end of a function.
}

HTH

sirrocco
  • 7,975
  • 4
  • 59
  • 81