Functions receive inputs via parameters and send outputs back to the caller via return values. Mastering parameter defaults, rest parameters, and return semantics is essential for writing robust JavaScript functions.
1. Parameters vs. Arguments
While often used interchangeably in casual conversation, there is a clear distinction:
Parameters: The variable names listed in the function definition.
Arguments: The real values passed into the function when you invoke it.
1// 'base' and 'exponent' are PARAMETERS:
2functionpower(base, exponent){
3return base ** exponent;
4}
5
6// 2 and 3 are ARGUMENTS:
7const result =power(2,3);
2. The return Statement
The return statement does two things:
1
It immediately stops the execution of the function.
2
It sends the evaluated value back to the caller.
1functioncalculateTax(subtotal, taxRate){
2if(subtotal <=0){
3return0;// Exits early!
4}
5
6return subtotal * taxRate;
7}
8
9const tax =calculateTax(1000,0.18);// 180
[!IMPORTANT]
If a function does not have an explicit return statement (or has an empty return;), it automatically returns undefined!
1functiondoNothing(){}
2console.log(doNothing());// undefined
3. Default Parameters (ES6)
What happens if a caller forgets to pass an argument? Without defaults, missing arguments become undefined. In ES6, you can specify default values directly in the parameter list:
1functioncreateAccount(username, role ="Student", isActive =true){
What does a JavaScript function return by default if it lacks an explicit return statement?
Question 2
What is the difference between a parameter and an argument?
Question 3
What is the value of tax if invoked as calculateTotal(500) where the function is defined as function calculateTotal(price, tax = 0.1) { return price * tax; }?
Question 4
Which operator allows a function to collect an indefinite number of arguments into a single array?
Question 5
Can code written after a return statement in the same execution branch ever execute?
Next Lesson
Arrow Functions (Basic)
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.