A Step-by-Step Guide to Interactive Web Development
Including ES6+, Error Handling & jQuery
JavaScript (JS) is a programming language primarily used in websites to make pages interactive:
ποΈ HTML = Skeleton (structure)
π¨ CSS = Clothes (style)
π§ JavaScript = Brain (interactivity)
Right-click β Inspect β Console tab
Add <script> tags
CodePen, JSFiddle, JSBin
// Method 2: In HTML file
<script>
console.log('Hello from JavaScript!');
</script>
// Or external file
<script src="script.js"></script>
let name = "Alex"; // Text (string)
let age = 20; // Number
let isStudent = true; // Boolean
let items = ["a", "b"]; // Array
let person = {name: "Jo"}; // Object
let = Reassignable variable
const = Constant (cannot reassign)
var = Old keyword (avoid)
β’ Start with letter, _, or $
β’ Case-sensitive
β’ Use camelCase convention
| Type | Example | Description |
|---|---|---|
| String | "Hello", 'World' | Text |
| Number | 10, 3.14 | Integer or decimal |
| Boolean | true, false | True or False |
| null | null | Intentionally empty |
| undefined | undefined | Not yet defined |
| Symbol | Symbol('id') | Unique identifier |
| BigInt | 9007199254740991n | Large integers |
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
5 + 3 // 8 (add)
10 - 2 // 8 (subtract)
2 * 4 // 8 (multiply)
16 / 2 // 8 (divide)
2 ** 3 // 8 (power)
10 % 3 // 1 (modulo)
let x = 5;
x += 3; // x = 8
x -= 2; // x = 6
x *= 2; // x = 12
x++; // x = 13
x--; // x = 12
let name = "Lina";
let msg1 = "Hello, " + name; // Concatenation
let msg2 = `Hello, ${name}!`; // Template literal (ES6)
== | Equal (value) | 5 == "5" β
|
=== | Strict equal | 5 === "5" β |
!= | Not equal | 5 != 6 β
|
!== | Strict not equal | 5 !== "5" β
|
> < >= <= | Comparisons | 8 > 6 β
|
// AND - both must be true
true && true // true
// OR - at least one true
true || false // true
// NOT - inverts value
!true // false
π‘ Always use === and !==
let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else {
console.log("C");
}
let age = 18;
let status = age >= 18
? "Adult"
: "Minor";
switch(day) {
case 1: return "Mon";
case 2: return "Tue";
default: return "?";
}
// 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;
// Default Parameters
const welcome = (name = "Guest") => `Hi, ${name}`;
π‘ Arrow functions don't have their own this context
for (let i = 0; i < 5; i++) {
console.log(i);
}
// 0, 1, 2, 3, 4
let i = 0;
while (i < 3) {
console.log(i++);
}
const arr = ["a", "b", "c"];
for (const item of arr) {
console.log(item);
}
const obj = {x: 1, y: 2};
for (const key in obj) {
console.log(key, obj[key]);
}
let fruits = ["apple", "banana", "mango"];
fruits[0] // "apple" (index starts at 0)
fruits.length // 3
fruits.push("orange") // Add to end
fruits.pop() // Remove from end
fruits.unshift("kiwi") // Add to start
fruits.shift() // Remove from start
const nums = [1, 2, 3, 4, 5];
nums.map(n => n * 2) // [2, 4, 6, 8, 10]
nums.filter(n => n > 2) // [3, 4, 5]
nums.reduce((a,b) => a+b) // 15
nums.find(n => n > 3) // 4
nums.includes(3) // true
const student = {
name: "Amadou",
age: 20,
grades: [85, 90, 78],
getAverage() {
return this.grades.reduce((a,b) => a+b) / this.grades.length;
}
};
student.name // "Amadou"
student["age"] // 20
student.getAverage() // 84.33
student.school = "MIT"; // Add property
const {name, age} = student;
const [first, ...rest] = [1, 2, 3]; // first=1, rest=[2,3]
DOM = Document Object Model (page structure as objects)
// Selecting Elements
const el = document.getElementById('myId');
const els = document.querySelectorAll('.myClass');
const btn = document.querySelector('button');
// Modifying Elements
el.textContent = "New text";
el.innerHTML = "<strong>Bold</strong>";
el.style.color = "red";
el.classList.add("active");
// Events
btn.addEventListener('click', () => {
alert('Clicked!');
});
try {
// Code that might fail
let result = riskyOperation();
} catch (error) {
// Handle the error
console.error("Error:", error.message);
} finally {
// Always runs
console.log("Cleanup done");
}
// Throwing custom errors
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero");
return a / b;
}
setTimeout(() => {
console.log("After 1s");
}, 1000);
fetch('/api/data')
.then(r => r.json())
.then(d => console.log(d))
.catch(e => console.error(e));
async function getData() {
try {
const res = await fetch('/api');
const data = await res.json();
return data;
} catch (err) {
console.error(err);
}
}
π‘ async/await makes asynchronous code look synchronous and easier to read
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1,2,3,4]
const obj1 = {a: 1};
const obj2 = {...obj1, b: 2}; // {a:1,b:2}
const val = obj?.prop?.nested;
// Returns undefined if any is null
const val = null ?? "default";
// "default" (only for null/undefined)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} sounds`);
}
}
jQuery is a fast, small JavaScript library that simplifies DOM manipulation
<!-- CDN -->
<script src="https://code.jquery.com/
jquery-3.7.1.min.js"></script>
// Wait for DOM to load
$(document).ready(function() {
// Your code here
});
// Short version
$(function() {
// Your code here
});
π‘ $ is an alias for jQuery
| Vanilla JS | jQuery | Description |
|---|---|---|
document.getElementById('id') | $('#id') | By ID |
document.getElementsByClassName('c') | $('.c') | By Class |
document.querySelectorAll('p') | $('p') | By Tag |
document.querySelector('[data-x]') | $('[data-x]') | By Attribute |
// Advanced selectors
$('ul li:first') // First li in ul
$('input:checked') // Checked inputs
$('div.active') // Divs with class active
$('p:contains("hello")') // P containing "hello"
// Get text content
$('#el').text();
// Set text content
$('#el').text('New text');
// Get/Set HTML
$('#el').html('<b>Bold</b>');
// Get/Set value (inputs)
$('input').val();
$('input').val('new value');
// CSS
$('#el').css('color', 'red');
$('#el').css({color: 'red', fontSize: '20px'});
// Classes
$('#el').addClass('active');
$('#el').removeClass('active');
$('#el').toggleClass('active');
// Attributes
$('img').attr('src', 'new.jpg');
// Click event
$('#btn').click(function() {
alert('Clicked!');
});
// Multiple events with on()
$('#input').on('focus blur', function(e) {
console.log(e.type);
});
// Event delegation (for dynamic elements)
$('ul').on('click', 'li', function() {
$(this).toggleClass('selected');
});
// Common events: click, dblclick, mouseenter, mouseleave,
// keydown, keyup, submit, change, focus, blur, scroll
$('#el').hide();
$('#el').show();
$('#el').toggle();
// With duration (ms)
$('#el').hide(500);
$('#el').show('slow');
$('#el').fadeIn();
$('#el').fadeOut();
$('#el').fadeToggle();
$('#el').fadeTo(500, 0.5);
$('#el').slideUp();
$('#el').slideDown();
$('#el').slideToggle();
$('#el').animate({
opacity: 0.5,
left: '+=50px',
height: '200px'
}, 1000);
// Simple GET request
$.get('/api/data', function(response) {
console.log(response);
});
// POST request
$.post('/api/submit', {name: 'John', age: 25}, function(res) {
console.log(res);
});
// Full AJAX control
$.ajax({
url: '/api/data',
method: 'POST',
data: JSON.stringify({id: 1}),
contentType: 'application/json',
success: function(res) { console.log(res); },
error: function(err) { console.error(err); }
});
| Task | jQuery | Vanilla JS |
|---|---|---|
| Select element | $('#id') | document.getElementById('id') |
| Add class | $el.addClass('x') | el.classList.add('x') |
| Set text | $el.text('Hi') | el.textContent = 'Hi' |
| Click event | $el.click(fn) | el.addEventListener('click',fn) |
| AJAX | $.get(url,fn) | fetch(url).then(fn) |
π‘ Modern JS has caught up! Use jQuery for legacy projects or when you need its convenience. For new projects, consider vanilla JS or modern frameworks.
= instead of === for comparisonNumber() or parseInt()0, not 1null or undefinedmyFunc vs myFunc()let/const scope with varasync/await properly with Promisesπ‘ Place <script> at the end of <body> or use defer attribute
Check values at each step
They show line numbers!
Use DevTools debugger
// Useful console methods
console.log("Message");
console.error("Error!");
console.warn("Warning");
console.table([{a:1}, {a:2}]); // Display as table
console.time('x'); /* code */ console.timeEnd('x'); // Measure time
πͺ Errors are part of learning! Test code in small pieces.
Thank You! π