Don’t name your global JavaScript function ‘clear’


Same as the title, don’t name your global JavaScript function clear.


I learned the hard way not to use clear as the name for my global JavaScript function.

Given the example below:

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test 1</title>

        function clear() {
            document.getElementById('result').innerHTML = '';

    <button id="clear" onclick="clear()">Clear</button>
    <div id="result">Testing</div>


and clicking the Clear button, the Testing text will just not be removed.

I found this very cool StackOverflow explanation of why is that. The gist of it is that this way the document.clear function is being called, and simply renaming it to something like clearResult works fine.

Written by Nikola Brežnjak