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() { };
- It makes the function immutable, so you don’t have to worry about that function being changed by some other piece of code.
- You can use fat arrow syntax, which is shorter & cleaner.
- Using arrow functions takes care of
this
binding for you.
Source: stackoverflow.com
JavaScript const function
Simple function example code with const
keywords and parameters. In case you declare it as const, the function will never get overridden by some other js file having the same function name.
The definition will remain the same, whatever 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:
If you want to create an immutable function, one approach is to use function expressions and avoid modifying the function after declaration. Another approach is to use ES6 arrow functions, as they are always anonymous and cannot be reassigned.
// Using function expression
const immutableFunction = function() {
console.log("This is an immutable function.");
};
// Using arrow function
const immutableArrowFunction = () => {
console.log("This is an immutable arrow function.");
};
Remember that while const
helps in making the reference to the function constant, it doesn’t make the function itself immutable. If you need true immutability, you may want to explore other patterns or use libraries like Immutable.js.
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