JavaScript Overview
JavaScript (often abbreviated as JS) is a lightweight, interpreted, object-oriented language with first-class functions, most known as the scripting language for Web pages, but used in many non-browser environments as well.
Key Features
- Client-side execution: Runs in the user's web browser without needing resources from the web server.
- Event-driven: Responds to user interactions like clicks, mouse movements, etc.
- Prototype-based: Uses prototypes instead of classes for inheritance.
- Dynamic typing: Variable types are determined at runtime.
- First-class functions: Functions are treated as objects and can be passed as arguments.
- Asynchronous programming: Supports promises and async/await for non-blocking operations.
- Cross-platform: Runs on any platform with a JavaScript engine.
Common Use Cases
Web Development
Essential for creating interactive and dynamic web pages.
Frontend Frameworks
Used with React, Angular, Vue.js for building complex user interfaces.
Server-side Development
Node.js allows JavaScript to be used for backend development.
Mobile Apps
Frameworks like React Native enable cross-platform mobile development.
Example Code
// Modern JavaScript (ES6+) example
// Arrow functions
const greet = (name) => {
return `Hello, ${name}! Welcome to JavaScript.`;
};
// Class syntax
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
return `Hi, I'm ${this.name} and I'm ${this.age} years old.`;
}
}
// Async/await example
async function fetchData(url) {
try {
const response = await fetch(url);
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Using the examples
console.log(greet('Alice'));
const alice = new Person('Alice', 30);
console.log(alice.introduce());
fetchData('https://api.example.com/data');