JavaScript and TypeScript Tutorial
Introduction to JavaScript
JavaScript is a high-level, dynamic, untyped, and interpreted programming language. It is widely used for web development to create interactive effects within web browsers.
JavaScript was initially created to make web pages interactive and dynamic. Today, it is one of the core technologies of web development alongside HTML and CSS.
Basic Syntax of JavaScript
JavaScript syntax is the set of rules that define a correctly structured JavaScript program. Here are some basic elements:
Variables
Variables in JavaScript can be declared using var, let, or const.
var name = "John";
let age = 30;
const isStudent = false;
Functions
Functions are blocks of code designed to perform a particular task. They are executed when they are invoked.
function greet() {
return "Hello, World!";
}
Working with JavaScript
You can run JavaScript code in several environments, including web browsers and Node.js. In browsers, you can use the console for testing small snippets of code.
Example: Console Log
The console.log() function is used to output messages to the console.
console.log(greet()); // Outputs: Hello, World!
Introduction to TypeScript
TypeScript is a superset of JavaScript that adds optional static typing. It was developed by Microsoft to help catch errors during development and enhance code quality.
TypeScript compiles to plain JavaScript, allowing you to use it in any environment where JavaScript is supported.
Basic Syntax of TypeScript
TypeScript introduces types to JavaScript. Here are some basic examples:
Declaring Variables with Types
You can specify types for variables in TypeScript.
let userName: string = "Alice";
let userAge: number = 25;
let isActive: boolean = true;
Functions with Type Annotations
Functions can also have type annotations for parameters and return types.
function add(a: number, b: number): number {
return a + b;
}
Setting Up TypeScript
To start using TypeScript, you need to install it. Use Node.js and npm to install TypeScript globally:
npm install -g typescript
After installation, you can compile TypeScript files using the tsc command:
tsc filename.ts
Conclusion
JavaScript is a powerful language for web development, while TypeScript adds additional features to enhance development and improve code quality. Learning both can significantly enhance your programming skills and open up various opportunities in web development.