skip to Main Content
  function convertToFahrenheit(celsius) {
    return (celsius * 9 / 5) + 32;
  }

  function convertToCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5 / 9;
  }

  function convertTemperature(degrees, unit) {
    if (unit === 'C') {
      const result = convertToFahrenheit(degrees);    /* How can we use "degrees" here? */
      return `${result}F`;
    } else if (unit === 'F') {
      const result = convertToCelsius(degrees);       /* How can we use "degrees" here? */
      return `${result}C`;
    }
  }

  console.log(convertTemperature(25, 'C'));
  console.log(convertTemperature(86, 'F'));

As you can see in the above code, there were two functions defined – convertToFahrenheit(celsius) and convertToCelsius(fahrenheit). But later on, when these functions were called, there parameter names were changed to degrees. How is it possible?

At first, I thought that , when the functions were called inside the new function convertTemperature(degrees, unit), the argument passed for the convertToFahrenheit(celsius) and convertToCelsius(fahrenheit) was "degrees" itself. Am i correct?

2

Answers


  1. The arguments are called degrees. The parameters are called celcius and fahrenheit. The name of the argument does not need to match the name of the parameter. This should be especially obvious when you consider that an argument doesn’t need to be associated with a name at all:

    function func(param) {
      console.log(param);
    }
    
    func(1)  // The argument is not stored in a variable and has no associated name
    // Prints 1
    

    when the functions were called inside the new function . . ., the argument passed for the convertToFahrenheit(celsius) and convertToCelsius(fahrenheit) was "degrees" itself

    The object that degrees holds/points to is passed into, for example, convertToFahrenheit. That passed object is then stored inside the fahrenheit parameter variable. At that point, degrees and fahrenheit are two names that both refer to the same object.

    Login or Signup to reply.
  2. You’re correct, you’re passing ‘degrees’ into the function. Function calls do not require the actual name of the parameter, you just put the value, in this case a number.

    When you create a function, you use the parameter names as a stand in for the value you’re going to get when you call the function.

    See how on the bottom lines you use 25 and 86 in a function call. Then within that function it uses those numbers under the name degrees. Then it calls the top 2 functions which use those numbers under the names celsius and fahrenheit, but the whole time they are 25 and 86.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search