JavaScript: Type annotations
In JavaScript, you can pass any values to a function. Sometimes this makes the code harder to understand: it is not always clear what the function expects and what it returns. JavaScript syntax itself has no type annotations, but there is a de facto standard — JSDoc: special comments placed before a function that editors and checking tools understand.
How to annotate parameter types
A JSDoc comment starts with /** and goes right before the function definition. Each parameter type is declared with the @param tag, and the return type with the @returns tag. The type itself is written in curly braces:
/**
* @param {number} a
* @param {number} b
* @returns {number}
*/
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // => 5Now the editor knows that add() takes two numbers and returns a number. If you try to pass a string, the editor will highlight it as a problem.
Which types are used
At this point, it is enough to know annotations for primitive types:
numberfor numbers — JavaScript has a single numeric type for both integers and floatsstringfor stringsbooleanfor logical values (trueorfalse)
If a function returns nothing, use void as the return type. For optional parameters with default values, the parameter name is wrapped in square brackets: @param {string} [greeting='Hello'].
Annotations and static checking
JavaScript itself does not check JSDoc annotations at runtime, but tools can do it without running the code — this is called static checking. In the JavaScript world, the TypeScript compiler can read plain JS files and understand types from JSDoc comments. Annotations are optional, but using them is considered good practice. When types grow numerous, developers often switch to TypeScript — a superset of JavaScript with annotations built into the syntax.
Instructions
The application builds text separators from repeating characters — for example, ------- or =====. Implement a wordMultiply() function. It takes two parameters:
- A string
- A number that tells how many times the string should be repeated
It returns the string repeated n times. If zero is passed, it returns an empty string.
const text = 'javascript';
console.log(wordMultiply(text, 2)); // => javascriptjavascript
console.log(wordMultiply(text, 0)); // =>Add JSDoc type annotations to the function definition: @param tags for both parameters and @returns for the return value.
Hints
- The string method repeat() is handy here
- Do not forget the annotation for the return value
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-nocheck -- tsconfig has no Node.js types (types: []), and the test reads the source via node:fs
import { readFileSync } from 'node:fs';
import { expect, test } from 'vitest';
import f from './index.js';
test('test', () => {
const source = readFileSync(new URL('./index.js', import.meta.url), 'utf8');
const paramAnnotations = source.match(/@param\s*\{/g) ?? [];
expect(
paramAnnotations.length,
'Add JSDoc @param annotations for both parameters',
).toBeGreaterThanOrEqual(2);
expect(
source,
'Add a JSDoc @returns annotation for the return value',
).toMatch(/@returns\s*\{/);
expect(f('javascript', 1)).toBe('javascript');
expect(f('javascript', 3)).toBe('javascriptjavascriptjavascript');
expect(f('java', 0)).toBe('');
});Teacher's solution will be available in:
20:00
