-1

Is there a proper way (ES6 friendly) to avoid using global variable in my JavaScript example ? I saw that we can use a function to wrap our code in a closure ?..

<textarea name="fileEdition" id="fileEdition" placeholder="Some content from a file, editable"></textarea>
<button id="saveFile">Save</button>

<script>
    const files = document.querySelector('#RandomFileListGotInPHP');
    const fileEdition = document.querySelector('#fileEdition');
    const saveButton = document.querySelector('#saveFile');

    function openFile() {
        fileEditionBackup = fileEdition.value;    
    }

    function saveFile() {
        console.log(`backup content before save in PHP: ${fileEditionBackup}`);
    }

    files.addEventListener('change', openFile);
    saveButton.addEventListener('click', saveFile);
</script>

Thank for the help.

GuillaumeRZ
  • 2,656
  • 4
  • 19
  • 35

1 Answers1

1

I can't see a reason against an IIFE:

(function () {

    const files = document.querySelector('#RandomFileListGotInPHP');
    const fileEdition = document.querySelector('#fileEdition');
    const saveButton = document.querySelector('#saveFile');

    function openFile() {
        fileEditionBackup = fileEdition.value;    
    }

    function saveFile() {
        console.log(`backup content before save in PHP: ${fileEditionBackup}`);
    }

    files.addEventListener('change', openFile);
    saveButton.addEventListener('click', saveFile);
})();

Of course, +function(){ ... }() or (_=>{ ... })() will work as well.

PeterMader
  • 6,987
  • 1
  • 21
  • 31