Javascript and typescript differences with examples

 

Differences Between JavaScript and TypeScript with Examples

JavaScript and TypeScript are both widely used programming languages, especially in the context of web development. TypeScript is a superset of JavaScript, meaning every valid JavaScript code is also valid TypeScript code, but TypeScript adds additional features like static typing, interfaces, and type safety.

Below are the key differences between JavaScript and TypeScript with examples:


1. Static Typing vs. Dynamic Typing

JavaScript:
JavaScript is a dynamically-typed language, meaning types are assigned at runtime. The type of a variable can change during the execution of the program.

javascript
let message = "Hello, World!"; // message is a string message = 123; // Now message is a number

TypeScript:
TypeScript is a statically-typed language, which means types are assigned at compile-time. This allows for type checking and error prevention during development, before running the code.

typescript
let message: string = "Hello, World!"; // message is explicitly typed as a string message = 123; // Error: Type 'number' is not assignable to type 'string'

2. Type Annotations

JavaScript:
JavaScript does not support type annotations. Variables, functions, and parameters are not explicitly typed, so there is no way to declare a type for a variable or function.

javascript
function greet(name) { console.log("Hello, " + name); } greet("Alice"); // Works fine greet(123); // JavaScript will not throw an error, even though this is invalid logic

TypeScript:
TypeScript allows type annotations, so you can explicitly specify the type of variables and function parameters.

typescript
function greet(name: string): void { console.log("Hello, " + name); } greet("Alice"); // Works fine greet(123); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.

3. Interfaces

JavaScript:
JavaScript does not have interfaces, so developers rely on object literals and prototype inheritance for defining the structure of objects.

javascript
const person = { name: "Alice", age: 30 }; console.log(person.name); // Works fine

TypeScript:
TypeScript provides interfaces, which allow you to define the structure of an object in a type-safe manner. This helps in ensuring that objects conform to a specified structure.

typescript
interface Person { name: string; age: number; } const person: Person = { name: "Alice", age: 30 }; console.log(person.name); // Works fine

4. Classes and Inheritance

JavaScript:
JavaScript has class-based inheritance (introduced in ES6), but classes are still based on JavaScript’s prototype inheritance. JavaScript does not enforce any structure or visibility for class members (e.g., private, public).

javascript
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound`); } } class Dog extends Animal { constructor(name) { super(name); } speak() { console.log(`${this.name} barks`); } } const dog = new Dog("Buddy"); dog.speak(); // Output: Buddy barks

TypeScript:
TypeScript extends JavaScript's class syntax by adding visibility modifiers (e.g., public, private, protected) and abstract classes. TypeScript also provides type checking for class members.

typescript

class Animal { public name: string; // public property protected age: number; // protected property, accessible in subclasses constructor(name: string) { this.name = name; } speak(): void { console.log(`${this.name} makes a sound`); } } class Dog extends Animal { constructor(name: string, public breed: string) { super(name); } speak(): void { console.log(`${this.name} barks`); } } const dog = new Dog("Buddy", "Golden Retriever"); dog.speak(); // Output: Buddy barks console.log(dog.breed); // Output: Golden Retriever

5. Modules and Namespaces

JavaScript:
JavaScript supports modules starting with ES6, allowing you to import and export functionality between files using import and export.

javascript

// in math.js export function add(a, b) { return a + b; } // in main.js import { add } from './math'; console.log(add(1, 2)); // Output: 3

TypeScript:
TypeScript fully supports ES6 modules and also allows the use of namespaces (although namespaces are generally not recommended in modern TypeScript).

typescript

// in math.ts export function add(a: number, b: number): number { return a + b; } // in main.ts import { add } from './math'; console.log(add(1, 2)); // Output: 3

6. Optional Parameters and Default Values

JavaScript:
JavaScript allows functions to have optional parameters by checking if a parameter is provided or not.

javascript

function greet(name, age) { if (age === undefined) { age = 25; // Default value } console.log(`Hello, ${name}, you are ${age} years old.`); } greet("Alice"); // Output: Hello, Alice, you are 25 years old. greet("Bob", 30); // Output: Hello, Bob, you are 30 years old.

TypeScript:
TypeScript allows optional parameters and default values directly in the function signature.

typescript

function greet(name: string, age: number = 25): void { console.log(`Hello, ${name}, you are ${age} years old.`); } greet("Alice"); // Output: Hello, Alice, you are 25 years old. greet("Bob", 30); // Output: Hello, Bob, you are 30 years old.

7. Union Types

JavaScript:
In JavaScript, variables are dynamically typed, so they can hold any value, but there's no way to explicitly define multiple acceptable types for a variable.

javascript

let value = "Hello"; value = 123; // This is allowed, but you may run into runtime errors

TypeScript:
TypeScript allows union types, where a variable can hold more than one type of value.

typescript

let value: string | number = "Hello"; value = 123; // Works fine value = true; // Error: Type 'boolean' is not assignable to type 'string | number'

8. Type Inference

JavaScript:
JavaScript does not provide type inference. You have to rely on the runtime to figure out types, and this can lead to unexpected results.

javascript

let x = 10; // JavaScript infers x as a number, but you can't explicitly define it x = "Hello"; // No error, but this might be problematic during runtime

TypeScript:
TypeScript has powerful type inference, which means the compiler can automatically infer types based on the assigned value.

typescript

let x = 10; // TypeScript infers that x is of type number x = "Hello"; // Error: Type 'string' is not assignable to type 'number'

9. Compilation and Tooling

JavaScript:
JavaScript code runs directly in the browser or in a Node.js environment without the need for a compilation step. Tools like Babel can be used to transpile newer JavaScript features to older versions for compatibility.

javascript

// JavaScript is executed directly in the browser or Node.js console.log("Hello, World!");

TypeScript:
TypeScript code must be compiled to JavaScript before it can be executed in a browser or Node.js. TypeScript uses the TypeScript compiler (tsc) to generate JavaScript.

typescript

// TypeScript file: app.ts let x: number = 10; console.log(x); // Compile using `tsc app.ts` to generate app.js

10. Tooling and IDE Support

JavaScript:
JavaScript is supported by all modern IDEs and text editors. It has basic syntax highlighting and autocompletion, but the lack of static types can limit some advanced features.

TypeScript:
TypeScript provides stronger tooling support, especially in IDEs like VSCode. TypeScript enables autocompletion, inline documentation, error checking, and refactoring support based on types.


Summary

FeatureJavaScriptTypeScript
TypingDynamically typedStatically typed with type annotations
Type CheckingDone at runtimeDone at compile-time
ClassesES6 classes with prototype inheritanceES6 classes with additional features like visibility modifiers and abstract classes
Optional ParametersHandled with default values or manual checksDirectly in function signature with ? or default values
Union TypesNot availableAvailable (e.g., `string
InterfacesNot availableAvailable for type checking and structure
CompilationRuns directly in the browser/Node.jsNeeds to be compiled to JavaScript
ToolingBasic autocompletion, syntax highlightingAdvanced tooling, autocompletion, type checking

In summary:

  • JavaScript is more flexible, but can lead to bugs due to its dynamic nature.
  • TypeScript provides type safety, better tooling support, and more maintainable code for larger projects.

If you’re building a small project or prototype, JavaScript might be sufficient. For large-scale applications, TypeScript offers better maintainability, error prevention, and scalability.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics