⚙️ Lesson 13: Introduction to JavaScript

What is JavaScript? JavaScript is a programming language that runs in web browsers. It makes web pages interactive by allowing you to respond to user actions, validate forms, animate elements, and much more.

History and Purpose of JavaScript

Created in 1995 by Brendan Eich, JavaScript was designed to make web pages interactive. Originally called Mocha, then LiveScript, it was renamed JavaScript for marketing reasons. Today, it's one of the most popular programming languages.

Three Ways to Add JavaScript

1. Inline JavaScript

Add JavaScript directly to HTML elements:

<button onclick="alert('Hello, World!')">Click me</button>

2. Internal JavaScript

Add JavaScript in the <head> or <body> using <script> tags:

<head> <script> console.log("This script runs when the page loads"); </script> </head>

3. External JavaScript (BEST PRACTICE)

Create a separate .js file and link it in your HTML:

<!-- In your HTML --> <script src="script.js"></script> // In script.js console.log("External JavaScript file!");

JavaScript Output

console.log()

Print messages to the browser console (useful for debugging):

console.log("Hello, World!"); console.log(42); console.log(true);

Open the Developer Console (F12 or Ctrl+Shift+I) and click the button to see the output:

alert()

Display a message in a popup dialog:

alert("This is an alert message!");

document.write()

Write directly to the HTML document:

document.write("<h2>This is written by JavaScript</h2>");

Modify HTML (Most Common)

Change the content of HTML elements:

document.getElementById("demo").innerText = "Hello!";

Original text

Comments

Comments explain code and don't affect execution:

// Single-line comment /* Multi-line comment can span multiple lines for longer explanations */

Basic Syntax Rules

console.log("Hello"); // Correct console.log('Hello'); // Also correct console.log("Hello") // Works but missing semicolon

Variables

Variables store data values. Declare them with var, let, or const:

let name = "Alice"; let age = 28; let isStudent = true; console.log(name); // Output: Alice console.log(age); // Output: 28 console.log(isStudent); // Output: true

Common Data Types

Number: 42, 3.14, -10

String: "Hello", 'World', "123"

Boolean: true, false

Array: [1, 2, 3], ['Apple', 'Banana']

Object: {name: "Alice", age: 28}

null: Intentional no value

undefined: Variable not assigned a value

typeof Operator

Get the data type of a value:

console.log(typeof 42); // "number" console.log(typeof "hello"); // "string" console.log(typeof true); // "boolean" console.log(typeof [1, 2, 3]); // "object" console.log(typeof undefined); // "undefined"

Interactive Example

Key Concepts

Key Takeaways

← Back to Course | ← Previous | Next: Variables & Data Types →