Learn Intermediate JavaScript Using Object Destructuring

Hi everyone!

I am reading the article in the javascript modules chapter: https://www.codecademy.com/courses/learn-intermediate-javascript/articles/implementing-modules-in-node

and I am struggling to understand the "Using object destructuring to be more selective with require() part.

The article says that the code snippet extracts the celsiusToFahrenheit() method and leaves fahrenheitToCelsius() behind.

/* celsius-to-fahrenheit.js */
const { celsiusToFahrenheit } = require('./converters.js');
 
const celsiusInput = process.argv[2]; 
const fahrenheitValue = celsiusToFahrenheit(celsiusInput);
 
console.log(`${celsiusInput} degrees Celsius = ${fahrenheitValue} degrees Fahrenheit`);

So it seems like the require() part is importing the converters.js, which is containing celsiusToFahrenheit function and fahrenheitToCelsius function. How does assigning this to const ( celsiusToFahrenheit } result in extracting celsiusToFahrenheit()?

/* converters.js */
function celsiusToFahrenheit(celsius) {
  return celsius * (9/5) + 32;
}
 
module.exports.celsiusToFahrenheit = celsiusToFahrenheit;
 
module.exports.fahrenheitToCelsius = function(fahrenheit) {
  return (fahrenheit - 32) * (5/9);
};

This is the converters.js code just in case the link doesn’t work.

I think the key part to understand is this first approach:
const { celsiusToFahrenheit } = require('./converters.js');

vs this second approach:

const converters = require('./converters.js');

The first approach uses deconstructing so you can see it specifies the function in the curly brackets to require. In this case it specifies { celsiusToFahrenheit }. So it will go and look for the function name that matches in an export inside the conveerters.js file - which it finds on this line: module.exports.celsiusToFahrenheit = celsiusToFahrenheit;

The second approach does not use deconstructing and does not have the curly brackets which will make available to all the functions from the converters.js.

Thank you for the comparison! I thought const { celsiusToFahrenheit } destructured the function celsiusToFahrenheit so I was not getting how would this result in solely importing celsiusToFahrenheit function. Have a great day :grinning:

1 Like