What is the function return when throwing an error - Javascript
Asked Answered
C

2

7

I was reading the book Professional Javascript For Web Developers, and saw the following code. I have some questions about it:

  1. What does "throw new Error()" return? Undefined?
  2. What will happen to the code block of "if" if there is an error thrown out?

function matchesSelector(element, selector){

  if(element.matchesSelector){
      return element.matchesSelector(selector);
  }else if(element.msMatchesSelector){
      return element.msMatchesSelector(selector);
  }else if(element.mozMatchesSelector){
      return element.mozMatchesSelector(selector);
  }else if(element.webkitMatchesSelector){
      return element.webkitMatchesSelector(selector);
  }else{
    throw new Error("Not supported!");
  }
}


if(matchesSelector(document.body, "body.page1")){
  //do somthing
}
Cyclothymia answered 21/2, 2017 at 21:10 Comment(2)
}else? will need one open {?Affined
Thanks for reminding. I just added it. @ÁlvaroTouzónCyclothymia
A
8

When an error is thrown, if it is not caught using a try...catch block, the scope execution just stops.

Nothing is returned by that function, and if that function's return value is used somewhere in if statement, that if statement block is not executed as well.

Archenteron answered 21/2, 2017 at 21:15 Comment(0)
T
2

This particular block of code is an attempt to create a generic, cross-platform selector. If you get to the error, then whatever browser you're on doesn't support any of the given selector matches (and may likely be considered a fringe browser, used by an "acceptably small" minority of users). It will fail, and an error message may be returned in the console. But it will most likely die silently.

By extension, when the final if() is run, it'll also die silently...

Triolein answered 21/2, 2017 at 21:15 Comment(3)
Thanks. One more question: If the if() dies silently, will the remaining code be executed?Cyclothymia
If the error is never caught using a try/catch, the code will try to continue but it may give you unexpected errors -- for example, if you're trying to act upon the returned data, it will return error messages. If you're working with other data in that same if statement, THAT would work fine.Triolein
I see. Thank you!Cyclothymia

© 2022 - 2024 — McMap. All rights reserved.