4.4 JavaScript Basics

Introduction to JavaScript

JavaScript is a high-level, interpreted programming language that makes web pages interactive. It allows you to create dynamic content, control multimedia, animate images, and much more.

Key Points About JavaScript

  • Client-side scripting language
  • Lightweight and interpreted
  • Object-oriented
  • Event-driven
  • Cross-platform

Basic JavaScript Syntax

1. Including JavaScript in HTML

<!-- Internal JavaScript -->
<script>
    // JavaScript code here
    alert('Hello, World!');
</script>

<!-- External JavaScript file -->
<script src="script.js"></script>

2. Variables and Data Types

// Variables
let message = 'Hello';
const PI = 3.14159;
var count = 0;

// Data Types
let name = 'John';          // String
let age = 25;               // Number
let isStudent = true;       // Boolean
let fruits = ['apple', 'banana']; // Array
let person = {              // Object
    firstName: 'John',
    lastName: 'Doe'
};

Functions

Functions are blocks of code designed to perform particular tasks.

// Function declaration
function greet(name) {
    return 'Hello, ' + name + '!';
}

// Function expression
const add = function(a, b) {
    return a + b;
};

// Arrow function (ES6+)
const multiply = (a, b) => a * b;

// Using functions
console.log(greet('Alice'));  // Output: Hello, Alice!
console.log(add(5, 3));       // Output: 8
console.log(multiply(4, 5));  // Output: 20

DOM Manipulation

JavaScript can access and modify the Document Object Model (DOM) to change the content and appearance of a webpage.

// Select elements
const heading = document.querySelector('h1');
const button = document.getElementById('myButton');

// Change content
heading.textContent = 'New Heading';

// Add event listener
button.addEventListener('click', function() {
    alert('Button clicked!');
});

// Create new element
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
document.body.appendChild(newParagraph);