TypeScript vs JavaScript

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

Javascript Course - Mastering the Fundamentals
Javascript Course - Mastering the Fundamentals
By Mrinal Bhattacharya
Free
star4.8
Enrolled: 1000
Javascript Course - Mastering the Fundamentals
Javascript Course - Mastering the Fundamentals
Mrinal Bhattacharya
Free
4.8
icon_usercirclecheck-01Enrolled: 1000
Start Learning

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 vsv s JavaScript.

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.

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 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 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.

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.

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.

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:

  1. 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.
  2. 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.
  3. 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.

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 vsv s JavaScript.

TypeScript vs JavaScript

TypeScript vs JavaScript is a very popular question among the developers who are learning these languages and want to know which is better, or how to choose between the two. But, both the languages have their own pros and cons. We have noted the various points about: TypeScript vs JavaScript, which might help you to discover which one to use where.

  1. What it is:
    TypeScript is a superset of JavaScript, having a powerful 'Type' system(assigns a type to functions, variables, expressions), and built to overcome code difficulty for large,complex projects. JavaScript is a scripting language that helps you create interactive web pages.
  2. Static/Dynamic :
    TypeScript is a statically typed language. TypeScript provides static typing through type annotations to enable type checking at compile time. whereas, JavaScript is a dynamically typed language. So, type checkings are done during the runtime.
  3. Compilation:
    TypeScript is a "compiled language". The compiler takes the TypeScript code, removes the type information, and generates JavaScript code. It is often called 'transpilation' because it is translating from one source language to another. JavaScript is an interpreted language. However, the modern approach of running the JavaScript source code creates a sort of “in-between” area, with the JIT(just in time) compilation, which compiles the code during the execution itself.
  4. Interfaces:
    TypeScript uses concepts like interfaces and types to define the data being used. Interfaces defines the syntax for the classes to follow. JavaScript does not have concepts like interfaces or types.
  5. Browser:
    TypeScript cannot directly run in the browser. To run TypeScript code in browser, it needs to be transpiled into JavaScript with the TypeScript compiler (tsc). In this case, tsc creates a new .js file based on the .ts code, which can be used like any other JavaScript file. JavaScript can run directly in browsers and it is flexible.
  6. Generics:
    TypeScript supports generics. We have already discussed it in our previous sections(refer to Features of TypeScript). JavaScript does not support generics.
  7. File Extension:
    The TypeScript source file has the ".ts" extension, whereas the JavaScript files have the extension ".js"
  8. Error: TypeScript highlights errors during the development time because it is statically typed. JavaScript, due to it's dynamically typed nature handles errors during runtime.
  9. Annotation : In Typescript, type annotations specify the type of a variable, function, or function return value. It uses the syntax :[type], where type is the Typescript type. If you use a variable of a different type than described, the Typescript compiler throws an error. JavaScript does not have Type Annotations.
  10. Community Support : TypeScript is relatively new, and evolving at a rapid pace. JavaScript is an old language and has extensive community support over TypeScript. It has also been the most popular language for several years, according to surveys by stack overflow.

Conclusion

In this article, we learnt about TypeScript vsv s JavaScript. We outlined the differences between these languages and learned how both JavaScript and TypeScript are well suited for modern web environments.

JavaScript may not be a comprehensive(complete) coding language, but it plays a crucial role in enhancing the quality of web pages by combining it with HTML. And, there are millions of JavaScript users.

Alternatively, TypeScript is a preferred option for developers who want to write compact, readable code that is clean and beautiful, with the added benefits of errors and type checking.

Let us just recap the points we went through in this article :

  • JavaScript - About, Background, Features
  • TypeScript - About, Background, Features
  • Why we use JavaScript / TypeScript
  • TypeScript vs JavaScript
  • Advantages & Disadvantages of TypeScript Vs JavaScript

Learn More: