TypeScript Vs JavaScript - What's the Differences?
Overview
What was the purpose of TypeScript development when we already had JavaScript?
What are the similarities/differences between them?
Is one of them going to replace the other?
If you have got similar questions in your head, don't worry! Here in this article, we are going to dive deep into this and provide you with a brief insight about the two most trending languages in the world of web development - JavaScript & TypeScript. Let us begin with our main goal - TypeScript vs JavaScript.
What is TypeScript?
TypeScript is a strongly typed language, that is, variables and other data structures can be declared to have specific types, like strings, booleans, etc. By adding this static type definitions to our code, TypeScript makes it easier to see errors early in development, so we spend far less time looking for errors later on.
It is also object oriented and a compiled language, built on JavaScript. It is a superset of JavaScript, meaning that it contains all of the functionality of JavaScript and plus some more.
TypeScript = JavaScript + Additional Features
Any program written in valid JavaScript can also run in TypeScript. When TypeScript is run in a browser, it must be transpiled into JavaScript using the TypeScript compiler (tsc) . Then, tsc generates a new .js file based on the .ts code, which can be used the same way we would use any JavaScript file.
The process of detecting errors in code without actually running it is called static checking.
Identifying what is and what isn't an error, based on the type of value being operated on is called static type checking.
In TypeScript, an error check is performed before a program is executed based on the types of values, i.e. it is a static type checker.
TypeScript gives you a better scalability. It also adds syntax modifications to JavaScript to support tighter integration with the code editor, so we can catch errors very easily and early in our editors.
History of TypeScript
TypeScript was created at Microsoft by Anders Hejlsberg (designer of C#) in Oct 2012. It is maintained by Microsoft. In November 2021, TypeScript 4.5 was released.
Check more of this here - Announcing TypeScript 4.5.
What is JavaScript?
JavaScript is a "dynamic" programming language that is used for web development, web applications, game development, and a lot more. It allows you to implement dynamic features on web pages that cannot be done only with HTML and CSS.
JavaScript is also a scripting language, used by many browsers to do dynamic things on the web. It is used to add interactivity to any HTML webpage. You can see JavaScript in action whenever you click to show a drop-down menu, extra content on a webpage, or element colours changing dynamically on a page, etc.
The reason JavaScript is called a dynamic language is that pretty much everything in it is dynamic. A few reasons are stated below:
- We have variable parameter list in JavaScript, where we can pass any number of variables to a function as parameters.
- We have function variables - Functions stored in variables(exg. arrow functions, function expressions, etc.) do not need function names. They can be called using the variable name.
- Dynamic variable types : In JS, type checks are performed at runtime, only when our program is running. That means, we can assign any value to the variable and it will work.
These things makes JavaScript truly dynamic!
In the absence of JavaScript, we would only have HTML and CSS on the Web. This would make almost 90% of our web pages static and probably you could add dynamic content in form of CSS animations ONLY. So, it would limit our implementations of web pages to a great extent.
Application Programming Interfaces (APIs) add even more super powers to JavaScript. Back then, JavaScript was just implemented on the client-side, but some newer JavaScript engines also have server-side implementations for example the node JS environment.
History of JavaScript
JavaScript was invented by Brendan Eich in 1995 , working in NetScape communications. The latest JS version is ES2021(Jun 2021). "JavaScript" is a trademark of Oracle Corporation in the United States.
Key Difference Between TypeScript and JavaScript
The main difference between TypeScript and JavaScript lies in their approach to typing and development support. TypeScript is a superset of JavaScript, equipped with a robust type system, making it well-suited for large, complex projects. It enforces static typing through type annotations, enabling type checking at compile time. JavaScript, on the other hand, is a dynamically typed scripting language that conducts type checks during runtime. TypeScript compiles into JavaScript, introducing a layer of type safety during development. JavaScript, though flexible and versatile, relies on the dynamic nature of types. These distinctions underscore the importance of choosing the right language for a specific project, where TypeScript excels in maintaining code quality and catching errors early, while JavaScript’s flexibility and extensive community support make it a prominent choice for web development.
TypeScript Vs JavaScript
Features | TypeScript | JavaScript |
---|---|---|
What it is | Superset of JavaScript with a powerful type system for large, complex projects. | A scripting language for creating interactive web pages. |
Interfaces | Supports interfaces and types for defining data structures. | Lacks interfaces and types. |
Type System | Has a static type system with type annotations. | Dynamically-typed language. |
Browser | Requires transpilation to JavaScript for browser execution. | Runs directly in browsers. |
Generics | Supports generics for reusable code. | Doesn’t support generics. |
File Extension | Source files have “.ts” extension. | JavaScript files have “.js” extension. |
Error Handling | Highlights errors during development (statically typed). | Handles errors during runtime (dynamically typed). |
Annotations | Uses type annotations like :[type] for variables, functions, and return values. | Doesn’t use type annotations. |
Community Support | Relatively new and evolving rapidly. | An older language with extensive community support. |
Compilation | Requires compilation using TypeScript compiler (tsc). | Interpreted language, no compilation required. |
ES6+ Support | Yes, supports ECMAScript 2015 (ES6) and newer features. | Supports ECMAScript standards up to the respective version supported by the browser. |
Scalability | Provides better scalability with static typing and type checking. | No inherent scalability features. |
Object-Oriented Features | Supports object-oriented programming with classes, interfaces, etc. | Supports object-oriented programming with prototypes. |
Features of TypeScript
- It is a free and open-source programming language developed and maintained by Microsoft
- ES6 features - TypeScript includes most features of ECMAScript 2015 (ES 6, 7) such as class, interface, Arrow functions etc.
- Static typing(optional) - TypeScript provides static typing through type annotations, to enable type checking at compile time. It speeds up the development process by detecting bugs in real-time.
- Type Annotations on Variables - If you declare a variable with const, var, or let, you can optionally add a type annotation to specify the type of the variable. For example the following code uses type annotations --
-
Type inference - When there is no explicit type annotation given in TypeScript, type inference is used. For example, the code below uses type inference to provide type information.
-
Generics - The TypeScript Generics allows you to create reusable components by creating components that can work with a variety of data types, instead of just a single type of data.
A simple example of generics would be --
Output:
In the above example, we have made a reusable function genericsDemo(), which can process both string and number types of data. Generics use this special kind of type variable <T> that denotes the types.
- Interfaces - Interfaces defines the syntax for classes to follow, means a class which implements an interface is bound to implement all its members. The TypeScript compiler uses interface for type-checking whether the object has a specific structure or not.
Example:
The example defines an interface. The student1 object is of the type Student. Hence, it will now be binding on the object to define all properties as specified by the interface.
- Object-oriented features - TypeScript supports these Oops features - Inheritance, Abstraction, Polymorphism, and Encapsulation.
- Cross-Platform - Portable across browsers, devices, and operating systems. It can run on any environment that JavaScript runs on.
- built-in types - Apart from regular JS , it has some more built-in types like: unknown, never, object literal, void, etc. For example, typeScript uses the type any whenever it can’t tell what the type of an expression should be.
Features Of JavaScript
Some great features of JavaScript are --
- Interpreted programming language - JavaScript is an interpreted language. An interpreter in the browser reads the JavaScript code, interprets each line, and runs it. Modern browsers use a technology known as Just-In-Time compilation, which compiles JavaScript to executable bytecode during execution itself.
- First-class functions - Functions in JavaScript are treated like any other variable. Here, a function can be passed as an argument to other functions, can be returned by another function and can also be assigned as a value to any variable.
- Single-threaded language - JavaScript executes one command at a time. It finishes executing one piece of code before moving on to the next. There is only one call stack in JavaScript.
- Synchronous - One line of code is executed at a time in JavaScript. The execution is in the order in which the code appears(however, in web browsers, there are APIs and functions that can make JS work asynchronously, such as callback functions, setTimeOut, promises, etc.)
- multi-paradigm scripting language - JavaScript supports object-oriented, imperative, and declarative (e.g. functional programming) styles of programming.
- Inheritance with prototype chain: As JavaScript is a dynamic language,here OOP cannot be implemented with the traditional Java class-based model. Instead, OOP in JavaScript is implemented through the prototypal inheritance model.
- Cross-platform language - You can write JavaScript code and run it on several platforms or different OSs.
- JavaScript can be used in both client side and server side. Client-side means that the JavaScript code can run on the client machine, which is the browser. Server-side JavaScript means that the code is run on the server which is serving web pages.
- Weakly Typed Language - Javascript allows implicit conversion between unrelated types. It automatically converts one data type to another (to the correcy type). A simple example would be -
Output:
In the above example, we have initialized the variable val with a string - "Fifty". Then, we add val with an integer value 50. As we see here, implicit type conversion takes place and the integer is implicitly converted to String. Instead of the arithmetic addition operation, here concatenation takes place and the result is logged as "Fifty50". So, an implicity type conversion takes place.
- Dynamic Typing - JavaScript do type checks during runtime. Here, variables are assigned a type based on their value at runtime.
- JavaScript is supported by all browsers like : Netscape Navigator (beginning with version 2.0), Firefox, Safari, Opera, Google Chrome. Or,any other browser whose vendor licensed or implemented JavaScript.
- JIT(just-in-time) compilation - In JIT compilation, the compilation is done during the execution of the code(at run time) rather than before execution. It is used by modern JavaScript interpreters to improve performance and speed up the execution of JS code. Just-in-time compilation is a form of dynamic compilation.
Why TypeScript?
TypeScript is a superset of the JavaScript language that has a single open-source compiler and is developed mainly by Microsoft. The major goal of TypeScript is to help catch mistakes early through a type system and to make JavaScript development more efficient and easy.
Mainly, TypeScript does this in 3 ways:
- Support for modern JavaScript features -- You can safely use new ECMAScript features, like modules, lambda functions, classes, the spread operator and destructuring, while remaining backward compatible with the older browsers and JavaScript runtimes.
- Advanced type system -- The type system of TypeScript is incredibly rich and includes: interfaces, enums, hybrid types, generics, union/intersection types, access modifiers and much more.
- Developer tooling support -- TypeScript's compiler can run as a background process. It supports incremental compilation and IDE integration. This makes it easier to identify the problems, navigate, and refactor your codebase.
TypeScript shares syntax and runtime behaviour with JavaScript, so anything you learn about JavaScript is helping you learn TypeScript at the same time.
Learn more about why typescript is important from here.
Why JavaScript?
No Doubt, javaScript is the most favourite client-side scripting language, it has a lot more to offer than just this. Apart from the unlimited possibilities, there are many reasons for developers to choose JavaScript over other programming languages:
Developers of All Levels Can Use JavaScript
Yes, be it beginner, intermediate or advanced developers, they can start coding in javascript. JavaScript does not require any such environment setups like other languages. We can directly go to our browser(exg. Chrome), navigate to the developers tools and start coding.
However, we need to dive into some advanced concepts(like closures, currying, etc.) to master JavaScript.
Website client-side Usage
JavaScript is the dominant or ruling client-side scripting language of the Web, with 97% of websites using it for this purpose. All major web browsers like Google Chrome, Safari, Firefox etc. have a built-in JavaScript engine that executes the code on the user's device.
Client side refers to everything that is displayed or takes place in the end-user's device. It can include anything the user sees in the UI, any actions that can be performed within the browser, etc.
Client-side scripting means running scripts on the client device, usually within a browser. Any script written in JavaScript can run on the client side, since JavaScript is universally supported on all browsers.
Scripting behaviour of JavaScript
Scripts in JavaScript are embedded(inserted) in the HTML documents. When a web page is loaded, the browser creates a Document Object Model(DOM) of the page. The HTML DOM is a standard object model and programming interface for HTML. In simple words, it is a standard for how to get, change, add, or delete HTML elements. It allows the creation of dynamic web pages.
Hence, within a page, JavaScript can -
- add, change, and remove any of the HTML elements and attributes
- change any CSS styles
- create new events
- react to any event
A few examples of this scripting behaviour are:
- By using Ajax or a WebSocket, we can load a new webpage without reloading the page. For example, social media users can send messages without leaving the current page.
- Playing browser game
- Generating pop-up ads.
- Validating input values of a web form, before the data is sent to a web server.
Modern frameworks for Front-end
Frameworks provide developers with the basic foundation necessary for building JavaScript applications. Nearly 80% of websites rely on third-party JavaScript libraries or frameworks for client-side scripting.
ReactJS is a free and open-source JavaScript library, developed by Facebook. It is used for building interactive UIs, based on UI components. It is the base of React Native, a framework for building mobile applications. It is used by major companies like Facebook, Instagram, Netflix, Twitter, Dropbox, yahoo, Discord and a lot more.
AngularJS created by Google, is a JavaScript-based front-end web framework for developing single-page applications. Major companies using Angular JS include Microsoft Office, Forbes, Paypal, Gmail, etc.
jQuery is by far the most popular javascript library, used by over 75% of websites.
There are other frameworks as well like vue.js, ember.js which are also highly used.
Back-End with JavaScript
Node.js is a Javascript run-time environment, that helps in the execution of JavaScript code server-side. It is majorly used in the back-end.
Node.js represents a "JavaScript everywhere" paradigm, allowing developers to build web applications using a single programming language, instead of different languages for server-side and client-side scripts.
Server-side means anything that is happening on the server, instead of on the client's end. It can include rendering dynamic webpages, interacting with databases,push notifications and identity authentication.
Server-side scripts run on the server, delivering dynamic content to webpages in response to the user's interaction.
Omni-platform
JavaScript can run on every platform, making it a universal language. It can run on:
- Client-side and the server-side
- All devices like mobile, tablet, laptops, etc.
Community Support
There are over 1.8 Billion websites in the world, and JavaScript is used on 95% of them! JavaScript is by far the most used language according to Github’s 2021 Octoverse Report. And javascript has one of the largest communities according to Stack Overflow.
According to Stack overflow 2021 Developer survey -
JavaScript completes it's ninth year in a row as the most commonly used programming language.
Because of all of this, JavaScript is a crucial programming language to have in your toolkit as a web developer, irrespective of whether you specialize in front end, back end, or full stack development.
Advantages & Disadvantages of TypeScript
We have already discussed very briefly about TypeScript, its powerful features, capabilities, etc. Below are some of the advantages of TypeScript over JavaScript--
Advantages of TypeScript
- Optional Static typing - In TypeScript, once a variable is declared, it doesn't change its type and can take only a certain value. The compiler also alerts the developer about any type-related mistakes. This results in less error-prone code and better performance during execution.
- Early spotted bugs - TypeScript spots most of the common bugs at a very early stage,reducing the overall load on the compiler for testing activities.
- Rich IDE support - IDEs can offer features like code navigation and autocompletion, providing accurate suggestions. They also give feedback while we are typing: The editor flags errors, including type-related errors. This majorly helps us write maintainable code, resulting in a significant productivity boost. Some popular IDEs for TypeScript include - Microsoft Visual Studio, VS Code, WebStorm, Eclipse, etc.
- Fast refactoring - Code refactoring is a process that involves editing and cleaning up code without changing any functionality. Basically, it makes the code more efficient and maintainable. TypeScript does it very smoothly for us. For example, if we rename any function, and forget to change the name somewhere, then TS will raise an alert about that. Refactoring is accelerated this way, which is especially useful when dealing with large portions of code.
- Power of OOP - In TypeScript, you can use concepts from class-based object-oriented programming (OOP) like classes, interfaces, inheritance, etc. As our project grows in size and complexity, the OOP paradigm facilitates building a well-organized, scalable code.
- Cross-platform and cross-browser compatibility - TypeScript works on every device, platform, and browser that runs JavaScript, after it is converted into vanilla JS by the compiler. TypeScript editors and IDEs come with a built-in TS compiler (tsc), which can be invoked from the command line.
- Tech world support - TypeScript is an open-source language with a rapidly growing community. It is used by millions of developers around the world and its large community can always guide you. Even some major companies such as slack and KAVAK, switched to TS for managing their large codebases.
Let us also look at some disadvantages of TypeScript:
Disadvantages of TypeScript
- Transpiling - Browsers cannot interpret the TypeScript code, so you need to transpile it to JavaScript before running. Nevertheless, this process is extremely automated and doesn't require a lot of additional time.
- Large code length - TypeScript requires you to write more code, which could slow down the overall development process. Also, the additional annotations make the TypeScript files larger than those written in JavaScript. However, all these get disappeared once the code is transpiled. And the browser executes plain JavaScript in the end.
- Not truly static typing - TypeScript have optional static typing. Unlike other languages such as Java, C++, C# it is not a true statically typing language. Since TypeScript is transpiled into untyped JavaScript, there is always the possibility of weird type conversions at runtime.
Nevertheless, TypeScript continues to evolve, fixing and improving all the time.
Let us now study the main agenda of this article - TypeScript JavaScript.
Advantages & Disadvantages of JavaScript
Undoubtedly, JavaScript has become a revolutionary technology that everyone seems to talk about. Let us also discuss some pros & cons of the language:
Advantages of JavaScript:
- Speed - Client-side JavaScript is very fast because they are directly executed in the client's browser, without making any network(server) calls(which is time consuming). Also, modern browsers support JIT (just in time) compilation for JavaScript, meaning that there's no need to compile the code before running it, so it adds up to it's speed as well.
- Simplicity - The structure is simple and feasible to implement. The syntax of JavaScript was inspired by Java, and is relatively easy to learn.
- Interoperability - We can embed JavaScript into any webpage or inside the script of another programming language.
- Less Server Load - As JavaScript operates on the client-side, data validation happens on the browser itself before sending it to the server, reducing the overall server load. Typically, validations are either performed using the built-in validations provided by HTML (for example, when creating forms using HTML, we specify constraints like minlength, required, etc., which automatically perform validations for us), or through custom Javascript validation. With custom JS validations, we write our own JS code and can provide any custom error messages to the user instead of default error messages which are provided by built-in validations.
- Rich interfaces - JavaScript gives us the ability to create rich user interfaces. For example, we can create features like drag and drop, and components such as sliders using JavaScript. This greatly enhances the user interface and the experience of the website.
- Versatility - JavaScript is capable of both front-end and back-end development. For example, we have libraries and frameworks like ReactJS, AngularJS, Vue.js, etc. for the frontend development. We also have VanillaJS(for front-end) for library/framework free javascript. We can use Node.js for the backend part, and in many other ways. It is possible to build an entire application(from frontend to backend) using only JavaScript.
- Lesser Code length - JavaScript optimizes the performance of websites and web applications by reducing code length. There is less overhead in the code since there are many built-in functions for loops, DOM access, etc in javascript.
- Browser Support - All the modern browsers comes with built-in support for JavaScript. However, users do have choice to disable JavaScript running in their browsers.
Disadvantages of JavaScript:
- Rendering: Any problem with the code execution, or rendering, can cause a breakdown in your site appearance and displayed content. Thus, it will disrupt the overall user experience.
- Slower Bitwise function: JavaScript stores any number as 64-bit floating-point number, whereas operators need 32-bit bitwise operands for operating. Hence, this conversion from number to integer is time taking.
- Single Inheritance: JavaScript only supports single inheritance, not multiple.
- Client-side Security: Since, users can see the JavaScript code, they can use it for illegal/wrong purposes which can compromise the security of data over the website.
- Browser Support: JavaScript is interpreted differently in different browsers. So, the javascript code must be well tested on every platform before publishing to avoid any mishappenings. Also, the old browsers do not support some new features, so we need to keep that in check too. For example, Internet Explorer does not support ECMAScript 2015.
Learn more about the advantages and disadvantaged of javascript from here.
Conclusion
- TypeScript emerges as a powerful choice for large and complex projects with its robust type system and static typing, which provides early error detection and code clarity.
- JavaScript, on the other hand, remains the go-to for creating interactive web pages, offering dynamic typing with errors identified during runtime.
- The compilation aspect sets them apart, as TypeScript requires transpilation into JavaScript for browser execution, while JavaScript, with its JIT compilation, runs directly in browsers.
- TypeScript leverages interfaces and types for data definition, fostering code maintainability, while JavaScript lacks these constructs.
- Generics are another point of divergence, with TypeScript supporting this feature for creating reusable code.
- File extensions distinguish them, where TypeScript source files have a “.ts” extension, and JavaScript files have “.js”.
- Error handling varies; TypeScript’s static typing detects errors during development, while JavaScript handles them dynamically during runtime.
- TypeScript employs type annotations, offering clarity but with the trade-off of an initially steeper learning curve, whereas JavaScript doesn’t use them.
- Finally, in terms of community support, JavaScript’s extensive community and maturity make it the staple choice, while TypeScript is rapidly evolving and gaining traction.
Choosing between TypeScript and JavaScript depends on the project’s nature, size, and development priorities, with TypeScript excelling in large, organized projects and JavaScript being the versatile and established option for general web development.