Introduction to JavaScript
This course provides a comprehensive foundation in JavaScript for web development. Designed for students with basic HTML and CSS knowledge, it covers essential concepts including variables, functions, control structures, and DOM manipulation. Participants will learn to create interactive web elements, handle user events, validate forms, and update content dynamically. Through hands-on exercises and a final project, students will gain practical experience in enhancing web pages with JavaScript, preparing them for more advanced web development techniques and frameworks.
Level 3: Introduction to JavaScript: Variables, Functions, Basic Interactivity, and DOM
What is JavaScript?
JavaScript is a high-level, interpreted programming language that conforms to the ECMAScript specification. It's a core technology of the World Wide Web, alongside HTML and CSS. JavaScript enables interactive web pages and is an essential part of web applications.
JavaScript in Web Development
In web development, JavaScript is primarily used for:
- Adding interactivity to web pages
- Manipulating the Document Object Model (DOM)
- Handling events (like clicks, form submissions, etc.)
- Making asynchronous requests to servers (AJAX)
- Building full-fledged web applications
Adding JavaScript to HTML
There are two main ways to add JavaScript to an HTML document:
- Inline JavaScript using the
<script>
tag - External JavaScript files
Inline JavaScript
You can add JavaScript directly within your HTML file using the <script>
tag:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My JavaScript Page</title> </head> <body> <h1>Hello, World!</h1> <script> console.log("This is an inline JavaScript code"); </script> </body> </html>
External JavaScript Files
For better organization and reusability, it's often preferable to keep your JavaScript in separate files:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My JavaScript Page</title> </head> <body> <h1>Hello, World!</h1> <script src="script.js"></script> </body> </html>
Then in your script.js
file:
console.log("This is an external JavaScript file");
Variables
Variables are used to store data values. In JavaScript, we have three ways to declare variables:
var
: Function-scoped or globally-scoped variable. A globally-scoped variable is accessible from any part of the code, regardless of where it is declared.let
: Block-scoped variable. A block-scoped variable is only accessible within the block (enclosed by{}
) where it is declared.const
: Block-scoped constant. Similar tolet
, but the value assigned to aconst
variable cannot be changed once it is set.
These variable declarations were standardized in ECMAScript 2015, commonly known as ES6. ES6 is a version of the ECMAScript standard and is a major enhancement to the JavaScript language that includes more features for better coding practices.
var globalVar = "I'm a global variable"; let blockVar = "I'm block-scoped"; const CONSTANT = "I can't be reassigned"; // Naming conventions let camelCase = "This is the standard for JavaScript"; let snake_case = "This is less common in JavaScript"; let PascalCase = "This is typically used for classes";
Operators
JavaScript supports various types of operators:
-
Arithmetic Operators:
+
,-
,*
,/
,%
,**
These operators perform arithmetic operations like addition, subtraction, multiplication, division, modulus(x mod y), and exponentiation(x^y). -
Assignment Operators:
=
,+=
,-=
,*=
,/=
These operators assign the result of the operation to the variable on the left. Given two variables,x
andy
,x += y
is the same asx = x + y
, andx -= y
is the same asx = x - y
, and so on. -
Comparison Operators:
==
,===
,!=
,!==
,>
,<
,>=
,<=
These operators compare two values and return a boolean result, true or false. Here are the descriptions of the operators:
==
: Equality. Returns true if the two operands are equal.===
: Strict equality. Returns true if the two operands are equal AND OF THE SAME TYPE.!=
: Inequality. Returns true if the two operands are not equal.!==
: Strict inequality. Returns true if the two operands are not equal OR OF DIFFERENT TYPES.
- Logical Operators:
&&
,||
,!
These operators perform logical operations on boolean expressions. Here is a description of the operators:
&&
: Logical AND. Returns true if both operands are true.||
: Logical OR. Returns true if at least one of the operands is true.!
: Logical NOT. Returns true if the operand is false.
let x = 5; let y = 2; console.log(x + y); // Addition: 7 console.log(x - y); // Subtraction: 3 console.log(x * y); // Multiplication: 10 console.log(x / y); // Division: 2.5 console.log(x % y); // Modulus: 1 console.log(x ** y); // Exponentiation: 25 x += y; // x is now 7 because you are adding y to x and assigning the result to x, ie x = x + y console.log(x == "7"); // true (equality) console.log(x === "7"); // false (strict equality) let a = true, b = false; console.log(a && b); // false console.log(a || b); // true console.log(!a); // false
From these examples, you can see that we store our results in console.log to see the output of the operations. The console is a tool in the browser's developer tools that allows you to see the output of your code, using console.log()
. We a
Data Types
JavaScript has several built-in data types:
- Number: Represents both integer and floating-point numbers
- String: Represents textual data
- Boolean: Represents
true
orfalse
- Undefined: Represents a variable that has been declared but not assigned a value
- Null: Represents a deliberate non-value
- Object: Represents a collection of related data
- Symbol (introduced in ES6): Represents a unique identifier
let num = 42; let str = "Hello, World!"; let bool = true; let undef; let nullValue = null; let obj = {name: "John", age: 30}; let sym = Symbol("unique"); console.log(typeof num); // "number" console.log(typeof str); // "string" console.log(typeof bool); // "boolean" console.log(typeof undef);// "undefined" console.log(typeof nullValue); // "object" (this is a known bug in JavaScript) console.log(typeof obj); // "object" console.log(typeof sym); // "symbol"
Control Structures
JavaScript supports various control structures for decision making and looping:
If-Else Statements
If-Else statements are used to execute different code depending on the value of a condition. They are expressed in the following format:
if (condition) { // code to execute if condition is true } else { // code to execute if condition is false }
The if
statement is used to check if the condition is true. If it is, the code inside the if
block is executed. If the condition is false, the code inside the else
block is executed.
let age = 18; if (age >= 18) { console.log("You are an adult"); } else if (age >= 13) { console.log("You are a teenager"); } else { console.log("You are a child"); }
Switch Statements
Switch statements are similar to if-else statements, but they are used to execute different code depending on the value of a variable. They are expressed in the following format:
switch (expression) { case value1: // code to execute if expression matches value1 break; case value2: // code to execute if expression matches value2 break; default: // code to execute if expression does not match any case }
In a switch statement, the expression is evaluated and the result is compared to the values of the cases. If a match for a specific condition is found, the code for that case
is executed. If no match is found, the code for the default
case is executed.
Example:
let day = "Monday"; switch(day) { case "Monday": console.log("Start of the work week"); break; case "Friday": console.log("TGIF!"); break; default: console.log("It's a regular day"); }
Loops
JavaScript provides several types of loops:
- For loop
- While loop
- Do-While loop
The differences in these types go down to the syntax and the way they are used:
- For loops are used to iterate over a range of values. Before they are used, we need to initialize a variable, a condition, and an increment/decrement. Here is the syntax for a For loop:
for (let i = 0; i < 5; i++) { //code to be executed for each iteration }
- While loops are used to iterate until a certain condition is met. The syntax is given as such:
while (condition) { // code to execute while condition is true }
- Do-While loops are used to iterate until a certain condition is met, but they always execute at least once. The syntax is given as such:
do { // code to execute for each iteration } while (condition);
Here is an example of using these loops:
// For loop for (let i = 0; i < 5; i++) { console.log(i); } // While loop let j = 0; while (j < 5) { console.log(j); j++; } // Do-While loop let k = 0; do { console.log(k); k++; } while (k < 5);
Functions
Functions are reusable blocks of code that perform a specific task. For each function, there exists a parameter and an argument. The parameter is the variable that we use to name the function, and the argument is the value that we pass to the function when we call it. For example, given the function:
function greet(name) { return `Hello, ${name}!`; }
The parameter is name
. This is the basis of the function on which we would write the code in the curly braces. The argument is the value we pass to the function when we call it. For example, greet("Alice")
would return "Hello, Alice!"
.
JavaScript provides several ways to define functions:
Function Declaration
Function declarations are named functions that are defined by a name. They are defined by the function
keyword. They are expressed in the following format:
function greet(name) { return `Hello, ${name}!`; } console.log(greet("Alice")); // "Hello, Alice!"
Function Expression
Function Expressions are anonymous functions that are assigned to a variable. These functions are not clearly defined until they are called, so they CANNOT be called before they are defined. They are expressed in the following format:
const greet = function(name) { return `Hello, ${name}!`; }; console.log(greet("Bob")); // The constant "greet" is a variable that calls a function with the parameter "Bob" and returns "Hello, Bob!"
Arrow Functions (ES6)
Arrow functions are a way to write anonymous functions in JavaScript. They are a more concise way to write functions. They are expressed in the following format:
const greet = (name) => `Hello, ${name}!`;
In the above example, we assign a constant to the function greet
. This is the same as writing:
const greet = function(name) { return `Hello, ${name}!`; }
Where name
is the parameter and =>
is the arrow operator, leading to the code in the curly braces. The $
is used to interpolate the value of the name
parameter into the string. In this way, we can write shorter and more readable code to achieve the same result. Here is the arrow function being used in full:
const greet = (name) => `Hello, ${name}!`; console.log(greet("Charlie")); // "Hello, Charlie!"
JavaScript String and Array Methods
Arrays and Strings are the two most common data types in JavaScript. Arrays are collections of elements enclosed by the []
brackets, and Strings are sequences of characters enclosed by the ''
or ""
quotes. Strings can ALSO act as arrays, in which you can manipulate the characters of the string as if it were an array.
JavaScript provides a variety of methods to manipulate strings and arrays, which are essential for handling data.
String Methods:
toUpperCase()
: Converts a string to uppercase.split(separator)
: Splits a string into an array of substrings.slice(start, end)
: Returns a new string that is a slice of the original string from the start index to the end index. Parameters are STRICTLY integers, and the start index is INCLUSIVE, and the end index is EXCLUSIVE.replace(oldValue, newValue)
: Replaces all occurrences ofoldValue
in the string withnewValue
.
Array Methods:
push(element)
: Adds an element to the end of an array.map(function)
: Creates a new array with the results of calling a function for every array element. The function goes through each element of the array and returns a new array with the results of each element in the same index.join(separator)
: Joins all elements of an array into a string, with the elements separated by theseparator
string.pop()
: Removes the last element from an array and returns that element.shift()
: Removes the first element from an array and returns that element.unshift(element)
: Adds an element to the beginning of an array.
Here's an example of using these methods:
let message = 'Hello, World'; let words = message.split(', '); // Here, we use the `split` method to split the `message` string into an array of words. let upperCase = function(word) { return word.toUpperCase(); // Here, we define a function that takes a word as an argument and returns the word in uppercase. } let upperWords = words.map(upperCase); // Here, we use the `map` method to apply the `upperCase` function to each element of the `words` array. console.log(upperWords); // Outputs: ["HELLO", "WORLD"]
DOM Manipulation
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree-like hierarchy of objects.
Selecting Elements
JavaScript provides several methods to select DOM elements:
// By ID const element = document.getElementById('myId'); // By class name const elements = document.getElementsByClassName('myClass'); // By tag name const paragraphs = document.getElementsByTagName('p'); // Using CSS selectors const element = document.querySelector('.myClass'); const elements = document.querySelectorAll('p');
Modifying Elements
Once you've selected an element, you can modify its content, attributes, and styles:
const element = document.getElementById('myId'); // Changing content element.textContent = 'New text content'; element.innerHTML = '<strong>New HTML content</strong>'; // Changing attributes element.setAttribute('class', 'newClass'); // Changing styles element.style.color = 'red'; element.style.fontSize = '20px';
Creating and Appending Elements
You can also create new elements and add them to the DOM:
// Create a new element const newParagraph = document.createElement('p'); newParagraph.textContent = 'This is a new paragraph.'; // Append it to an existing element const container = document.getElementById('container'); container.appendChild(newParagraph);
Event Handling
JavaScript can respond to various events that occur in the browser, such as clicks, key presses, form submissions, etc.
const button = document.getElementById('myButton'); button.addEventListener('click', function(event) { console.log('Button clicked!'); console.log(event); // The event object contains information about the event });
Basic Form Validation
JavaScript can be used to validate form inputs before they're submitted:
const form = document.getElementById('myForm'); form.addEventListener('submit', function(event) { const nameInput = document.getElementById('name'); if (nameInput.value.trim() === '') { event.preventDefault(); // Prevent form submission alert('Please enter your name'); } });
AJAX for Dynamic Content Fetching
AJAX (Asynchronous JavaScript and XML) allows you to update parts of a web page without reloading the entire page. Here's a basic example using the Fetch API to get data from an API and display it:
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { document.getElementById('output').innerHTML = data.message; }) .catch(error => console.error('Error:', error));
This method enhances user experience by making web pages feel more responsive and interactive.
Conclusion
This introduction to JavaScript covers the fundamental concepts you need to start adding interactivity to your web pages. As you progress, you'll learn more advanced concepts like asynchronous programming, working with APIs, and modern JavaScript frameworks.
Assignments
- Create a form validation script for the form you created in the HTML lesson. The criteria for validity in this form is:
- The name field must be filled out.
- The email field must be a VALID email address.
- The password field must be at least 8 characters long, and contain at least one number and one special character.
Remember to test your JavaScript in different browsers to ensure compatibility.
Happy coding!