How to use the defaultTo function from lodash

Find comprehensive JavaScript lodash.defaultTo code examples handpicked from public code repositorys.

lodash.defaultTo is a function that returns the first argument if it is not null or undefined, otherwise it returns the second argument.

33
34
35
36
37
38
39
40
41
42
const phase = {
  id: uuid(),
  phaseId: phaseFromTemplate.phaseId,
  name: phaseDefinition.name,
  description: phaseDefinition.description,
  duration: _.defaultTo(_.get(phaseFromInput, "duration"), phaseFromTemplate.defaultDuration),
  isOpen: false,
  predecessor: phaseFromTemplate.predecessor,
  constraints: _.defaultTo(_.get(phaseFromInput, "constraints"), []),
  scheduledStartDate: undefined,
fork icon44
star icon17
watch icon25

+ 19 other calls in file

893
894
895
896
897
898
899
900
901
902
903
904
905
console.log(cond({ 'a': 1, 'b': 2 })); // => 'matches A'


const constant = _.constant(1);
console.log(constant); // => 1


const defaultTo = _.defaultTo(1, 10);
console.log(defaultTo); // => 1


const flow = _.flow([function(n) { return n * 3; }, function(n) { return n + 1; }]);
console.log(flow(1)); // => 4
fork icon0
star icon4
watch icon0

+ 15 other calls in file

How does lodash.defaultTo work?

lodash.defaultTo is a function that takes two arguments, a value and a default value, and returns the value if it is not null or undefined, otherwise it returns the default value. If the value is a NaN, it will return the default value as well.

669
670
671
672
673
674
675
676
677
678
// based on the existingInfo properties
// merge in the commitParams if null or undefined
// defaulting back to null if all fails
// NOTE: only properties defined in "existingInfo" will be returned
const combined = _.transform(existingInfo, (memo, value, key) => {
  return memo[key] = _.defaultTo(value || commitParamsObj[key], null)
})

debug('combined git and environment variables from provider')
debug(combined)
fork icon0
star icon0
watch icon622

+ 4 other calls in file

Ai Example

1
2
3
4
5
6
7
8
const _ = require("lodash");

// If `value` is falsy, then it will be replaced with the default value 42.
const result1 = _.defaultTo(undefined, 42); // result1 will be 42
const result2 = _.defaultTo(null, 42); // result2 will be null
const result3 = _.defaultTo(0, 42); // result3 will be 0
const result4 = _.defaultTo(false, 42); // result4 will be false
const result5 = _.defaultTo("hello", 42); // result5 will be 'hello'

In this example, lodash.defaultTo is used to provide a default value in case the input value is falsy. The first argument is the value to check, and the second argument is the default value to use if the first argument is falsy.

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)