October 24th, 2024
JavaScript
TypeScript
Web Development
Programming
JavaScript and TypeScript Comparison
JavaScript and TypeScript are both essential languages in web development. While JavaScript is dynamic and widely used, TypeScript adds static typing, which can enhance code quality and maintainability. Below are some key differences illustrated with concise examples.
1. Variable Declaration
JavaScript:
let user = { name: "Alice", age: 30 };
user.age = "30"; // No error, but can lead to bugs.
TypeScript:
let user: { name: string; age: number } = { name: "Alice", age: 30 };
user.age = "30"; // Error: Type 'string' is not assignable to type 'number'.
2. Function Definition
JavaScript:
function add(a, b) {
return a + b; // Can lead to unintended string concatenation.
}
console.log(add(5, "10")); // Outputs: "510"
TypeScript:
function add(a: number, b: number): number {
return a + b; // Strictly expects numbers.
}
console.log(add(5, 10)); // Outputs: 15
3. Interfaces
JavaScript:
function printUser(user) {
console.log(`${user.name} is ${user.age} years old.`);
}
printUser({ name: "Alice", age: 30 }); // No type checks.
TypeScript:
interface User {
name: string;
age: number;
}
function printUser(user: User) {
console.log(`${user.name} is ${user.age} years old.`);
}
printUser({ name: "Alice", age: 30 }); // Type checked.
4. Classes
JavaScript:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
const dog = new Animal("Dog");
dog.speak(); // Outputs: "Dog makes a noise."
TypeScript:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log(`${this.name} makes a noise.`);
}
}
const dog = new Animal("Dog");
dog.speak(); // Outputs: "Dog makes a noise."
5. Enums
JavaScript:
const Directions = {
Up: 0,
Down: 1,
Left: 2,
Right: 3,
};
let direction = Directions.Up; // No type checking.
TypeScript:
enum Directions {
Up,
Down,
Left,
Right,
}
let direction: Directions = Directions.Up; // Strongly typed.
Conclusion
TypeScript enhances JavaScript by adding static typing, which helps catch errors early and improves code readability. Adopting TypeScript can lead to more robust applications and a better development experience.