Now that you know a bit more about the history of JavaScript, and before we finally dive into TypeScript, we need to learn about the importance of knowing JavaScript, with its good and bad parts.
As you now know, JavaScript was initially created in 10 days, so it had issues, some of which are, unfortunately, still here today. The TypeScript compiler will protect you from some of these issues but it can't change things that are fundamental in JavaScript such as how numbers are represented.
Here are a few examples of things that are surprising (to say the least) in JavaScript:
- JavaScript variables declared with var are function-scoped. For example, if you declare a variable in a for loop, then that variable declaration actually gets hoisted (that is, moved) to the top of the enclosing function. Block scoping is only possible since ES2015 with the let and const keywords (which you should always use instead of var!).
- JavaScript's number type supports only 64-bit doubles (IEEE 754 double precision standard). Integers are represented as floating point variables; that is, some precision is lost once numbers get too large. Here's an example where it breaks: 9999999999999999 === 10000000000000000 evaluates to true!
- typeof(NaN) evaluates to number.
- true == 1 evaluates to true because == does type coercion (that is, converts the type).
- null == undefined evaluates to true.
- 42 == [42] evaluates to true: in conclusion, always prefer === and !== over == and !=.
- 0 == '' evaluates to true.
- null == undefined evaluates to true.
- alert((![]+[])[+[]]+(![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]);: Displays an alert box with the message fail. Check out the JSF*ck website to know more about this one. Needless to say, hackers love these kinds of things!
The list could go on and on but we will leave it here. As mentioned earlier, TypeScript transpiles into JavaScript, which means that you need to have a good understanding of JavaScript, even if you program in TypeScript, and have knowledge about its good and bad parts.
Douglas Crockford has written a lot and given many talks about JavaScript. He has covered at great length JavaScript's weaknesses and strengths and we really recommend you watch some of his talks and read his book. You'll have fun while doing so and you'll discover many things that you should avoid at all costs in JavaScript as well as some that are really worth using. For a quick review, you can also check out the following summary: https://github.com/dwyl/Javascript-the-Good-Parts-notes.
Mr. Crockford has also created JSLint, a JavaScript linter (that is, a code quality checker) that helps to avoid dangerous syntax and detect possible mistakes before it is too late. A similar tool exists for TypeScript and is called TSLint.