JavaScript is a high - level, dynamic, untyped, and interpreted programming language. It is primarily used for creating interactive web pages and web applications. JavaScript is a multi - paradigm language, supporting object - oriented, imperative, and functional programming styles.
One of the key features of JavaScript is its dynamic typing. Variables in JavaScript do not need to be declared with a specific type, and their type can change during the execution of the program. For example:
let num = 10;
num = "Hello";
TypeScript is a superset of JavaScript. It adds static typing to JavaScript, which means that variables, function parameters, and return values can be explicitly typed. TypeScript code is transpiled into plain JavaScript code, which can then be run in any JavaScript environment.
Here is an example of a TypeScript variable with a type annotation:
let num: number = 10;
// The following line will cause a compilation error because we are trying to assign a string to a number variable
// num = "Hello";
JavaScript can be used in several ways:
<script>
tag.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
</head>
<body>
<button id="myButton">Click me</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', function () {
alert('Button clicked!');
});
</script>
</body>
</html>
.js
file and link it to your HTML file.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
<script src="script.js"></script>
</head>
<body>
<button id="myButton">Click me</button>
</body>
</html>
And in script.js
:
const button = document.getElementById('myButton');
button.addEventListener('click', function () {
alert('Button clicked!');
});
To use TypeScript, you first need to install it globally using npm:
npm install -g typescript
.ts
extension, for example, app.ts
.function greet(name: string): string {
return `Hello, ${name}!`;
}
const message = greet('John');
console.log(message);
tsc
command to transpile your TypeScript code to JavaScript.tsc app.ts
This will generate an app.js
file, which can be run in a JavaScript environment.
'use strict';
let x = 10;
// The following line will throw an error in strict mode because 'y' is not declared
// y = 20;
import
and export
syntax.// math.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from './math.js';
const result = add(5, 3);
console.log(result);
interface Person {
name: string;
age: number;
}
function printPerson(person: Person) {
console.log(`${person.name} is ${person.age} years old.`);
}
const john: Person = { name: 'John', age: 30 };
printPerson(john);
function printValue(value: string | number) {
if (typeof value === 'string') {
console.log(`The string is: ${value}`);
} else {
console.log(`The number is: ${value}`);
}
}
printValue('Hello');
printValue(10);
try...catch
blocks to handle errors gracefully.try {
const result = JSON.parse('{ "name": "John" }');
console.log(result);
} catch (error) {
console.error('Error parsing JSON:', error);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
</head>
<body>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
const list = document.getElementById('myList');
list.addEventListener('click', function (event) {
if (event.target.tagName === 'LI') {
console.log(`Clicked on ${event.target.textContent}`);
}
});
</script>
</body>
</html>
type Admin = {
name: string;
role: 'admin';
};
type User = {
name: string;
role: 'user';
};
type AdminOrUser = Admin | User;
function printRole(person: AdminOrUser) {
console.log(`${person.name} has role: ${person.role}`);
}
const admin: Admin = { name: 'Alice', role: 'admin' };
const user: User = { name: 'Bob', role: 'user' };
printRole(admin);
printRole(user);
The choice between JavaScript and TypeScript depends on the nature of your project. If you are working on a small - scale project or need quick prototyping, JavaScript might be the better choice due to its simplicity and immediate availability. However, for large - scale, complex projects where code maintainability, type safety, and developer productivity are crucial, TypeScript is a great option. TypeScript’s static typing helps catch errors early in the development process and makes the codebase more understandable and refactorable.