Search code examples
javascriptecmascript-6modulearrow-functions

Arrow functions not working with modules?


So I'm practicing my javascript skills. I'm currently studying es6 and I'm trying to use arrow functions with modules but they don't seem to work together. What is the reason for this?

I've tried only using one javascript file. Arrow functions work when the script type attribute in HTML is "text/javascript", but I want to separate the codes so it can be cleaner and easier to manage. So I used modules. I set the script type attribute to "module" so this would work. But now that I've separated the code, the arrow functions won't work anymore.


No module


HTML

    <script type="text/javascript" src="script.js" async></script>

Javascript

    const quoteBtn = document.getElementById('quoteBtn');
    const quote = document.getElementById('quote');
    const author = document.getElementById('author');

    const quotes = [
        {name:'Stephen King', quote:'signosfnggf'}
        /// more objects...
    ]

    displayQuote =()=> {
        var selectQuote = Math.floor(Math.random() * quotes.length);
        quote.innerHTML = `"${quotes[selectQuote].quote}"`;
        author.innerHTML = `<i> - ${quotes[selectQuote].author}</i>`;
    }

    quoteBtn.addEventListener('click', displayQuote);

With Module


HTML

    <!-- Module type required in using module functionality-->
    <script type="module" src="script.js" async></script>

JS (now using modules...)


    import {quotes} from './lib/quotes.js'
    const quoteBtn = document.getElementById('quoteBtn');
    const quote = document.getElementById('quote');
    const author = document.getElementById('author');

    displayQuote =()=> { /*Uncaught ReferenceError: displayQuote is not 
    defined*/

        var selectQuote = Math.floor(Math.random() * quotes.length);
        quote.innerHTML = `"${quotes[selectQuote].quote}"`;
        author.innerHTML = `<i> - ${quotes[selectQuote].author}</i>`;
    }

    quoteBtn.addEventListener('click', displayQuote);

I expected arrow functions to work with modules and run normally. But the browser gives me an error: script.js:6 Uncaught ReferenceError: displayQuote is not defined


Solution

  • You need to add let, var or const - I'd use const because it's a function:

    const displayQuote = () => {...}
    

    Declaring variables without these keywords results in an implicit global, and fails in strict mode.