Skip to content

JavaScript const function | Example code

  • by

You can define the JavaScript function with the const keyword. JavaScript const function comes with some great advantages that make it superior.

const func = function() { };
  1. It makes the function immutable, so you don’t have to worry about that function being changed by some other piece of code.
  2. You can use fat arrow syntax, which is shorter & cleaner.
  3. Using arrow functions takes care of this binding for you.

Source: stackoverflow.com

JavaScript const function

Simple function example code with const keyword and parameters. The function will never get overridden by some other js file having same function name in case you declare it as const.

The definition will remain exactly the same, whatever be the case

<!DOCTYPE html>
<html>
<body>
  <script>    
    // define a function (wow! that is 8 chars shorter)
    const add = (x, y) => x + y;

    // use it
    console.log(add(100, 200)); 

    // someone tries to mutate the function
    add = (x, y) => x - y; 
  </script>  

</body>
</html>

Output:

JavaScript const function

Do comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *