In JavaScript, function overriding means replacing an existing function implementation with a new one. The new implementation is then used whenever the function is called.
- User-defined functions can be overridden by assigning a new function to the same variable.
- Built-in functions can also be replaced, but doing so should be avoided unless there is a specific reason.
- Overriding is useful for customizing existing behavior, testing, or debugging.
- The original function is no longer directly available unless a reference to it was saved beforehand.
Approach 1: Overriding a User-Defined Function
A user-defined function can be overridden by assigning a new function to the same variable.
function Fun() {
return "This is from the old function";
}
console.log(Fun());
// Override the function
Fun = function() {
return "This is from the overridden function";
};
console.log(Fun());
Output
This is from the old function This is from the overridden function
- Initially, Fun() returns the message from the original implementation.
- A new function is assigned to Fun.
- The new implementation replaces the previous function.
- Subsequent calls to Fun() use the overridden implementation.
If you need to preserve the original function, store its reference before overriding it:
function Fun() {
return "Original function";
}
const originalFun = Fun;
Fun = function() {
return "Overridden function";
};
console.log(originalFun());
console.log(Fun());
Output
Original function Overridden function
Approach 2: Overriding a Built-in Function
JavaScript also allows properties such as built-in functions to be reassigned. However, overriding built-in functions such as parseFloat() can lead to unexpected behavior and should generally be avoided in production code.
console.log(parseFloat("2.345"));
// Override parseFloat()
parseFloat = function(value) {
return Math.floor(value);
};
console.log(parseFloat("2.345"));
Output
2.345 2
- Initially, the built-in parseFloat() converts "2.345" to 2.345.
- A new function is assigned to parseFloat.
- Subsequent calls use the new implementation, which returns the floor value.
- This changes the expected behavior of a standard JavaScript function.
Note: Overriding built-in functions can affect other parts of an application that depend on their standard behavior. Prefer creating a new function with a different name when possible.