esc_js() is used to escape single quotes, htmlspecialchar ” < > &, and fix line endings; it takes only a single required parameter as a string: the text to be escaped, and returns an escaped text.
It is intended to be used for inline JavaScript such as the onclick="" attribute (note that the strings have to be in single quotes). The 'js_escape' filter is also applied here.
In practice, using the esc_js() function is quite simple and is encouraged for sanity of data.
Let’s take a look at its usage in the example below;
Instead of simply echoing a variable as in <?php echo $variable; ?> for an onclick="" attribute when using inline JavaScript, you should leverage on the esc_js() function and as such, you should instead do this: <?php echo esc_js( $variable ); ?>.
So: use (good)
<a href="https://wordpress.stackexchange.com/news/" onclick="alert( '<?php echo esc_js( $variable ); ?>' )"></a>
instead of (bad)
<a href="https://wordpress.stackexchange.com/news/" onclick="alert( '<?php echo $variable; ?>' )"></a>
Introduced in version 2.8.0 and defined in wp-includes/formatting.php, the esc_js() related Functions include: esc_sql(), esc_url(), esc_html(), esc_attr(), fetch_rss().