Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the plus sign before a function? [duplicate]

Here is the JS code from bootstrap.js

/* ========================================================================
 * Bootstrap: collapse.js v3.1.1
 * http://getbootstrap.com/javascript/#collapse
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // COLLAPSE PUBLIC CLASS DEFINITION
  // ================================
   ...
  }

I've seen ";" before a function to avoid mixing code before the function definition. But what does the "+" sign mean before the function mean? Is it going to convert the return to String?

like image 241
Nicolas S.Xu Avatar asked Mar 11 '14 06:03

Nicolas S.Xu


1 Answers

It is normally used with IIFE/SIFE. When you use + sign like that, it evaluates the expression following that, so when you put it in a function, it executes even an anonymous function, like this

+function(){
    console.log("Welcome");
}()

Output

Welcome

It is another way to get the same behavior when the entire function is enclosed with parenthesis, like this

(function(){
    console.log("Welcome");
}());

Note: Not only +, any unary arithmetic operator will give the same result.

like image 74
thefourtheye Avatar answered Nov 11 '22 03:11

thefourtheye