bind

_.bind(function, object, *arguments) source

Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, pass arguments to the function to pre-fill them, also known as partial application. For partial application without context binding, use partial.

  1. var func = function(greeting){ return greeting + ': ' + this.name };
  2. func = _.bind(func, {name: 'moe'}, 'hi');
  3. func();
  4. => 'hi: moe'

bindAll

_.bindAll(object, *methodNames) source

Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. methodNames are required.

  1. var buttonView = {
  2. label : 'underscore',
  3. onClick: function(){ alert('clicked: ' + this.label); },
  4. onHover: function(){ console.log('hovering: ' + this.label); }
  5. };
  6. _.bindAll(buttonView, 'onClick', 'onHover');
  7. // When the button is clicked, this.label will have the correct value.
  8. jQuery('#underscore_button').on('click', buttonView.onClick);

partial

_.partial(function, *arguments) source

Partially apply a function by filling in any number of its arguments, without changing its dynamic this value. A close cousin of bind. You may pass _ in your list of arguments to specify an argument that should not be pre-filled, but left open to supply at call-time. Note: if you need placeholders and a this binding at the same time, use both _.partial and _.bind_.

  1. var subtract = function(a, b) { return b - a; };
  2. sub5 = _.partial(subtract, 5);
  3. sub5(20);
  4. => 15
  5. // Using a placeholder
  6. subFrom20 = _.partial(subtract, _, 20);
  7. subFrom20(5);
  8. => 15

memoize

_.memoize(function, [hashFunction]) source

Memoizes a given function by caching the computed result. Useful for speeding up slow-running computations. If passed an optional hashFunction, it will be used to compute the hash key for storing the result, based on the arguments to the original function. The default hashFunction just uses the first argument to the memoized function as the key. The cache of memoized values is available as the cache property on the returned function.

  1. var fibonacci = _.memoize(function(n) {
  2. return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
  3. });

delay

_.delay(function, wait, *arguments) source

Much like setTimeout, invokes function after wait milliseconds. If you pass the optional arguments, they will be forwarded on to the function when it is invoked.

  1. var log = _.bind(console.log, console);
  2. _.delay(log, 1000, 'logged later');
  3. => 'logged later' // Appears after one second.

defer

_.defer(function, *arguments) source

Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating. If you pass the optional arguments, they will be forwarded on to the function when it is invoked.

  1. _.defer(function(){ alert('deferred'); });
  2. // Returns from the function before the alert runs.

throttle

_.throttle(function, wait, [options]) source

Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

By default, throttle will execute the function as soon as you call it for the first time, and, if you call it again any number of times during the wait period, as soon as that period is over. If you’d like to disable the leading-edge call, pass {leading: false}, and if you’d like to disable the execution on the trailing-edge, pass
{trailing: false}.

  1. var throttled = _.throttle(updatePosition, 100);
  2. $(window).scroll(throttled);

If you need to cancel a scheduled throttle, you can call .cancel() on the throttled function.

debounce

_.debounce(function, wait, [immediate]) source

Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.

At the end of the wait interval, the function will be called with the arguments that were passed most recently to the debounced function.

Pass true for the immediate argument to cause debounce to trigger the function on the leading instead of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double-clicks on a “submit” button from firing a second time.

  1. var lazyLayout = _.debounce(calculateLayout, 300);
  2. $(window).resize(lazyLayout);

If you need to cancel a scheduled debounce, you can call .cancel() on the debounced function.

once

_.once(function) source

Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.

  1. var initialize = _.once(createApplication);
  2. initialize();
  3. initialize();
  4. // Application is only created once.

after

_.after(count, function) source

Creates a wrapper of function that does nothing at first. From the count-th call onwards, it starts actually calling function. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.

  1. var renderNotes = _.after(notes.length, render);
  2. _.each(notes, function(note) {
  3. note.asyncSave({success: renderNotes});
  4. });
  5. // renderNotes is run once, after all notes have saved.

before

_.before(count, function) source

Creates a wrapper of function that memoizes its return value. From the count-th call onwards, the memoized result of the last invocation is returned immediately instead of invoking function again. So the wrapper will invoke function at most count - 1 times.

  1. var monthlyMeeting = _.before(3, askForRaise);
  2. monthlyMeeting();
  3. monthlyMeeting();
  4. monthlyMeeting();
  5. // the result of any subsequent calls is the same as the second call

wrap

_.wrap(function, wrapper) source

Wraps the first function inside of the wrapper function, passing it as the first argument. This allows the wrapper to execute code before and after the function runs, adjust the arguments, and execute it conditionally.

  1. var hello = function(name) { return "hello: " + name; };
  2. hello = _.wrap(hello, function(func) {
  3. return "before, " + func("moe") + ", after";
  4. });
  5. hello();
  6. => 'before, hello: moe, after'

negate

_.negate(predicate) source

Returns a new negated version of the predicate function.

  1. var isFalsy = _.negate(Boolean);
  2. _.find([-2, -1, 0, 1, 2], isFalsy);
  3. => 0

compose

_.compose(*functions) source

Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

  1. var greet = function(name){ return "hi: " + name; };
  2. var exclaim = function(statement){ return statement.toUpperCase() + "!"; };
  3. var welcome = _.compose(greet, exclaim);
  4. welcome('moe');
  5. => 'hi: MOE!'

restArguments

_.restArguments(function, [startIndex]) source

Returns a version of the function that, when called, receives all arguments from and beyond startIndex collected into a single array. If you don’t pass an explicit startIndex, it will be determined by looking at the number of arguments to the function itself. Similar to ES6’s rest parameters syntax.

  1. var raceResults = _.restArguments(function(gold, silver, bronze, everyoneElse) {
  2. _.each(everyoneElse, sendConsolations);
  3. });
  4. raceResults("Dopey", "Grumpy", "Happy", "Sneezy", "Bashful", "Sleepy", "Doc");