How to set a default value to function parameters in JavaScript

2 Answers

0 votes
function sum(x = 2, y = 9) {
    return x + y;
}

console.log(sum(3, 12)); // 3 + 12
console.log(sum(8)); // 8 + 9
console.log(sum()); // 2 + 9





      
/*
run:
      
15
17
11
      
*/

 



answered Jan 26, 2022 by avibootz
0 votes
function multiply(a, b = 2) {
  	return a * b;
}

console.log(multiply(7, 8));

console.log(multiply(4));





      
/*
run:
      
56
8
      
*/

 



answered Jan 26, 2022 by avibootz

Related questions

...