Comprehensive Guide to JavaScript Core Concepts and Web APIs

Introduction to JavaScript

JavaScript is a dominant scripting language primarily used to create dynamic and interactive web content. It integrates seamlessly with HTML and CSS to build modern web applications.

Integrating JavaScript into Web Pages

JavaScript can be embedded directly within an HTML document or linked as an external file.

Internal Script

Use the <script> tag inside your HTML to write JS code directly:

<script>
  console.log("Internal script executed");
</script>

External Script

For better maintainability, write JavaScript in a separate file (e.g., app.js) and link it:

<script src="js/app.js"></script>

Note: The <script> tag must be properly closed. It does not require the type attribute in HTML5, as JavaScript is the default.

Strict Mode

ES5 introduced strict mode to catch common coding mistakes. Always enable it at the top of your script to prevent silent errors and enforce better coding practices.

<script>
  'use strict';
  // Prevents the accidental creation of global variables
  let count = 10; 
</script>

Fundamental Data Types and Syntax

Variables

Modern JavaScript prefers let for block-scoped variables and const for constants, replacing the older var keyword which is function-scoped.

Primitives

  • Number: JavaScript does not differentiate between integers and floating-point numbers. ``` 42 // Integer 3.14 // Float 2.998e8 // Scientific notation NaN // Not a Number Infinity // Infinite value

  • String: Enclosed in single or double quotes, or backticks for template literals. ``` 'Hello' "World" Template

  • Boolean: true or false.

Comparison Operators

Avoid using the loose equality operator (==), as it performs type coercion. Always use strict equality (===) to ensure both value and type match.

1 == '1'   // true (type coercion)
1 === '1'  // false (strict equality)

Special case: NaN is not equal to itself. Use Number.isNaN() to check for it. Also, be cautious of floating-point precision issues; use a small epsilon for comparisons.

console.log(0.1 + 0.2 === 0.3); // false
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // true

Null and Undefined

  • null explicitly represents an empty or non-existent value.
  • undefined means a variable has been declared but not assigned a value.

Arrays

Array are ordered collections that can hold mixed data types.

const inventory = ['apple', 42, null, true];

Accessing an out-of-bounds index returns undefined.

Objects

Objects are collections of key-value pairs enclosed in curly braces.

const employee = {
  name: "Alice",
  role: "Engineer",
  active: true
};
console.log(employee.name); // Alice

Control Flow

Standard conditional and looping constructs apply.

// If-Else
let status = 'active';
if (status === 'active') {
  console.log('Online');
} else {
  console.log('Offline');
}

// For Loop
for (let i = 0; i < 5; i++) {
  console.log(i);
}

// While Loop
let attempts = 0;
while (attempts < 3) {
  attempts++;
}

// For...of (Iterable traversal)
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
  console.log(color);
}

// Array.forEach
colors.forEach((color, index) => {
  console.log(`${index}: ${color}`);
});

ES6 Collections: Map and Set

Map

A key-value pair collection where keys can be of any type.

const userRoles = new Map();
userRoles.set('alice', 'admin');
userRoles.set('bob', 'editor');
console.log(userRoles.get('alice')); // admin
userRoles.delete('bob');

Set

A collection of unique values.

const uniqueIds = new Set([1, 2, 3, 3]);
uniqueIds.add(4);
console.log(uniqueIds.has(2)); // true
uniqueIds.delete(1);

Functions

Declarations and Expressions

// Function Declaration
function calculateArea(radius) {
  return Math.PI * radius * radius;
}

// Function Expression
const calculateCircumference = function(radius) {
  return 2 * Math.PI * radius;
};

Arguments and Rest Parameters

Functions can accept variable arguments. The arguments object (array-like) holds all passed parameters. ES6 introduced rest parameters for cleaner syntax.

function logParams(required, ...extras) {
  console.log('Required:', required);
  console.log('Extras:', extras);
}
logParams('Core', 'A', 'B', 'C');
// Extras: ['A', 'B', 'C']

Variable Scope

Variables defined inside a function are local. Global variables attach to the window object in browsers. Use let and const to avoid scope leakage and accidental global declarations.

Methods and the this Keyword

When a function is a property of an object, it becomes a method. this refers to the object that invokes the method.

const server = {
  port: 8080,
  getPort: function() {
    return this.port;
  }
};
console.log(server.getPort()); // 8080

You can explicitly bind this using apply() or call().

function extractPort() {
  return this.port;
}
console.log(extractPort.apply(server, [])); // 8080

Standard Built-in Objects

Date

const now = new Date();
console.log(now.getFullYear());
console.log(now.getTime()); // Unix timestamp

JSON

JSON is the standard format for data interchange. JavaScript provides methods to convert between JSON strings and objects.

const product = { item: "Laptop", price: 999 };
const jsonString = JSON.stringify(product);
const parsedObject = JSON.parse(jsonString);

Object-Oriented Programming

Prototypal Inheritance

Objects can inherit directly from other objects using __proto__ (though Object.create() is preferred).

const baseDevice = {
  powerOn() { console.log(this.name + ' is on'); }
};
const laptop = { name: 'MacBook' };
laptop.__proto__ = baseDevice;
laptop.powerOn(); // MacBook is on

ES6 Classes

Classes provide syntactic sugar over the prototype-based inheritance model.

class Vehicle {
  constructor(type) {
    this.type = type;
  }
  identify() {
    return `This is a ${this.type}`;
  }
}

class Car extends Vehicle {
  constructor(type, brand) {
    super(type);
    this.brand = brand;
  }
}
const myCar = new Car('Sedan', 'Toyota');

Browser Object Model (BOM)

The BOM allows JavaScript to interact with the browser environment.

  • window: The global object representing the browser window. Properties include innerHeight and innerWidth.
  • navigator: Contains browser metadata (e.g., userAgent). Avoid relying on it for critical logic due to spoofing.
  • location: Represents the current URL. location.href gets/sets the URL, location.reload() refreshes the page.
  • document: The entry point to the DOM. Also exposes document.cookie.
  • history: Manipulates the browser history (history.back(), history.forward()).

Document Object Model (DOM)

The DOM represents the page structure as a tree of nodes. Core operations include selecting, updating, deleting, and creating nodes.

Selecting Nodes

const header = document.getElementsByTagName('h1');
const mainContent = document.getElementById('main');
const warnings = document.getElementsByClassName('alert');

Updating Nodes

const container = document.getElementById('main');
container.innerText = 'Updated Text';
container.innerHTML = '<strong>Bold Text</strong>';
container.style.color = 'blue';
container.style.fontSize = '16px'; // Use camelCase for CSS properties

Deleting Nodes

You must navigate to the parent node to remove a child.

const childNode = document.getElementById('remove-me');
childNode.parentElement.removeChild(childNode);

Inserting Nodes

const list = document.getElementById('my-list');
const newItem = document.createElement('li');
newItem.id = 'item-3';
newItem.innerText = 'Third Item';
list.appendChild(newItem);

// Insert before a specific node
const existingItem = document.getElementById('item-2');
list.insertBefore(newItem, existingItem);

Form Handling and Validation

JavaScript can read and modify form inputs, intercept submissions, and validate data before sending it to the server.

const emailInput = document.getElementById('email');
console.log(emailInput.value); // Get value
emailInput.value = 'test@example.com'; // Set value

// For radio/checkboxes, check the 'checked' property
const termsCheckbox = document.getElementById('terms');
console.log(termsCheckbox.checked); 

When submitting forms securely, intercept the onsubmit event to hash sensitive data (like passwords) using a hidden field before transmission.

jQuery Overview

jQuery is a library designed to simplify HTML DOM traversal, manipulation, and event handling.

Selectors and Events

jQuery utilizes CSS selectors to target elements.

$('#submit-btn').click(function() {
  alert('Button clicked!');
});

DOM Manipulation

// Text and HTML
$('#output').text('Hello jQuery');
$('#output').html('<em>Italic</em>');

// CSS
$('#output').css({ "color": "green", "font-weight": "bold" });

// Visibility
$('#output').show();
$('#output').hide();
$('#output').toggle();

Tags: javascript ES6 DOM BOM jquery

Posted on Wed, 30 Sep 2026 16:33:46 +0000 by legio