Skip to content

Instantly share code, notes, and snippets.

@jamesmurdza
Last active March 23, 2023 09:55
Show Gist options
  • Save jamesmurdza/617cfb99d2cfd7d12062b942c3a331a4 to your computer and use it in GitHub Desktop.
Save jamesmurdza/617cfb99d2cfd7d12062b942c3a331a4 to your computer and use it in GitHub Desktop.
JavaScript and TypeScript comparison

JavaScript and TypeScript comparison

Variable Declarations

JavaScript:

var x = 10;

TypeScript:

let x: number = 10;

In TypeScript, we need to specify the data type of a variable explicitly. JavaScript does not require this.

Function Declarations

JavaScript:

function greet(name) {
  console.log("Hello, " + name + "!");
}

TypeScript:

function greet(name: string): void {
  console.log("Hello, " + name + "!");
}

In TypeScript, we need to specify the data type of the function parameters and the return type of the function. JavaScript does not require this.

Class Declarations

JavaScript:

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(this.name + " makes a noise.");
  }
}

TypeScript:

class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  speak(): void {
    console.log(this.name + " makes a noise.");
  }
}

In TypeScript, we need to specify the data type of the class properties and the return type of the class methods. JavaScript does not require this.

Type Annotations

JavaScript:

// This is a comment
var x = 10; // This is also a comment

TypeScript:

// This is a comment
let x: number = 10; // This is also a comment

In TypeScript, we can annotate the types of variables, functions, and class properties with comments or with explicit type annotations. JavaScript does not support type annotations.

Optional Parameters

JavaScript:

function greet(name, message) {
  message = message || "Hello";
  console.log(message + ", " + name + "!");
}

TypeScript:

function greet(name: string, message?: string): void {
  message = message || "Hello";
  console.log(message + ", " + name + "!");
}

In TypeScript, we can make a function parameter optional by using the ? symbol. JavaScript does not support this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment