JavaScript Fundamentals
Embedding JavaScript in HTML
Inline Script Tags
Place JavaScript code within <script></script> tags. These tags can appear anywhere in the HTML document, though placing them at the bottom of the <body> section improves page load performance.
<script>
alert("Welcome");
</script>
External File Inclusion
Store JavaScript in separate .js files and reference them in HTML:
<script src="js/main.js"></script>
Syntax Fundamentals
- JavaScript is case-sensitive
- Semicolons at line endings are optional
- Single-line comments use
//, multi-line comments use/* */ - Curly braces
{}define code blocks
Output Methods
alert()
Displays content in a modal dialog box:
window.alert("Notice"); // Browser shows a popup alert
write()
Inserts content directly into the HTML document:
document.write("Greetings"); // Renders directly to the webpage
log()
Writes output to the browser's developer console. Access via right-click → Inspect → Console, or press F12:
console.log("Farewell"); // Outputs to browser console
Variables
Naming Conventions
- Allowed characters: letters, digits, underscores
_, and dollar signs$ - Digits cannot appear as the first character
- Employ camelCase for multi-word identifiers
Variable Declaration
JavaScript employs dynamic typing, allowing variables to hold values of any type:
var count = 100;
count = "Anderson";
The var keyword declares variables with function scope. Variables declared with var can be redeclared within the same scope.
Modern Variable Keywords
let: Block-scoped variable declaration. Cannot be redeclared in the same scope.const: Declares a constant whose value cannot be reassigned after initialization.
Data Types and Operators
JavaScript distinguishes between primitive types and reference types.
Primitives:
number: numeric values (integers and decimals)
string: text, enclosed in single or double quotes
boolean: true or false
null: intentional absence of an object value
undefined: variable declared but not yet assigned
The typeof operator returns a variable's data type.
Operators:
JavaScript operators closely mirror Java, with one notable addition: the strict equality operator.
| Operator | Behavior |
|---|---|
== |
Performs type coercion before comparison |
=== |
Compares without type coercion |
var num = 42;
console.log(num == "42"); // true (coercion occurs)
console.log(num === "42"); // false (no coercion)
console.log(num === 42); // true
Type Conversions
String to Number:
parseInt() extracts numeric values from strings. Non-numeric characters after valid digits are discarded:
parseInt("25"); // 25
parseInt("25B70"); // 25
parseInt("C99"); // NaN (Not a Number)
To Boolean:
| Input Type | Conversion Result |
|---|---|
| Number | false for 0 and NaN; true for all others |
| String | false for empty string; true otherwise |
| Null | false |
| Undefined | false |
Functions
Functions encapsulate reusable blocks of code designed for specific tasks.
Function Declaration
// Declaration syntax
function calculateSum(x, y) {
return x + y;
}
// Expression syntax
var multiply = function(a, b) {
return a * b;
};
// Invocation
var sum = calculateSum(15, 25);
var product = multiply(8, 6);
// Extra arguments are ignored
var result = calculateSum(1, 2, 3, 4); // Uses only first two arguments
Parameters require no type specification due to JavaScript's dynamic typing. Return types are also undeclared—simply use the return keyword. Calling a function requires the function name followed by parentheses containing arguments. Surplus arguments beyond the parameter list are disregarded.
Array Objects
Arrays in JavaScript are dynamic, ordered collections that can hold mixed data types.
Array Creation
// Constructor syntax
var data = new Array(10, 20, 30, 40);
// Literal syntax
var data = [10, 20, 30, 40];
Element Access
var colors = ["red", "green", "blue"];
colors[3] = "yellow"; // Dynamically extends the array
Arrays exhibit dynamic length—they automatically expand when assigning to indices beyond the current size. Elements in expanded positions receive undefined until assigned values.
var numbers = [1, 2, 3];
numbers[7] = 100;
console.log(numbers[7]); // 100
console.log(numbers[5]); // undefined
Array Properties
length: Returns or sets the number of elements
var size = numbers.length;
Common Array Methods
var items = ["apple", "banana", "cherry"];
// Traverse with forEach
items.forEach(function(item) {
console.log(item);
});
// Append elements to end
items.push("date", "elderberry");
// Remove elements: splice(startIndex, deleteCount)
items.splice(1, 2); // Removes banana and cherry
String Objects
String Creation
// Constructor approach
var message = new String("Constructed String");
// Literal approach
var message = "Literal String";
Properties and Methods
length: Character count
var charCount = message.length;
Utility Methods:
| Method | Purpose |
|---|---|
charAt(index) |
Returns character at specified position |
indexOf(substring) |
Locates substring within string |
trim() |
Removes leading and trailing whitespace |
substring(start, end) |
Extracts characters between indices |
JavaScript Objects and JSON
Custom Objects
var person = {
username: "Alice",
userAge: 28,
userGender: "female",
speak: function() {
alert("Speaking...");
}
};
// Access properties
person.username;
// Invoke methods
person.speak();
JSON Format
JSON (JavaScript Object Notation) resembles JavaScript object syntax but requires double quotes around property names. It serves as a standard data interchange format for network communication.
{"username":"Alice","userAge":28,"userGender":"female"}
Working with JSON
// JSON string to JavaScript object
var jsonData = '{"username":"Alice","userAge":28}';
var jsObj = JSON.parse(jsonData);
console.log(jsObj.username); // Alice
// JavaScript object back to JSON string
var backToJson = JSON.stringify(jsObj);
console.log(backToJson); // {"username":"Alice","userAge":28}
BOM: Browser Object Model
BOM enables JavaScript interaction with the browser environment. Each browser component gets represented as an object.
BOM Structure:
- Window: Represents the browser window/tab
- Navigator: Contains browser application details and version info
- Screen: Provides display screen information
- History: Manages browsing session history
- Location: Handles URL and navigation
Window Object Methods
// Display alert dialog
alert("Notification");
window.alert("Equivalent syntax");
// Confirmation dialog returns boolean
var confirmed = confirm("Proceed with deletion?");
if (confirmed) {
// User clicked OK
}
// Recurring timer (executes repeatedly)
setInterval(function() {
console.log("Timer tick");
}, 3000);
// Delayed execution (fires once)
setTimeout(function() {
console.log("Delayed message");
}, 5000);
Location Object
Controls browser address bar behavior:
// Retrieve current URL
console.log(location.href);
// Navigate to specified address
location.href = "https://example.com";
DOM: Document Object Model
DOM transforms HTML documents into manipulable objects. JavaScript can traverse and modify page elements through this model.
DOM Component Objects:
- Document: The entire document tree
- Element: Individual HTML tags
- Attribute: Tag attributes
- Text: Element content
- Comment: HTML comments
Element Selection Methods
// Find by ID (returns single element)
var header = document.getElementById('mainHeader');
// Find by tag name (returns collection)
var paragraphs = document.getElementsByTagName('p');
// Find by name attribute (returns collection)
var formFields = document.getElementsByName('userInput');
// Find by class name (returns collection)
var cards = document.getElementsByClassName('card');
DOM Manipulation Example
// Retrieve all div elements
var containers = document.getElementsByTagName('div');
// Modify first div's content
var firstDiv = containers[0];
firstDiv.innerHTML = "Content Updated";
Event Handling
Events are actions occurring on HTML elements—user clicks, mouse movements, keyboard input. Event handlers execute JavaScript code when specific events fire.
Binding Approaches
Inline Binding:
<button onclick="handleClick()">Click Me</button>
<script>
function handleClick() {
alert("Button activated");
}
</script>
Programmatic Binding:
<button id="actionBtn">Trigger Action</button>
<script>
document.getElementById('actionBtn').onclick = function() {
alert("Button activated");
};
</script>
Frequently Used Events
| Event | Trigger |
|---|---|
| onclick | Element receives click |
| onmouseover | Mouse enters element |
| onmouseout | Mouse leaves element |
| onfocus | Element gains focus |
| onblur | Element loses focus |
| onkeydown | Key is pressed |
| onload | Page or image finishes loading |
| onsubmit | Form is submitted |