JavaScript Essentials and Web APIs: Syntax, DOM, BOM, and jQuery
Syntax and Core Concepts
Variable Declarations and Types
JavaScript is a dynamically typed language. Variables can be declared using var, let, or const.
var: Function-scoped, hoisted.let: Block-scoped, not hoisted.const: Block-scoped, must be initialized, cannot be reassigned.
let userAge = 28;
const userName = 'Alice';
userAge = 29; // Valid
// userName = 'Bob'; // Throws TypeError
Data types are divided into primitives (String, Number, Boolean, Undefined, Null, Symbol, BigInt) and reference types (Object, Array, Function).
Use typeof to inspect a variable's type. Note that typeof null returns "object".
let score = 100;
console.log(typeof score); // "number"
let isLoggedIn = true;
console.log(typeof isLoggedIn); // "boolean"
Type Coercion and Conversion
When interacting with user inputs (which are always strings), type conversion is often necessary.
- To String:
String(value)or implicit concatenationvalue + ''. - To Number:
Number(value),parseInt(value),parseFloat(value), or implicit math operationsvalue - 0. - To Boolean:
Boolean(value). Falsy values include0,"",null,undefined,NaN, andfalse.
let inputVal = '42.5';
let integerPart = parseInt(inputVal, 10); // 42
let floatPart = parseFloat(inputVal); // 42.5
let isValid = Boolean(inputVal); // true
Functions and Scope
Functions can be declared or expressed.
// Function Declaration
function calculateSum(a, b) {
return a + b;
}
// Function Expression
const multiplyValues = function(x, y) {
return x * y;
};
Before ES6, JavaScript only had function scope and global scope. let and const introduced block scope. Scope chains determine variable accessibility. Hoisting moves function and variable declarations to the top of their scope, though variable initializations are not hoisted.
Objects and Prototypes
Object Creation
Objects can be created using literals, the Object constructor, or custom constructor functions.
// Literal
const vehicle = {
brand: 'Tesla',
model: 'Model 3',
accelerate() {
console.log('Speeding up');
}
};
// Constructor Function
function Employee(empName, empRole) {
this.name = empName;
this.role = empRole;
}
const dev = new Employee('John', 'Developer');
Prototypes
Every JavaScript object has a prototype. Constructor functions possess a prototype property, while instances possess a __proto__ property pointing back to it.
Employee.prototype.greet = function() {
console.log(`Hello, I am ${this.name}`);
};
dev.greet(); // "Hello, I am John"
console.log(Employee.prototype === dev.__proto__); // true
Built-in Objects
Standard built-in objects like Math, Date, and Array provide essential utilities.
console.log(Math.PI);
console.log(Math.floor(4.9)); // 4
console.log(Math.random()); // 0 to <1
const currentDate = new Date();
console.log(currentDate.getFullYear());
const numbers = [10, 20, 30];
console.log(numbers.includes(20)); // true
console.log(numbers.push(40)); // 4
Browser Interaction: DOM
The Document Object Model represents the HTML document structure.
Element Selection and Manipulation
const header = document.getElementById('main-title');
const buttons = document.querySelectorAll('.action-btn');
header.textContent = 'Updated Title';
header.style.color = 'navy';
header.classList.add('highlight');
Event Handling
Events respond to user actions. Modern binding uses addEventListener.
const submitBtn = document.querySelector('#submitBtn');
submitBtn.addEventListener('click', function(event) {
event.preventDefault();
console.log('Button triggered', event.target);
});
Event delegation leverages event bubbling by attaching a single listener to a parent element.
document.querySelector('#item-list').addEventListener('click', function(e) {
if (e.target.tagName === 'LI') {
console.log('List item selected:', e.target.textContent);
}
});
Browser Interaction: BOM
The Browser Object Model provides access to the browser window.
Window and Navigation
const currentProtocol = window.location.protocol;
const currentHost = window.location.hostname;
// Redirecting
// window.location.href = 'https://example.com';
Timers
const timeoutId = setTimeout(() => {
console.log('Executed after 2 seconds');
}, 2000);
clearTimeout(timeoutId);
const intervalId = setInterval(() => {
console.log('Repeats every second');
}, 1000);
Web Storage
Data can be persisted in the browser using localStorage (persistent) and sessionStorage (cleared on tab close).
localStorage.setItem('config', 'dark-mode');
const config = localStorage.getItem('config');
localStorage.removeItem('config');
jQuery Essentials
jQuery simplifies DOM traversal and manipulation.
Selectors and DOM Manipulation
$(document).ready(function() {
$('.panel').hide();
$('#toggle-btn').on('click', function() {
$(this).next('.panel').slideToggle(300);
});
});
Event Binding and Delegation
// Delegation
$('.list-container').on('click', '.item', function() {
$(this).toggleClass('selected');
});
// Stopping event propagation
$('.inner-box').on('click', function(e) {
e.stopPropagation();
});
Common Utilities
URL Parameter Extraction
function extractUrlParam(key) {
const params = new URLSearchParams(window.location.search);
return params.get(key);
}
// URL: site.com?user=alice
// extractUrlParam('user') -> 'alice'
Cryptographically Secure Random ID
function generateUniqueId(len = 12) {
const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const randomBytes = crypto.getRandomValues(new Uint8Array(len));
return Array.from(randomBytes, byte => charSet[byte % charSet.length]).join('');
}
Node.js Directory Archiver
A utility script to zip a build folder.
const fs = require('fs');
const archiver = require('archiver');
const path = require('path');
const outputPath = path.join(__dirname, 'release.zip');
const output = fs.createWriteStream(outputPath);
const archive = archiver('zip', { zlib: { level: 9 } });
archive.pipe(output);
archive.directory(path.join(__dirname, 'dist'), false);
archive.finalize();