CodeToLive

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:

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:


// 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