Introduction to JavaScript
JavaScript is a versatile, high-level programming language primarily used for web development. It enables interactive web pages and is an essential part of front-end development. JavaScript is also used in back-end development (Node.js) and mobile app development (React Native).
Key Features of JavaScript:
- Client-Side Scripting: JavaScript runs in the browser, making web pages dynamic and interactive.
- Event-Driven: JavaScript responds to user actions like clicks and keypresses.
- Asynchronous Programming: JavaScript supports asynchronous operations using callbacks, promises, and async/await.
- Cross-Platform: JavaScript can be used for web, mobile, and desktop applications.
Embedding JavaScript in HTML
JavaScript can be embedded directly in HTML using the <script>
tag.
It can be placed in the <head>
or <body>
section of an HTML document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Embedded JavaScript</title>
<script>
console.log("JavaScript in the head section.");
</script>
</head>
<body>
<script>
console.log("JavaScript in the body section.");
</script>
</body>
</html>
Using External JavaScript Files
JavaScript code can also be stored in external files and linked to HTML using the <script>
tag with the src
attribute.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>External JavaScript</title>
<script src="script.js"></script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
The external JavaScript file (script.js
) might look like this:
// script.js
console.log("This is an external JavaScript file.");
Modern JavaScript (ES6+)
Modern JavaScript (ES6 and later) introduced many new features, such as:
- let and const: Block-scoped variable declarations.
- Arrow Functions: A concise syntax for writing functions.
- Template Literals: Easier string interpolation and multi-line strings.
- Destructuring: Extracting values from arrays or objects into variables.
- Modules: Organizing code into reusable modules.
// Example of ES6+ Features
const name = "Alice";
let age = 25;
// Arrow Function
const greet = () => `Hello, my name is ${name} and I am ${age} years old.`;
// Template Literals
console.log(greet());
// Destructuring
const person = { name: "Bob", age: 30 };
const { name: personName, age: personAge } = person;
console.log(`${personName} is ${personAge} years old.`);
Example: Hello World in JavaScript
// JavaScript Hello World Program
console.log("Hello, World!");
This code logs "Hello, World!" to the browser console. JavaScript can be embedded directly in HTML or included as an external file.
Next: Variables and Data Types