Class 8: Introduction to JavaScript - The Language of the Web
Introduction to Programming Languages
A programming language is a set of instructions, commands, and syntax used to create software programs. They serve as a bridge between human thoughts and machine execution, allowing developers to communicate with computers.
Types of Programming Languages
Low-Level Languages
These languages are very close to the computer's hardware. They offer high performance and direct memory management but are difficult for humans to read and write.
- Machine Code: Directly executable by the CPU, consisting of binary digits (0s and 1s).
- Assembly Language: Uses mnemonics (short codes) to represent machine code instructions, requiring an assembler to translate them into machine code.
High-Level Languages
These languages are designed to be user-friendly, abstracting away the complexities of hardware. They are easier to read, write, and maintain, and are often portable across different systems. These can be broadly categorized by how their code is executed:
-
Compiled Languages: Code written in
these languages is translated into machine code by a
program called a compiler before execution. The entire
program is converted into an executable file, which can
then run independently. This process generally results
in faster execution speeds.
Examples: C, C++, Rust, Go. -
Interpreted Languages: Code written in
these languages is executed line by line by an
interpreter at runtime. No separate executable file is
generated. This allows for greater flexibility and
easier debugging, but typically results in slower
execution compared to compiled languages.
Examples: Python, JavaScript, Java, PHP.
What is JavaScript? Its Role in Web Development
Welcome to JavaScript, the programming language that makes web pages interactive and dynamic! Until now, we've focused on HTML for structure and CSS for styling. JavaScript is the "behavior layer" of the web, enabling features like interactive forms, animations, dynamic content updates, and much more.
JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for web pages, where it enables interactive client-side scripts, it's also used in many non-browser environments, such as Node.js for server-side programming, desktop applications (Electron), and mobile apps (React Native).
Key Roles of JavaScript on the Web:
- Client-Side Interactivity: Responding to user actions (clicks, key presses), validating form inputs, showing/hiding elements, creating animations.
- Dynamic Content Updates: Fetching data from a server without reloading the page (AJAX, Fetch API), manipulating the Document Object Model (DOM).
- Web APIs: Interacting with browser features like geolocation, local storage, camera, etc.
- Full-Stack Development: With Node.js, JavaScript extends to the server-side, allowing developers to build entire web applications using a single language.

How to Include JavaScript in HTML
There are three primary ways to include JavaScript code in your HTML document:
1. Inline JavaScript (Discouraged for most cases)
You can place JavaScript directly within HTML attributes, especially for event handlers. This is generally not recommended for large amounts of code as it mixes content with behavior, making it hard to maintain.
<button onclick="alert('Hello from inline JS!');">Click Me</button>
2. Internal JavaScript
You can write JavaScript code directly within
<script>
tags inside your HTML file. These
tags can be placed in the <head>
or
<body>
section.
In <head>
:
<head>
<script>
console.log("This is JavaScript from the head.");
</script>
</head>
At the end of
<body>
(Recommended):
<body>
<!-- HTML content -->
<script>
console.log("This is JavaScript from the body.");
</script>
</body>
Placing scripts at the end of the <body>
is a
common practice because it ensures that the HTML content is
loaded and parsed by the browser before the JavaScript tries to
manipulate it.
3. External JavaScript Files (Most Recommended)
For larger applications, it's best practice to write your
JavaScript code in separate .js
files and link them
to your HTML using the src
attribute of the
<script>
tag. This improves organization,
readability, and caching.
// index.html
<body>
<!-- HTML content -->
<script src="js/script.js"></script>
</body>
// js/script.js
console.log("Hello from an external JavaScript file!");
document.getElementById('myElement').textContent = "Content updated by JS!";
Important Script Attributes:
-
async
: Scripts withasync
will download in parallel and execute as soon as they are available, without blocking HTML parsing. The order of execution is not guaranteed. -
defer
: Scripts withdefer
will download in parallel but execute only after the HTML document has been fully parsed. They maintain their relative execution order. This is often preferred for scripts that depend on the DOM.
<script src="js/script.js" async></script>
<script src="js/another-script.js" defer></script>
Variables, Data Types, and Operators
Variables (var
, let
,
const
)
Variables are containers for storing data values. JavaScript has three keywords for declaring variables:
-
var
: The oldest way to declare variables. It has function scope and can be redeclared and reassigned. Prone to issues like variable hoisting without block scope. (Generally discouraged in modern JS) -
let
: Introduced in ES6 (ECMAScript 2015). It has block scope, meaning it's only accessible within the block (curly braces{}
) where it's defined. It can be reassigned but not redeclared in the same scope. -
const
: Also introduced in ES6. It has block scope and declares a constant value. This means its value cannot be reassigned after initial assignment. For objects and arrays, the content can be changed, but the reference itself cannot be reassigned.
// Using var (function-scoped, can be redeclared)
var greeting = "Hello";
greeting = "Hi";
var greeting = "Greetings!"; // Valid, but can lead to confusion
console.log(greeting);
// Using let (block-scoped, can be reassigned but not redeclared)
let userName = "Alice";
userName = "Bob";
// let userName = "Charlie"; // Error: Identifier 'userName' has already been declared
console.log(userName);
// Using const (block-scoped, cannot be reassigned)
const PI = 3.14159;
// PI = 3.14; // Error: Assignment to constant variable.
console.log(PI);
const user = { name: "John", age: 30 };
user.age = 31; // Valid: content of object can be changed
// user = { name: "Jane", age: 25 }; // Error: Cannot reassign const
console.log(user);
Data Types
JavaScript variables can hold different data types. Data types describe the kind of value a variable can store.
Primitive Data Types: (hold a single value)
-
String
: Represents textual data. Enclosed in single quotes (''
), double quotes (""
), or backticks (``
for template literals).let name = "Alice";
-
Number
: Represents both integer and floating-point numbers.let age = 25; let price = 99.99;
-
Boolean
: Represents logical entities; eithertrue
orfalse
.let isActive = true;
-
Undefined
: A variable that has been declared but not yet assigned a value.let city;
-
Null
: Represents the intentional absence of any object value.let car = null;
-
Symbol
(ES6): Represents a unique identifier.const id = Symbol('id');
-
BigInt
(ES2020): For numbers larger than 2^53 - 1.const bigNumber = 1234567890123456789012345678901234567890n;
Non-Primitive Data Types: (can hold collections of values)
-
Object
: A collection of key-value pairs. Used to store more complex data structures.let person = { firstName: "John", lastName: "Doe", age: 30 };
-
Array
: A special type of object used to store ordered collections of values.let colors = ["red", "green", "blue"];
Operators
Operators are symbols that perform operations on values and variables.
Arithmetic Operators: Perform mathematical calculations.
+
(Addition)-
(Subtraction)*
(Multiplication)/
(Division)%
(Modulus/Remainder)**
(Exponentiation - ES6)++
(Increment)--
(Decrement)
let x = 10;
let y = 3;
console.log(x + y);
console.log(x % y);
console.log(x ** 2);
x++;
console.log(x);
Assignment Operators: Assign values to variables.
=
(Assignment)+=
(Add and assign)-=
(Subtract and assign)*=
(Multiply and assign)/=
(Divide and assign)%=
(Modulus and assign)**=
(Exponentiation and assign)
let a = 5;
a += 3; // Equivalent to a = a + 3;
console.log(a);
Comparison Operators: Compare two values and
return a boolean (true
or false
).
==
(Equal to - checks value only)-
===
(Strict equal to - checks value and type) !=
(Not equal to - checks value only)-
!==
(Strict not equal to - checks value and type) >
(Greater than)<
(Less than)>=
(Greater than or equal to)<=
(Less than or equal to)
console.log(5 == "5");
console.log(5 === "5");
console.log(10 > 5);
Logical Operators: Combine conditional statements.
-
&&
(Logical AND) - returns true if both operands are true. -
||
(Logical OR) - returns true if at least one operand is true. -
!
(Logical NOT) - inverts the boolean value of the operand.
let isAdult = true;
let hasLicense = false;
console.log(isAdult && hasLicense);
console.log(isAdult || hasLicense);
console.log(!isAdult);
Ternary Operator (Conditional Operator): A
shorthand for if...else
statements.
condition ? expressionIfTrue : expressionIfFalse
let age = 18;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status);