issue in if else statement

535 Views Asked by At

I need help to solve this issue that I am having. I have went through few question available in stackoverflow but i still dont get it.

this is the code im writing:

var myFeedback = ""
      if (this.userFriendlinessRating <= 4.0 && this.userFriendlinessRating >= 3.5){
        myFeedback = 'VERY SATISFIED' 
        return myFeedback;
      } else if (this.userFriendlinessRating <= 3.5 && this.userFriendlinessRating >= 2.5){
        myFeedback = 'SATISFIED' 
        return myFeedback;
      } else if (this.userFriendlinessRating <=2.5 && this.userFriendlinessRating >=1.5){
        myFeedback = 'NOT SATISFIED' 
        return myFeedback;
      } else {
        myFeedback = 'VERY NOT SATISFIED' 
        return myFeedback;
      }
      console.log(myFeedback)

and this is the error that i get:

unreachable code

3

There are 3 best solutions below

2
On BEST ANSWER

If you want to access the console log you should restructure like this, so the last line is reachable.

var myFeedback = ""
if (this.userFriendlinessRating <= 4.0 && this.userFriendlinessRating >= 3.5){
  myFeedback = 'VERY SATISFIED' 
} else if (this.userFriendlinessRating <= 3.5 && this.userFriendlinessRating >= 2.5){
  myFeedback = 'SATISFIED' 
} else if (this.userFriendlinessRating <=2.5 && this.userFriendlinessRating >=1.5){
  myFeedback = 'NOT SATISFIED' 
} else {
  myFeedback = 'VERY NOT SATISFIED' 
}
console.log(myFeedback)
return myFeedback;
3
On

Every if part and the last else all contain return, so the control can not pass past the if-elseif-elseif-else structure. Hence the last console.Log line is unreachable.

Drop all inner return statements and add one at the end to get what you intend:

var myFeedback = ""
      if (this.userFriendlinessRating <= 4.0 && this.userFriendlinessRating >= 3.5){
        myFeedback = 'VERY SATISFIED' 
      } else if (this.userFriendlinessRating <= 3.5 && this.userFriendlinessRating >= 2.5){
        myFeedback = 'SATISFIED' 
      } else if (this.userFriendlinessRating <=2.5 && this.userFriendlinessRating >=1.5){
        myFeedback = 'NOT SATISFIED' 
      } else {
        myFeedback = 'VERY NOT SATISFIED' 
      }
      console.log(myFeedback)
      return myFeedback;
6
On

You have to pass a single return for your decision of myFeedback variable and that return should be placed at the end. See example outline below

      var obj = ""

      if (cond){
        obj = 'VERY SATISFIED' 
      } else if (cond){
        obj = 'SATISFIED' 
      } else if (cond){
        obj = 'NOT SATISFIED' 
      } else {
        obj = 'VERY NOT SATISFIED' 
      }
      console.log(obj)
      return obj;