How to set default values for the parameters of a function in JavaScript

2 Answers

0 votes
const func = (id = 657321, name = 'R2D2') => {
    console.log(id + " : " + name);
};
 
func();
func(9999);
func(8888, 'Harry');
func(undefined); 
 
  
  
/*
run:
            
657321 : R2D2
9999 : R2D2
8888 : Harry
657321 : R2D2
      
*/

 



answered Nov 6, 2019 by avibootz
edited Nov 24, 2025 by avibootz
0 votes
function calculateArea(length = 1, width = 1) {
    return length * width;
}

console.log(calculateArea()); // Output: 1 (1 * 1)
console.log(calculateArea(5)); // Output: 5 (5 * 1)
console.log(calculateArea(5, 10)); // Output: 50 (5 * 10)
console.log(calculateArea(undefined, 7)); // Output: 7 (1 * 7)

 

/*
run:
           
1
5
50
7
     
*/

 



answered Nov 24, 2025 by avibootz
...