tpdx49
tpdx49

Reputation: 25

Why do some angular $scope functions "return" an operation?

I've come across some code that looks like this:

$scope.open = function($event) {
    $event.preventDefault();
    $event.stopPropagation();
    return $scope.opened = true;
 };

Why is this returning an assignment? What does this do? Is there a benefit to doing or not doing this?

Upvotes: 2

Views: 60

Answers (3)

Sid
Sid

Reputation: 7631

I agree with Douglas's answer that it's not worth it. In fact I would go as far as saying that it's obfuscated coding. It's one thing to return something like return x===y in which case you are actually comparing x and y and returning true if they are equal and false otherwise. But returning the result of an assignment doesn't make much sense.

Upvotes: 0

Douglas
Douglas

Reputation: 37761

It is basically:

$scope.open = function($event) {
    $event.preventDefault();
    $event.stopPropagation();
    $scope.opened = true;
    return $scope.opened;
 };

So the benefit is that it saves one line of code. Probably not worth it.

It might also be compiled CoffeeScript code, which originally looked like:

$scope.open = ($event) ->
    $event.preventDefault()
    $event.stopPropagation()
    $scope.opened = true

CoffeeScript always returns the result of the last line in a method, so it may return values from functions which you'd expect to not normally return anything.

Upvotes: 1

dave
dave

Reputation: 64667

This will make the function return true, while at the same time setting $scope.opened to true. It is equivalent to doing

$scope.opened = true;
return true;

Upvotes: 0

Related Questions