2

I have some javascript that a prior developer had updated. It looks like they wrapped the code within the function with another function prefixed with a '+'. After some research, another SO post mentioned that it's used to treat the inner following function as an expression, but I'm not sure what the purpose is of it in this context.

Before

onCartClick: function() {
    $(this).parent().parent().find('.cart-loader').removeClass('hide');
    $('.cart-text').removeClass('hide');}, 4000);
}

After

onCartClick: function() {
    +function($) {
        $(this).parent().parent().find('.cart-loader').removeClass('hide');
        $('.cart-text').removeClass('hide');}, 4000);
    } (jQuery);
}

I'm trying to understand why the change was made and cannot contact the previous developer to find out what their intention was. The "Before" code works as the functions "this" returns the element that received the event. The "After" code doesn't, as the function's "this" returns the window object.

Is there a valid reason for trying to do things this way?

Milktea
  • 131
  • 8

1 Answers1

3

Without + before it would be considered a function declaration. If you see there is no name so the code will throw error. We need to make it an expression using +. You also use other operators like !.

Its another way to using IIFE. The code is almost same as

onCartClick: function() {
    (function($) {
        $(this).parent().parent().find('.cart-loader').removeClass('hide');
        $('.cart-text').removeClass('hide');}, 4000);
    }) (jQuery);
}
Maheer Ali
  • 32,967
  • 5
  • 31
  • 51