diff --git a/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md b/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md index 4facc8b29..2e6870983 100644 --- a/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md +++ b/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md @@ -1,48 +1,48 @@ -You could note the following: +Měli byste si všimnout následujícího: ```js no-beautify -function pow(x,n) // <- no space between arguments -{ // <- figure bracket on a separate line - let result=1; // <- no spaces before or after = - for(let i=0;i -Now let's discuss the rules and reasons for them in detail. +Nyní si tato pravidla a jejich důvody probereme podrobně. -```warn header="There are no \"you must\" rules" -Nothing is set in stone here. These are style preferences, not religious dogmas. +```warn header="Toto nejsou žádná povinná pravidla" +Nic tady není zasazeno do kamene. Toto jsou stylové preference, ne náboženská dogmata. ``` -### Curly Braces +### Složené závorky -In most JavaScript projects curly braces are written in "Egyptian" style with the opening brace on the same line as the corresponding keyword -- not on a new line. There should also be a space before the opening bracket, like this: +Ve většině JavaScriptových projektů se složené závorky píší „egyptským“ stylem, kdy je levá závorka na stejném řádku jako odpovídající klíčové slovo -- ne na novém řádku. Před levou závorkou by také měla být mezera, jako zde: ```js -if (condition) { - // do this - // ...and that - // ...and that +if (podmínka) { + // dělej tohle + // ...a tohle + // ...a tohle } ``` -A single-line construct, such as `if (condition) doSomething()`, is an important edge case. Should we use braces at all? +Důležitým krajním případem je jednořádková konstrukce, například `if (podmínka) dělejNěco()`. Měli bychom vůbec použít závorky? -Here are the annotated variants so you can judge their readability for yourself: +Uvádíme jednotlivé varianty s komentářem, takže můžete sami posoudit jejich čitelnost: -1. 😠 Beginners sometimes do that. Bad! Curly braces are not needed: +1. 😠 Začátečníci někdy píší takto. Špatně! Složené závorky nejsou zapotřebí: ```js - if (n < 0) *!*{*/!*alert(`Power ${n} is not supported`);*!*}*/!* + if (n < 0) *!*{*/!*alert(`${n}-tá mocnina není podporována`);*!*}*/!* ``` -2. 😠 Split to a separate line without braces. Never do that, easy to make an error when adding new lines: +2. 😠 Umístění na samostatný řádek bez složených závorek. Tohle nikdy nedělejte, jelikož snadno uděláte chybu, když budete přidávat další řádky: ```js if (n < 0) - alert(`Power ${n} is not supported`); + alert(`${n}-tá mocnina není podporována`); ``` -3. 😏 One line without braces - acceptable, if it's short: +3. 😏 Jeden řádek bez složených závorek - to je přijatelné, pokud je krátký: ```js - if (n < 0) alert(`Power ${n} is not supported`); + if (n < 0) alert(`${n}-tá mocnina není podporována`); ``` -4. 😃 The best variant: +4. 😃 Nejlepší varianta: ```js if (n < 0) { - alert(`Power ${n} is not supported`); + alert(`${n}-tá mocnina není podporována`); } ``` -For a very brief code, one line is allowed, e.g. `if (cond) return null`. But a code block (the last variant) is usually more readable. +Pro velmi krátký kód je dovolen jeden řádek, např. `if (podmínka) return null`. Ale kódový blok (poslední uvedená varianta) bývá obvykle čitelnější. -### Line Length +### Délka řádku -No one likes to read a long horizontal line of code. It's best practice to split them. +Nikdo není rád, když musí číst dlouhý vodorovný řádek kódu. Lepší přístup je rozdělit jej. -For example: +Například: ```js -// backtick quotes ` allow to split the string into multiple lines -let str = ` - ECMA International's TC39 is a group of JavaScript developers, - implementers, academics, and more, collaborating with the community - to maintain and evolve the definition of JavaScript. +// zpětné uvozovky ` umožňují rozdělit řádek na více řádků +let řetězec = ` + TC39 v ECMA International je skupina JavaScriptových vývojářů, + implementátorů, akademiků a dalších, kteří spolupracují s komunitou, + aby udržovali a rozvíjeli definici JavaScriptu. `; ``` -And, for `if` statements: +A pro příkazy `if`: ```js if ( id === 123 && - moonPhase === 'Waning Gibbous' && - zodiacSign === 'Libra' + měsíčníFáze === 'Ubývání' && + znameníZvěrokruhu === 'Váhy' ) { - letTheSorceryBegin(); + začniKouzlo(); } ``` -The maximum line length should be agreed upon at the team-level. It's usually 80 or 120 characters. +Na maximální délce řádku by se měl dohodnout celý tým. Obvykle bývá 80 nebo 120 znaků. -### Indents +### Odsazení -There are two types of indents: +Existují dva druhy odsazení: -- **Horizontal indents: 2 or 4 spaces.** +- **Vodorovné odsazení: 2 nebo 4 mezery.** - A horizontal indentation is made using either 2 or 4 spaces or the horizontal tab symbol (key `key:Tab`). Which one to choose is an old holy war. Spaces are more common nowadays. + Vodorovné odsazení se dělá pomocí 2 nebo 4 mezer nebo pomocí vodorovného symbolu tabulátoru (klávesa `key:Tab`). O tom, které zvolit, se už dlouho vedou svaté války. V dnešní době se více používají mezery. - One advantage of spaces over tabs is that spaces allow more flexible configurations of indents than the tab symbol. + Výhodou mezer oproti tabulátorům je, že mezery umožňují konfigurovat odsazení flexibilněji než symbol tabulátoru. - For instance, we can align the parameters with the opening bracket, like this: + Můžeme například zarovnat parametry k levé závorce takto: ```js no-beautify - show(parameters, - aligned, // 5 spaces padding at the left - one, - after, - another + zobraz(parametry, + zarovnané, // vlevo je odsazení 7 mezer + jeden, + za, + druhým ) { // ... } ``` -- **Vertical indents: empty lines for splitting code into logical blocks.** +- **Svislé odsazení: prázdné řádky pro rozdělení kódu do logických bloků.** - Even a single function can often be divided into logical blocks. In the example below, the initialization of variables, the main loop and returning the result are split vertically: + I jediná funkce může být často rozdělena do logických bloků. V níže uvedeném příkladu jsou svisle odděleny inicializace proměnných, hlavní smyčka a vrácení výsledku: ```js - function pow(x, n) { - let result = 1; + function mocnina(x, n) { + let výsledek = 1; // <-- for (let i = 0; i < n; i++) { - result *= x; + výsledek *= x; } // <-- - return result; + return výsledek; } ``` - Insert an extra newline where it helps to make the code more readable. There should not be more than nine lines of code without a vertical indentation. + Vkládejte prázdný nový řádek všude, kde pomáhá učinit kód čitelnějším. V kódu by nemělo být více než devět řádků za sebou bez svislého odsazení. -### Semicolons +### Středníky -A semicolon should be present after each statement, even if it could possibly be skipped. +Středník by měl být uveden za každým příkazem, i kdyby mohl být vynechán. -There are languages where a semicolon is truly optional and it is rarely used. In JavaScript, though, there are cases where a line break is not interpreted as a semicolon, leaving the code vulnerable to errors. See more about that in the chapter . +Existují jazyky, v nichž je středník zcela dobrovolný a používá se jen zřídka. V JavaScriptu však existují případy, kdy se zlom řádku neinterpretuje jako středník, čímž se kód stává náchylnějším k chybám. Více o tom se píše v kapitole . -If you're an experienced JavaScript programmer, you may choose a no-semicolon code style like [StandardJS](https://standardjs.com/). Otherwise, it's best to use semicolons to avoid possible pitfalls. The majority of developers put semicolons. +Jste-li zkušený programátor v JavaScriptu, můžete se rozhodnout pro bezstředníkový kódovací styl, např. [StandardJS](https://standardjs.com/). Jinak je však lepší středníky používat, abyste se vyhnuli možným úskalím. Většina vývojářů středníky uvádí. -### Nesting Levels +### Úrovně vnoření -Try to avoid nesting code too many levels deep. +Snažte se vyhnout příliš mnoha úrovním vnoření. -For example, in the loop, it's sometimes a good idea to use the [`continue`](info:while-for#continue) directive to avoid extra nesting. +Například v cyklu je někdy dobrý nápad použít direktivu [`continue`](info:while-for#continue), abychom se vyhnuli dalšímu vnoření. -For example, instead of adding a nested `if` conditional like this: +Například místo použití vnořené podmínky `if` tímto způsobem: ```js for (let i = 0; i < 10; i++) { - if (cond) { - ... // <- one more nesting level + if (podmínka) { + ... // <- o jednu úroveň vnoření víc } } ``` -We can write: +můžeme napsat: ```js for (let i = 0; i < 10; i++) { - if (!cond) *!*continue*/!*; - ... // <- no extra nesting level + if (!podmínka) *!*continue*/!*; + ... // <- žádná další úroveň vnoření } ``` -A similar thing can be done with `if/else` and `return`. +Podobně můžeme postupovat s `if/else` a `return`. -For example, two constructs below are identical. +Například dvě níže uvedené konstrukce jsou identické. -Option 1: +Možnost 1: ```js -function pow(x, n) { +function mocnina(x, n) { if (n < 0) { - alert("Negative 'n' not supported"); + alert("Záporné 'n' není podporováno"); } else { - let result = 1; + let výsledek = 1; for (let i = 0; i < n; i++) { - result *= x; + výsledek *= x; } - return result; + return výsledek; } } ``` -Option 2: +Možnost 2: ```js -function pow(x, n) { +function mocnina(x, n) { if (n < 0) { - alert("Negative 'n' not supported"); + alert("Záporné 'n' není podporováno"); return; } - let result = 1; + let výsledek = 1; for (let i = 0; i < n; i++) { - result *= x; + výsledek *= x; } - return result; + return výsledek; } ``` -The second one is more readable because the "special case" of `n < 0` is handled early on. Once the check is done we can move on to the "main" code flow without the need for additional nesting. +Druhá konstrukce je čitelnější, protože „zvláštní případ“ `n < 0` je ošetřen hned na začátku. Když je kontrola provedena, můžeme se přesunout k „hlavnímu“ toku kódu, aniž bychom potřebovali další vnoření. -## Function Placement +## Umístění funkcí -If you are writing several "helper" functions and the code that uses them, there are three ways to organize the functions. +Jestliže píšeme několik „pomocných“ funkcí a kód, který je používá, tak máme tři možnosti, jak funkce organizovat. -1. Declare the functions *above* the code that uses them: +1. Deklarovat funkce *před* kódem, který je používá: ```js - // *!*function declarations*/!* - function createElement() { + // *!*deklarace funkcí*/!* + function vytvořPrvek() { ... } - function setHandler(elem) { + function nastavHandler(prvek) { ... } - function walkAround() { + function choďKolem() { ... } - // *!*the code which uses them*/!* - let elem = createElement(); - setHandler(elem); - walkAround(); + // *!*kód, který je používá*/!* + let prvek = vytvořPrvek(); + nastavHandler(prvek); + choďKolem(); ``` -2. Code first, then functions +2. Nejprve kód, pak funkce: ```js - // *!*the code which uses the functions*/!* - let elem = createElement(); - setHandler(elem); - walkAround(); + // *!*kód, který používá funkce*/!* + let prvek = vytvořPrvek(); + nastavHandler(prvek); + choďKolem(); - // --- *!*helper functions*/!* --- - function createElement() { + // --- *!*pomocné funkce*/!* --- + function vytvořPrvek() { ... } - function setHandler(elem) { + function nastavHandler(prvek) { ... } - function walkAround() { + function choďKolem() { ... } ``` -3. Mixed: a function is declared where it's first used. +3. Směs: funkce je deklarována tam, kde je poprvé použita. -Most of time, the second variant is preferred. +Ve většině případů se dává přednost druhé variantě. -That's because when reading code, we first want to know *what it does*. If the code goes first, then it becomes clear from the start. Then, maybe we won't need to read the functions at all, especially if their names are descriptive of what they actually do. +Je to proto, že při čtení kódu chceme nejdříve vědět, *co kód dělá*. Pokud je kód uveden jako první, bude to zřejmé od začátku. Pak možná nebudeme muset funkce vůbec číst, zvláště pokud je z jejich názvů dostatečně jasné, co dělají. -## Style Guides +## Styloví průvodci -A style guide contains general rules about "how to write" code, e.g. which quotes to use, how many spaces to indent, the maximal line length, etc. A lot of minor things. +Stylový průvodce obsahuje obecná pravidla o tom, „jak psát“ kód, tj. které uvozovky používat, o kolik mezer odsazovat, maximální délku řádku atd. Mnoho vedlejších věcí. -When all members of a team use the same style guide, the code looks uniform, regardless of which team member wrote it. +Když všichni členové týmu používají stejného stylového průvodce, bude kód vypadat jednotně bez ohledu na to, který člen týmu ho napsal. -Of course, a team can always write their own style guide, but usually there's no need to. There are many existing guides to choose from. +Samozřejmě si tým vždy může napsat svého vlastního stylového průvodce, ale obvykle to není zapotřebí. Existuje mnoho průvodců, z nichž si lze vybrat. -Some popular choices: +Některé oblíbené možnosti: -- [Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html) -- [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript) +- [JavaScriptový stylový průvodce Google](https://google.github.io/styleguide/jsguide.html) +- [JavaScriptový stylový průvodce Airbnb](https://github.com/airbnb/javascript) - [Idiomatic.JS](https://github.com/rwaldron/idiomatic.js) - [StandardJS](https://standardjs.com/) -- (plus many more) +- (a mnoho dalších) -If you're a novice developer, start with the cheat sheet at the beginning of this chapter. Then you can browse other style guides to pick up more ideas and decide which one you like best. +Pokud jste začínající vývojář, začněte podle příkladu na začátku této kapitoly. Pak si můžete projít jiné stylové průvodce, abyste získali další nápady a rozhodli se, který se vám líbí nejvíc. -## Automated Linters +## Automatické lintery -Linters are tools that can automatically check the style of your code and make improving suggestions. +Lintery jsou nástroje, které umějí automaticky zkontrolovat styl vašeho kódu a navrhnout zlepšení. -The great thing about them is that style-checking can also find some bugs, like typos in variable or function names. Because of this feature, using a linter is recommended even if you don't want to stick to one particular "code style". +Výborné na nich je, že tato kontrola stylu umí najít i některé chyby, například překlepy v názvech proměnných nebo funkcí. Pro tuto jejich vlastnost se používání linteru doporučuje, i když se nechcete vázat k jednomu konkrétnímu „stylu zápisu“. -Here are some well-known linting tools: +Zde jsou některé dobře známé lintery: -- [JSLint](https://www.jslint.com/) -- one of the first linters. -- [JSHint](https://jshint.com/) -- more settings than JSLint. -- [ESLint](https://eslint.org/) -- probably the newest one. +- [JSLint](https://www.jslint.com/) -- jeden z prvních linterů. +- [JSHint](https://www.jshint.com/) -- více nastavení než JSLint. +- [ESLint](https://eslint.org/) -- pravděpodobně nejnovější. -All of them can do the job. The author uses [ESLint](https://eslint.org/). +Všechny tuto práci odvedou. Autor používá [ESLint](http://eslint.org/). -Most linters are integrated with many popular editors: just enable the plugin in the editor and configure the style. +Většina linterů je integrována s mnoha oblíbenými editory: jednoduše povolte plugin v editoru a nakonfigurujte styl. -For instance, for ESLint you should do the following: +Například pro ESLint byste měli udělat následující: -1. Install [Node.js](https://nodejs.org/). -2. Install ESLint with the command `npm install -g eslint` (npm is a JavaScript package installer). -3. Create a config file named `.eslintrc` in the root of your JavaScript project (in the folder that contains all your files). -4. Install/enable the plugin for your editor that integrates with ESLint. The majority of editors have one. +1. Nainstalujte [Node.js](https://nodejs.org/). +2. Nainstalujte ESLint příkazem `npm install -g eslint` (npm je instalátor JavaScriptových balíků). +3. Vytvořte konfigurační soubor s názvem `.eslintrc` v kořenové složce vašeho JavaScriptového projektu (ve složce, která obsahuje všechny vaše soubory). +4. Nainstalujte/povolte ve svém editoru plugin, který jej spojí s ESLintem. Většina editorů jej má. -Here's an example of an `.eslintrc` file: +Uvádíme příklad souboru `.eslintrc`: ```js { @@ -333,16 +333,16 @@ Here's an example of an `.eslintrc` file: } ``` -Here the directive `"extends"` denotes that the configuration is based on the "eslint:recommended" set of settings. After that, we specify our own. +Zde direktiva `"extends"` oznamuje, že konfigurace je založena na sadě nastavení „eslint:recommended“. Poté si specifikujeme vlastní. -It is also possible to download style rule sets from the web and extend them instead. See for more details about installation. +Je také možné si místo toho stáhnout sady stylových pravidel z webu a pak je rozšířit. Pro podrobnosti ohledně instalace viz . -Also certain IDEs have built-in linting, which is convenient but not as customizable as ESLint. +Také některá IDE obsahují zabudovaný linting, který je vyhovující, ale ne tak nastavitelný jako ESLint. -## Summary +## Shrnutí -All syntax rules described in this chapter (and in the style guides referenced) aim to increase the readability of your code. All of them are debatable. +Všechna syntaktická pravidla uvedená v této kapitole (a v odkazovaných stylových průvodcích) směřují ke zvýšení čitelnosti vašeho kódu. Všechna jsou diskutovatelná. -When we think about writing "better" code, the questions we should ask ourselves are: "What makes the code more readable and easier to understand?" and "What can help us avoid errors?" These are the main things to keep in mind when choosing and debating code styles. +Když uvažujeme o psaní „lepšího“ kódu, měli bychom si klást otázky „Co učiní kód čitelnějším a snadnějším k porozumění?“ a „Co nám pomůže vyvarovat se chyb?“. To je to hlavní, co bychom měli mít na paměti, když si vybíráme styly kódování a diskutujeme o nich. -Reading popular style guides will allow you to keep up to date with the latest ideas about code style trends and best practices. +Čtení oblíbených stylových průvodců nám umožní držet krok s nejnovějšími myšlenkami o trendech stylů zápisu programu a nejlepších praktikách. diff --git a/1-js/03-code-quality/02-coding-style/code-style.svg b/1-js/03-code-quality/02-coding-style/code-style.svg index 739d9f1ed..4a5acdb09 100644 --- a/1-js/03-code-quality/02-coding-style/code-style.svg +++ b/1-js/03-code-quality/02-coding-style/code-style.svg @@ -1 +1 @@ -2No space between the function name and parentheses between the parentheses and the parameterIndentation 2 spacesA space after for/if/while…} else { without a line breakSpaces around a nested callAn empty line between logical blocksLines are not very longA semicolon ; is mandatorySpaces around operatorsCurly brace { on the same line, after a spaceA space between argumentsA space between parameters \ No newline at end of file +2Bez mezer mezi názvem funkcí a závorkou mezi závorkou a parametremOdsazení 2 mezeryMezera za for/if/while…} else { bez konce řádkuMezery kolem vnořeného voláníPrázdný řádek mezi logickými blokyŘádky nejsou příliš dlouhéStředník ; je povinnýMezery kolem operátorůSložená závorka { na stejném řádku za mezerouMezera mezi argumentyMezera mezi parametry \ No newline at end of file