The Window Object

The window object is the top-level object in the browser environment and represents the current browser window or tab. It provides access to various browser features and properties, such as the document object, screen information, and browser history.

console.log(window.innerWidth); // Get the inner width of the browser window
console.log(window.location.href); // Get the current URL
window.alert("Hello, World!"); // Display an alert

Timers

JavaScript provides two methods for scheduling code execution at a later time:

  • setTimeout(function, delay): Executes a function after a specified delay (in milliseconds).
  • setInterval(function, delay): Executes a function repeatedly at a specified interval (in milliseconds).
// Delay execution for 2 seconds
setTimeout(function() {
console.log("Delayed message");
}, 2000);
// Repeat every second
const intervalId = setInterval(function() {
console.log("Repeating message");
}, 1000);

Cookies and Web Storage

Cookies are small text files stored on the client-side that can be used to store and retrieve data. Web Storage provides a larger and more secure way to store data on the client-side.

  • document.cookie: Allows you to read and write cookies.
  • localStorage: Provides a key-value storage that persists across browser sessions.
  • sessionStorage: Provides a key-value storage that is specific to the current browser session.
// Set a cookie
document.cookie = "username=John Doe";
// Store data in localStorage
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme"); // "dark"

AJAX and Fetch API

AJAX (Asynchronous JavaScript and XML) allows you to send and receive data from a server asynchronously, without reloading the entire page. The newer Fetch API provides a more modern and flexible way to make AJAX requests.

// Using the Fetch API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// Using XMLHttpRequest (older method)
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed');
}
};
xhr.send();

In the next chapter, we'll cover error handling and debugging techniques in JavaScript.