What do you understand by $watch?

In angularJS, $watch() function is used to watch the changes of variable in $scope object. Generally, the $watch() function is created internally to handle variable changes in the application.

If there is a need to create custom watch for some specific action then it’s better to use $scope.watch function. The $scope.watch() function is used to create a watch of some variable. When we register a watch, we pass two functions as parameters to the $watch() function:

  • A value function
  • A listener function
    An example is given below:

$scope.$watch(function() {},
function() {}
);
Here, the first function is the value function and the second function is the listener function.

In AngularJS, $watch is a function provided by the framework that allows you to monitor changes to a variable or expression and take action when the value changes. It is a part of the two-way data binding mechanism in AngularJS, which means that changes in the model (JavaScript variables or expressions) are automatically reflected in the view, and vice versa.

Here’s a brief explanation of how $watch works:

  1. Syntax:
    javascript
    $scope.$watch(watchExpression, listener, [objectEquality]);
  2. Parameters:
    • watchExpression: This is the expression to be observed for changes. It can be a variable, function, or an AngularJS expression.
    • listener: A function that gets called whenever the watchExpression changes. It receives two parameters – the new value and the old value of the watchExpression.
    • objectEquality (optional): A boolean parameter that indicates whether to do a deep watch (checking for changes inside objects) or a shallow watch (only checking for reference changes). If set to true, it performs a deep watch; if omitted or set to false, it performs a shallow watch.
  3. Usage:
    javascript
    $scope.$watch('variableName', function(newVal, oldVal) {
    // Do something when the variable changes
    });

    Alternatively, you can use a function as the watchExpression:

    javascripT
    $scope.$watch(function() {
    // Return the value or expression to be watched
    return $scope.variableName;
    }, function(newVal, oldVal) {
    // Do something when the variable changes
    });

The $watch function is commonly used in controllers, directives, or services to respond to changes in data and update the UI accordingly. However, it’s important to use it judiciously, as excessive use of $watch can lead to performance issues. In modern versions of Angular (after AngularJS), the usage of $watch has been significantly reduced in favor of more optimized mechanisms for change detection