Check file extension with JavaScript

<form>
    <input type="file" id="file" />
</form>

<script>
    function validateFileExtension() {
        //Create an array of acceptable values
        const acceptedFiles = [".txt", ".doc", ".docx", ".pdf", ".jpg", ".jpeg", ".png"];
        //Get value from form
        let file = document.querySelector("#file").value;
        
        let validFile = false;
        //Iterate through array of accepted files
        for (let j = 0; j < acceptedFiles.length; j++) {
            //Compare extension to current value in acceptedFiles at index j
            if (file.substr(file.length - acceptedFiles[j].length, acceptedFiles[j].length).toLowerCase() == acceptedFiles[j].toLowerCase()) {
                //When we reach extension that is allowed and
                //equal to current extension finish the loop
                //and pass true to validFile variable
                validFile = true;
                break;
            }
        }
        
        //When loop is finished we check if validFile is true or false
        if (!validFile) {
            //if it is not validFile, return error
            return false;
        }
        
        //If it is validFile continue your code execution
        
        
    }
</script>