Core Concepts and Techniques in JavaScript
JavaScript Overview
JavaScript is a client-side interpreted scripting language, executed line-by-line by the JavaScript engine within web browsers.
Key Characteristics
- Scripting Language: Interpreted during runtime without prior compilation.
- Object-Based: Supports object creation and utilization of existing objects.
- Simple Syntax: Uses loosely typed variables and compact design.
- Dynamic Behavior: Event-driven, responding to user interactions without server involvement.
- Client-Side Execution: Primarily runs in browsers, unlike server-side languages like PHP or ASP.
Common Applications
- Embedding dynamic content in HTML pages.
- Handling browser events.
- Manipulating HTML elements.
- Validating data before server submission.
- Detecting browser information.
- Managing cookies.
- Server-side programming with Node.js.
Note: JavaScript differs from Java as a weakly typed language, allowing functions to return any data type.
Document Object Model (DOM)
The DOM represents HTML elements as a tree structure.
Creating New Elements
To add elements, create a node and append it to an existing elemant.
<div id="container">
<p id="para1">First paragraph.</p>
<p id="para2">Second paragraph.</p>
</div>
<script>
const newParagraph = document.createElement('p');
const textNode = document.createTextNode('New paragraph content.');
newParagraph.appendChild(textNode);
const containerElement = document.getElementById('container');
containerElement.appendChild(newParagraph);
</script>
Modifying Existing Elements
Updating Content
Use the innerHTML property.
<p id="demo">Original text.</p>
<script>
document.getElementById('demo').innerHTML = 'Updated text.';
</script>
Changing Attributes
Modify attributes directly.
<img id="pic" src="original.jpg">
<script>
document.getElementById('pic').src = 'new.jpg';
</script>
Adjusting Styles
Alter CSS properties.
<p id="styled">Sample text.</p>
<script>
document.getElementById('styled').style.color = 'red';
</script>
Event Handling
Adding Events to Elements
Attach click events.
<button id="actionBtn">Click</button>
<script>
document.getElementById('actionBtn').onclick = function() {
alert('Button clicked!');
};
</script>
Event Binding for Dynamic Elements
Use event delegation for dynamically created elements.
// With jQuery
$('#parent').on('click', '.dynamic', function() {
console.log($(this).text());
});
// Without jQuery
const parent = document.getElementById('parent');
parent.addEventListener('click', function(event) {
if (event.target.classList.contains('dynamic')) {
console.log(event.target.textContent);
}
});
Looping Event Bindings
Avoid closure issues in loops.
<div class="links">
<a href="#" class="item">Link 1</a>
<a href="#" class="item">Link 2</a>
<a href="#" class="item">Link 3</a>
</div>
<script>
const items = document.querySelectorAll('.item');
items.forEach((link, index) => {
link.dataset.index = index;
link.onclick = function() {
alert(this.dataset.index);
};
});
</script>
Browser Object Model (BOM)
The BOM enables interaction with the browser.
Window Object
Represents the browser window; global variables and functions are part of it.
Common Methods
open(url, name, features): Opens a new window.close(): Closes the current window.alert(message): Displays an alert box.confirm(message): Shows a confirmation dialog.prompt(message, default): Presents an input prompt.back(): Navigates back (similar tohistory.back()).forward(): Navigates forward (similar tohistory.forward()).
Location Object
Manages URL information.
Properties
host: Server name and port.hostname: Server name.href: Full URL.pathname: Path and filename.port: Port number.protocol: Protocol (e.g., http).search: Query string.
Methods
assign(url): Loads a new page, preserving history.replace(url): Loads a new page without history.reload(): Refreshes the current page.
History Object
Controls browser history.
history.go(1); // Forward
history.go(-1); // Back
history.go(0); // Refresh
Function Definitions
Two primary ways to define functions.
Function Declaration
Can be called before definition within the same script.
sayHello(); // Works if defined in same script
function sayHello() {
console.log('Hello!');
}
Function Expression
Must be defined before calling.
const greet = function() {
console.log('Hi!');
};
greet(); // Call after definition
Data Types in JavaScript
Six data types: Number, Boolean, String, Object, Undefined, Null.
Type Detection with typeof
typeof 42; // "number"
typeof true; // "boolean"
typeof 'text'; // "string"
typeof {}; // "object"
typeof undefined; // "undefined"
typeof null; // "object"
typeof function() {}; // "function"
Number Type
Includes integers and floats; NaN indicates non-numeric values.
isNaN(123); // false
isNaN('abc'); // true
Boolean Type
Values: true or false.
String Type
Has a length property; convert with String() or toString().
Undefined Type
Single value undefined for uninitialized variables.
Null Type
Represents an empty object pointer.
Object Types
Complex data structures.
Boolean Object
const flag = new Boolean(false);
console.log(flag); // Boolean object
Math Object
Provides mathematical constants and functions.
Date Object
const now = new Date();
console.log(now.getFullYear()); // Current year
JavaScript Objects
const user = {
name: 'Alice',
age: 30
};
Arrays
const colors = ['red', 'blue', 'green'];
colors.forEach(color => console.log(color));
Function Type
Functions are objects with properties and methods.
const add = function(a, b) {
return a + b;
};
Value vs. Reference
- Value types: Copied by value (e.g., numbers).
- Reference types: Copied by reference (e.g., objects).
let x = 10;
let y = x;
x = 20;
console.log(y); // 10
let obj1 = { value: 10 };
let obj2 = obj1;
obj2.value = 20;
console.log(obj1.value); // 20
Variable Scope
Global Scope
Variables declared outside functions or without var.
var globalVar = 'I am global';
function show() {
console.log(globalVar); // Accessible
}
Local (Function) Scope
Variables declared with var inside functions.
function test() {
var localVar = 'I am local';
console.log(localVar); // Accessible
}
// console.log(localVar); // Error
Hoisting
Variable declarations are moved to the top of their scope.
function example() {
console.log(value); // undefined
var value = 'hoisted';
console.log(value); // 'hoisted'
}
Block Scope with let
Variables declared with let are confined to blocks.
let blockVar = 5;
if (true) {
let blockVar = 10;
console.log(blockVar); // 10
}
console.log(blockVar); // 5
Constants with const must be initialized and cennot be reassigned.
const PI = 3.14;
// PI = 3.14159; // Error
Page Navigation and Parameter Passing
Navigation Methods
// Using location
window.location.href = 'https://example.com';
// Using history
history.back();
history.forward();
// Meta tag in HTML
// <meta http-equiv="refresh" content="5;url=page.html">
Parameter Passing
URL Parameters
function getParams(url) {
const query = url.split('?')[1];
const pairs = query.split('&');
const result = {};
pairs.forEach(pair => {
const [key, value] = pair.split('=');
result[key] = decodeURIComponent(value);
});
return result;
}
Using Cookies
function setCookie(name, value, days) {
const expires = new Date();
expires.setTime(expires.getTime() + days * 86400000);
document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()}`;
}
function getCookie(name) {
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
return match ? decodeURIComponent(match[2]) : null;
}
Using localStorage
// Store data
localStorage.setItem('key', 'value');
// Retrieve data
const data = localStorage.getItem('key');
Timers in JavaScript
Single Execution with setTimeout
const timeoutId = setTimeout(() => {
console.log('Executed after delay');
}, 1000);
clearTimeout(timeoutId); // Cancel if needed
Repeated Execution with setInterval
const intervalId = setInterval(() => {
console.log('Repeating every second');
}, 1000);
clearInterval(intervalId); // Stop repetition