Can we write javascript code in twig template?
Yes, you can write JS code in a twig template. I can't think of any syntax crossovers so you should be able to literally write it as-is.

Indeed this works fine in html.twig.html:

&lt;script&gt;
  (function(val) {
    console.log(val);
  })('test');
&lt;/script&gt;


If you're having syntax trouble, you can always escape it with raw, but it should be unnecessary:

{% raw %}
&lt;script&gt;
  (function(val) {
    console.log(val);
  })('test');
&lt;/script&gt;
{% endraw %}