JavaScript: Modules
As long as a program is small, all the code can live in a single file. This approach is convenient for simple examples and small tasks. But over time a program starts to grow. When there is a lot of code, it becomes hard to navigate a single file. Real applications consist of tens of thousands of lines (at least) and hundreds of files.
To split a program into separate logical parts, JavaScript uses modules. A separate file with code is a module. The language provides mechanisms that let one file use functions and constants from another.
export and import
A module decides what to expose. The export keyword is used for this. Another file pulls in what was exported via import.
You have probably already seen lines like this at the beginning of some exercises — now let's figure out what they mean:
import { length } from 'hexlet-basics/string';
console.log(length('Hello!')); // => 6This line connects the length function from the hexlet-basics/string module and makes it available in the current file.
Named imports
You can import several names from one module at once by listing them in curly braces:
import { reverse, toUpperCase } from 'hexlet-basics/string';
console.log(reverse('hexlet')); // => telxeh
console.log(toUpperCase('hexlet')); // => HEXLETAfter such an import, you call the functions directly, by their names. This is convenient: you don't have to specify which module a function came from every time.
Default export
To export something, a module marks it with the word export. There are two kinds of export. A named one — there can be as many exported names as you like:
// string.js
const reverse = (s) => s.split('').reverse().join('');
const length = (s) => s.length;
export { reverse, length };And a default export — a module can have only one of those. You have already come across it when defining functions:
// sum.js
const sum = (a, b) => a + b;
export default sum;A default import is written without curly braces, and you may pick any name for it:
import sum from './sum.js';
console.log(sum(2, 3)); // => 5Renaming on import
Sometimes a name from a module is already taken in the current file. To avoid a conflict, an import can be renamed with as:
import { reverse as reverseString } from 'hexlet-basics/string';
console.log(reverseString('hexlet')); // => telxehNow the function is available under the name reverseString, while the original name reverse stays free.
Standard modules
Every language ships with a set of ready-made functions. In JavaScript, most of them are available globally and need no import — for example, the Math object for math or console for output.
But JavaScript runs in different environments. The Node.js server environment has built-in modules that need to be imported. They are imported with the node: prefix — for example, the node:fs module for working with files:
import { readFile } from 'node:fs/promises';Ready-made functions can be taken not only from standard modules but also from third-party ones. We'll talk about how those are distributed in the next lesson.
Instructions
Implement the mirror() function. It takes a string, reverses it, and converts it to upper case, then returns the result.
Use the reverse() and toUpperCase() functions from the hexlet-basics/string module. You need to write the import yourself.
mirror('hello'); // => 'OLLEH'
mirror('Hexlet'); // => 'TELXEH'Hint
- At the beginning of the file, import the functions you need:
import { reverse, toUpperCase } from 'hexlet-basics/string'; - First reverse the string, then convert the result to upper case
Tips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
// @ts-check
import { expect, test } from 'vitest';
import mirror from './index.js';
test('mirror', () => {
expect(mirror('hello')).toBe('OLLEH');
expect(mirror('Hexlet')).toBe('TELXEH');
});Teacher's solution will be available in:
20:00
