JavaScript is a powerful and widely used programming language for web applications. However, it can sometimes lead to unexpected results and errors due to its dynamic type system. In this blog post, we'll examine some of the most common errors that arise in JavaScript, and explore how TypeScript, a superset of JavaScript, can help prevent these issues with improved type safety and error handling.
Common JavaScript Errors
JavaScript is a beginner-friendly language due to its minimal setup requirements. However, the language's limited syntax and dynamic typing often lead to errors, making it challenging for even those who are familiar with the language.
Here are a few common errors when working with JavaScript:
Unexpected string concatenation: Mixing numbers and strings can lead to undesired results, such as console.log(10 + '100')
outputting 10100
instead of the expected 110
.
Stringified object concatenation: Using an object as an argument will result in a stringified version of the object combined with the other argument, e.g., console.log({} + '10')
returns [object Object]10
.
TypeError: Accessing properties of an object that are undefined or calling a non-function will trigger a TypeError
, such as caught TypeError: Cannot read properties of undefined (reading 'data')
when calling console.log({}.input.data)
.
NaN: Forgetting to pass an argument results in a non-existent number, commonly referred to as NaN
for "Not a Number". Example: console.log(parseInt())
ReferenceError: Using an undeclared variable results in a ReferenceError
, such as console.log(10 + abc)
.
Not defined functions: Calling functions that don't exist will also throw a ReferenceError
. Example: console.log(abc())
TypeScript to the Rescue
TypeScript is a programming language developed and maintained by Microsoft that adds type safety to JavaScript. By using TypeScript, you can catch errors during design time (when writing code) rather than at runtime. This will help you catching common JavaScript errors before they appear in production. TypeScript code is compiled (or transpiled) to JavaScript, ensuring compatibility with web applications.
Why Use TypeScript?
TypeScript offers several benefits, including:
- Strong type checking to catch errors before runtime
- Code autocompletion in your IDE for a smoother coding experience
- Fundamental linting rules, including detection of unused variables and parameters
- Const assertions to avoid side effects in functional programming
- Class decorators to facilitate dependency injection
- Inherent support for JSX in the language itself
- Downleveling to convert modern JavaScript to earlier versions of JavaScript
- Compatibility with various module systems, such as CommonJS and ECMAScript modules (ESM)
- Customizable output formatting options, including end-of-line sequence formatting
- Support for polymorphism via class inheritance and interfaces in object-oriented programming
Getting Started with TypeScript
As an experienced TypeScript contributor, I've spent years working with the language and have encountered its various challenges. That's why I've created a free TypeScript video tutorials, designed to help you master the latest version and enhance your coding skills. This series focuses on the fundamentals of TypeScript, ensuring you not only grasp how things work, but also why they work the way they do.
This knowledge can be a valuable asset as you progress from a junior to a senior programmer, and can even assist you in tackling difficult questions during job interviews. The best part? This entire tutorial series is available at no cost, so tune in and enjoy your journey towards TypeScript mastery.
Top comments (9)
This is a nicely written piece, though strongly Typescript biased, where are the counter points?
Many of the benefits listed do not require the use of typescript merely it's extension (ie: code auto completion).
Why ruin an excellent type agnostic language? If you like typescript then use a typed language, there is no point in turning js into .net when .net already exists (or you mike like golang)
Hello and thank you for sharing your perspectives on the matter. The primary argument for adopting TypeScript over .NET is that it serves as a superset of JavaScript. This eliminates the need to learn an entirely new language and ecosystem, allowing for a gradual upgrade of knowledge and development practices. Another advantage is the ability to utilize the same code for both frontend and backend applications.
Furthermore, code completion with JavaScript is notably limited. Due to the absence of types, IDEs face difficulties in accurately determining the properties of classes used from third-party libraries. In many cases, code completion in plain JavaScript relies on analyzing JSDoc comments, which can potentially be out of sync with the actual implementation.
The same applies to the other benefits I mentioned. While modern JavaScript includes classes, it lacks support for abstract classes. Therefore, all of the advantages of TypeScript that I mentioned are either completely absent in JavaScript or available in a very limited capacity.
PS: Benny,
On a personal note, it is not my intention to start a TypeScript flame war. I can see you're thoroughly enjoying TypeScript, and why not it is masterfully crafted and if you have taken the time and effort to master it, then a joy to use, I'm sure.
As I see it TypeScript's primary benefit is in its type safe handling of objects.
Lets just say, I am a javaScript purist.
Good luck with your TypeScript TV channel I liked your linux on win piece, and next time I dip into TypeScript I will be sure to check out your other articles.
I appreciate your positive response. Just to clarify, I value engaging in constructive discussions. I dedicated a significant amount of time, actually several years, to become proficient in TypeScript. That's why I've made the decision to create a video tutorial series to share my experience and help others save time in their learning journey.
I understand and respect your stance as a JavaScript purist. There is actually an ECMAScript Proposal to introduce Type Annotations in JavaScript. This development might potentially change the landscape, and it's possible that I might become a JavaScript purist myself in the future. 😀
However, at this moment, I personally find TypeScript to be the better programming language and appreciate its advantages.
TLDR: My apologies, but what benefits?
Learning TypeScript requires the effort of learning a new language, part of the beauty of javaScript is you can begin to code with no real coding knowledge.
You get code completion from the typescript ide plugin (vscode) you don't need to 'do' typescript for that, also
Soto voice
copilot.You don't need classes in JavaScript, you can emulate them, if you must, and enjoy supporting the pile of compiler plugin's needed, or maybe try a functional approach which is the paradigm from which JavaScript is created.
Hi @lucsan, there's no need to go through the trouble of learning an entirely new language when you can transition gradually from JavaScript to TypeScript. As mentioned, TypeScript is a superset of JavaScript, allowing you to write regular JavaScript code and leverage advanced programming patterns as needed. I recorded a video that shows that: youtube.com/watch?v=AZhZlEbBaB4
Regarding functional approaches, TypeScript offers support for readonly types, which can be valuable when applying functional programming principles. These readonly types help safeguard your code against unintended side effects, promoting more predictable and maintainable code. In light of that, if you're considering to try a functional approach, TypeScript would be a preferable choice.
I'd say you can also use JSDoc... But it really comes down to the level of type safety you want. Since I prefer complete integration, I tend to prefer TypeScript. But TypeScript can be difficult at times, forcing you to write your own typings. If you're willing to do that, I believe TypeScript is a good path.
You don't mention the downsides of Typescript over pure JS. The transpiled code it produces has more run time checks so is generally slower.
We've seen some big performance gains by dropping Typescript in Lambda.
As most of the benefits can be gained using other tools (eslint, sonar cloud and just basic unit tests). The only real advantage is a slightly better IDE.
Hey @wfreeth, thank you for your comment. Do you have performance benchmarks to share? TypeScript emits clean and idiomatic JavaScript code, as it is one of the language's primary design goals. Notably, features like "const assertions" don't emit additional runtime checks, which ensures that the resulting JavaScript code is not slower (see this video). Therefore, I'm curious to learn about the specific cases you encountered where performance was affected?