question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

callback && callback();

See original GitHub issue

Was reading through the style guide, but couldn’t find anything about this. Instead of

var callback;

if (callback) {
    callback();
}

I’ve started using

var callback;

callback && callback();

Which I haven’t found any issues with. Would this style guide frown upon this?

Issue Analytics

  • State:closed
  • Created 11 years ago
  • Reactions:3
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
netpoeticacommented, Apr 6, 2014

I don’t think either one adequately covers safely attempting to run your callback

if(typeof callback === 'function'){
  callback();
}

is what I use to be safe. I don’t think a simple null check is a good idea especially when the arguments are variable or when you intend to use arguments[arguments.length - 1] convention:

function myFn(firstName, lastName){
  var name = firstName + " " + lastName;

  // Is the last argument a callback function?
  var callback = arguments[arguments.length - 1];

  // If it is, use it, otherwise, technically callback is just a string equivalent to lastName.
  if(typeof callback === 'function'){
    callback(name);
  }
  return name;
}
myFn("Keith", "Rosenberg")
// "Keith Rosenberg"
myFn("Keith", "Rosenberg", function(name){ console.log("Callback: " + name); });
// Callback: Keith Rosenberg 

Otherwise:

function myFn(firstName, lastName){
  var name = firstName + " " + lastName;

  // Is the last argument a callback function?
  var callback = arguments[arguments.length - 1];

  // If it is, use it, otherwise, technically callback is just a string equivalent to lastName.
  if(callback){
    callback(name);
  }
  return name;
}
myFn("Keith", "Rosenberg")
// TypeError: string is not a function
3reactions
ssorallencommented, Mar 12, 2014

This leads to an error in JSLint and a warning in JSHint, "Expected an assignment or function call and instead saw an expression”. As JSLint explains its expr option:

This option suppresses warnings about the use of expressions where normally you would expect to see assignments or function calls. Most of the time, such code is a typo. However, it is not forbidden by the spec and that’s why this warning is optional.

The warning is useful and worth enabling as it does catch typos like JSLint explains. The line you wrote, callback && callback(); is an expression and not a function call. This may be contrived, but take code similar to your example:

var shouldCallCallback = (Math.random() > 0.5);
shouldCallCallback && callback;

JSLint will give the same warning for the code, and this time it caught a typo: callback is not actually being called, it’s missing parentheses. This code would raise the same warning for the same reason:

var shouldCallCallback = (Math.random() > 0.5);
if (shouldCallCallback) {
  callback;
}

The second example would likely be more quickly noticed by the developer, but again JSLint/JSHint is able to point it out. I find using an explicit if more readable for the next developer too. The intention of the conditional in that case is unmistakable whereas callback && callback(); or something like it is not as straightforward.

There is nothing “wrong” with writing callback && callback(); in the sense that it will run just fine. However, I am a fan of keeping it out of the style guide because endorsing a pattern that looks the same as a typo to tools can lead to frustrating debugging and code that is harder to read for the next developer.

Read more comments on GitHub >

github_iconTop Results From Across the Web

JavaScript Callbacks - W3Schools
A callback is a function passed as an argument to another function. Using a callback, you could call the calculator function ( myCalculator...
Read more >
Callback function - MDN Web Docs Glossary: Definitions of ...
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete...
Read more >
tf.keras.callbacks.Callback | TensorFlow v2.11.0
Abstract base class used to build new callbacks. ... Callback() ... Callbacks can be passed to keras methods such as fit , evaluate...
Read more >
Callbacks API - Keras
A callback is an object that can perform actions at various stages of training (e.g. at the start or end ... Usage of...
Read more >
JavaScript Callback Functions – What are Callbacks in JS and ...
Callbacks make sure that a function is not going to run before a task is completed but will run right after the task...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found