Within this function you have an HTML string.
This string has the opening tag <script>
and will receive content that the user enters.
If inside the content you insert you put the closing tag of this script </script>
then you will "cheat the code" and you can add a new opening tag <script>
and put whatever you want in it.
In your first example <script>alert(1);</script>
the result is :
return '<script>console.log("<script>alert(1);</script>");</script>';
where the last </script>
is discarded by the browser.
In your second example, you stop the console.log syntax and generate HTML with the script tag that you inserted and so on :
<script>console.log("</script><script>alert(1);</script>");</script>
The first block <script>console.log("</script>
gives syntax error, but the browser runs the next block <script>alert(1);</script>
that gives the alert.