7

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?

Nicolas S.Xu
  • 13,794
  • 31
  • 84
  • 129

2 Answers2

10

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

It's called unary plus operator:

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. For example, y = +x takes the value of x and assigns that to y; that is, if x were 3, y would get the value 3 and x would retain the value 3; but if x were the string "3", y would also get the value 3

Richard de Wit
  • 7,102
  • 7
  • 44
  • 54
Felix
  • 37,892
  • 8
  • 43
  • 55