Can we write javascript code in twig template? Can we write javascript code in twig template? 

Its needed to write javascript code in twig template.

When we are writting the same code in custom.js file that particular code is not working in it.

How to write javascript code directly into the 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 %}