1

I want to call a callback function if one was provided by the user, or default to a default defaultCallback function.

I've done it as follows:

function defaultCallback(x) {
  console.log('default callback ' + x)
}

function test(callback) {
  let x = 'x'

  if (callback) {
    callback(x)
  } else {
    defaultCallback(x)
  }
}

I feel there should be a more concise way of doing this?

Juicy
  • 11,840
  • 35
  • 123
  • 212

3 Answers3

2

You can just use || operator to get callback or fallback to defaultCallback.

function test(callback) {
   (callback || defaultCallback)('x')
}

Here is a test snippet you can use to view the results in the console.

function defaultCallback(x) { console.log('Used default ' + x); }

function test(callback) {
  (callback || defaultCallback)('x')
}

test(undefined);
test((y) => console.log('Used func ' + y));
Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70
1

I think you're looking for the conditional operator:

function test(callback) {
  let x = 'x'

  (typeof callback == "function" ? callback : defaultCallback)(x);
}

Alternatively, if you don't want to check the type of the argument, but just assert that it's something else than undefined, you can use a default initialiser in your parameter:

function test(callback = defaultCallback) {
  let x = 'x'

  callback(x);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

How about:

function test(callback) {
  let x = 'x'

  callback ? callback(x) : defaultCallBack(x);
}
RicardoAgra
  • 600
  • 1
  • 3
  • 13