The post has been translated automatically. Original language: Russian
📉 Low entry threshold — high cost of mistakes
After 4 years of developing in JS/TS, as I immerse myself more and more in the tool, I increasingly find myself thinking that writing really good JavaScript code requires a high level of discipline from a developer. 💪
The threshold for entering JS development is quite low, which is why, after reaching a certain level of proficiency with this tool, sufficient to build a basic UI interface, most people stop there - because the engine itself forgives many implicit transformations and hides from us a number of mechanisms (shallow comparison, closures and stale closures, the order of the event loop, the behavior of this depends on the context of the call), which we can violate, and then it starts shooting off in the prod.
"What about TypeScript?"
Of course, someone might object: "But Sergey, wait, we have TypeScript for this," and that would be a really sensible remark. With the advent of TypeScript, we really managed to write more predictable and fault-tolerant logic. But let's be honest: how many people are not lazy and prescribe all the necessary typing with all type guards and narrowing for processing various edge cases? In most legacy projects I've worked on, TS was more than nominal, and there was such a mess of under-typing, any and unknown, that it got in the way rather than clarifying logic. Of course, some kind of strict mode and various codegen tools for typing API schemas simplify life, but they still won't cover all the cases.
It follows that a JS developer needs deep involvement in the tool and a high level of discipline in order to write predictable and secure code to build high-quality UI interfaces.
⚙️ Comparison with Go: it's physically more difficult to make a mistake there
By no means do I want to say that this is a bad language. It's always convenient to find the last one. But not everyone can take responsibility for the specifics of the tool and immerse themselves in it in order to work out all the edge cases that can be shot in the prod. High involvement in the tool is needed in any stack — this is the base for any engineer, not the specifics of JS. But there is a difference: the Go engine will physically prevent you from making as many mistakes as the JS engine forgives — there is strict typing at the compilation level, there are no implicit conversions, and an unused variable or an unused import simply will not allow the program to compile.
What to do about it
I just encourage engineers to dive into their technology and their stack as needed in order to design more fault-tolerant and predictable systems that other developers will be pleased to work with later. 🙏
📉 Низкий порог входа — высокая цена ошибок
За 4 года разработки на JS/TS, погружаясь всё больше и больше в инструмент, я всё чаще ловлю себя на следующей мысли: для написания действительно хорошего кода на JavaScript от разработчика требуется высокий уровень дисциплины. 💪
Порог входа в разработку на JS достаточно низкий, из-за чего, достигнув определённого уровня владения этим инструментом, достаточного для построения базового UI-интерфейса, большинство людей останавливаются на этом — поскольку сам движок прощает множество неявных преобразований и скрывает от нас ряд механизмов (shallow comparison, замыкания и stale closures, порядок работы event loop, поведение this в зависимости от контекста вызова), которые мы можем нарушать, а потом в проде это начинает отстреливать.
🛡 «А как же TypeScript?»
Конечно, кто-то может возразить: «Но Сергей, погоди, у нас же есть для этого TypeScript» — и это будет действительно дельное замечание. С появлением TypeScript у нас и вправду получилось писать более предсказуемую и отказоустойчивую логику. Но давайте честно: как много людей не ленятся и прописывают всю необходимую типизацию со всеми type guard'ами и narrowing для обработки различных краевых кейсов? В большинстве legacy-проектов, в которых мне довелось поработать, TS там был больше чем-то номинальным, и там была такая каша из недотипизации, any и unknown, что он скорее мешал, чем вносил ясность в логику. Конечно, какой-нибудь strict mode и различные инструменты codegen для типизации API-схем упрощают жизнь, но всё равно всех кейсов они не покроют.
Отсюда следует, что для JS-разработчика необходима глубокая вовлечённость в инструмент и высокий уровень дисциплины, чтобы писать предсказуемый и безопасный код для построения качественных UI-интерфейсов.
⚙️ Сравнение с Go: там ошибиться физически сложнее
Ни в коем случае не хочу сказать, что это плохой язык. Всегда удобно найти крайнего. А вот взять на себя ответственность за специфику инструмента и погрузиться в него, чтобы проработать все edge-case'ы, которые могут отстрелить в проде, — может не каждый. Высокая вовлечённость в инструмент нужна в любом стеке — это база для любого инженера, а не специфика именно JS. Но есть разница: движок того же Go физически не даст вам совершить столько ошибок, сколько прощает движок JS — там строгая типизация на уровне компиляции, нет неявных преобразований, а неиспользуемая переменная или неиспользуемый импорт просто не дадут программе скомпилироваться.
✅ Что с этим делать
Я лишь призываю инженеров по мере необходимости погружаться в свою технологию и свой стек, чтобы проектировать более отказоустойчивые и предсказуемые системы, с которыми потом будет приятно работать другим разработчикам. 🙏