Everything you need as a full stack developer

JavaScript window object (global scope) and common properties

- Posted in Frontend Developer by

TL;DR In JavaScript, variables declared outside of a function become properties of the global object, which is the window object in web browsers, allowing them to be accessed globally using dot or bracket notation.

The Window Object: The Global Scope of JavaScript

As a developer, you're probably familiar with the concept of scope in programming languages. In JavaScript, every variable or function declared has a specific scope where it can be accessed. But have you ever wondered what happens when you declare a variable outside of any function? Where does it live? This is where the window object comes into play.

The Window Object: A Global Scope

In JavaScript, whenever you declare a variable outside of a function or block, it becomes a property of the global object. In web browsers, this global object is the window object. Think of it like a namespace that contains all the variables and functions declared in your code.

When you create a new variable using let, const, or var outside of any function, it gets attached to the window object as a property. This means you can access those variables from anywhere in your code by using the dot notation (window.propertyName) or bracket notation (window['propertyName']).

let globalVariable = 'Hello World!';
console.log(window.globalVariable); // outputs: Hello World!

Common Properties of the Window Object

The window object has several properties that are commonly used in web development. Let's take a look at some of them:

Location and Navigator Objects

  • location: This property provides information about the current URL, such as the protocol (protocol), hostname (hostname), port (port), pathname (pathname), search (search), and hash (hash) parts.
  • navigator: This object contains properties like appName, appCodeName, appMinorVersion, appMinorVersionId, productSub, userAgent, and more, which help you identify the browser type and version.
console.log(location.protocol); // outputs: http:
console.log(navigator.userAgent); // outputs: ... (Browser User Agent string)

Screen and History Objects

  • screen: This property provides information about the screen resolution (width, height), pixel depth, color depth, and more.
  • history: This object allows you to manipulate the browser's history stack using methods like back(), forward(), go(), and pushState().
console.log(screen.width); // outputs: screen width in pixels
console.log(history.length); // outputs: current history length

Other Properties

  • document: This property provides access to the HTML document object, which allows you to interact with elements on the page.
  • innerHeight and innerWidth: These properties give you the dimensions of the browser window's content area (excluding borders).
  • scrollX and scrollY: These properties let you get or set the horizontal and vertical scroll positions.
console.log(document.body); // outputs: <body> element
console.log(innerHeight); // outputs: current inner height in pixels

In Conclusion

The window object is a fundamental concept in JavaScript that every developer should understand. By knowing how it works and what properties it contains, you'll be able to write more efficient and effective code for web development projects. Whether you're working on client-side logic or integrating with browser APIs, the window object will become your trusted companion.

Now that you've learned about the window object and its common properties, go ahead and experiment with them in your own JavaScript code!

Key Use Case

Create a simple web application for tracking personal expenses. When users access the app, display their total spent amount using the window object.

Setup

  • Create an HTML file (index.html) with a basic structure and JavaScript file (script.js) to handle logic.
  • Add two buttons: "Add Expense" and "View Total Spent".
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Expense Tracker</title>
</head>
<body>
    <h1>Expense Tracker</h1>
    <button id="add-expense-btn">Add Expense</button>
    <button id="view-total-spent-btn">View Total Spent</button>
    <p>Total Spent: $0.00</p>

    <script src="script.js"></script>
</body>
</html>
// script.js
let totalSpent = 0;

document.getElementById('add-expense-btn').addEventListener('click', () => {
    let amount = parseFloat(prompt('Enter expense amount:'));
    if (!isNaN(amount)) {
        totalSpent += amount;
        document.querySelector('#total-spent-p').textContent = `Total Spent: $${totalSpent.toFixed(2)}`;
    }
});

document.getElementById('view-total-spent-btn').addEventListener('click', () => {
    console.log(`window.totalSpent: ${window.totalSpent}`);
});

Using the Window Object

  • When users click "Add Expense", prompt them to enter an amount.
  • Update totalSpent and display it on the page using document.querySelector('#total-spent-p').
  • When users click "View Total Spent", log the current totalSpent value to the console.

This simple example demonstrates how to use the window object to store a variable (totalSpent) that can be accessed and updated throughout the application.

Finally

Global Variables vs Window Object

One key takeaway from understanding the window object is knowing how it affects global variables in your code. When you declare a variable outside of any function, it becomes a property of the global object, which is the window object in web browsers. This means that all global variables are attached to the window object and can be accessed using the dot notation or bracket notation.

For example, consider the following code:

let globalVariable = 'Hello World!';
console.log(window.globalVariable); // outputs: Hello World!

In this case, globalVariable is a property of the window object. This can lead to unexpected behavior if not handled properly. For instance, if you're working with multiple JavaScript files or libraries that declare global variables with the same name, it could cause conflicts.

It's essential to be mindful of this when writing code and consider using a different approach, such as encapsulating your logic within functions or objects, to avoid potential issues.

Recommended Books

  • "JavaScript: The Definitive Guide" by David Flanagan: A comprehensive guide to JavaScript that covers the language in detail.
  • "Eloquent JavaScript" by Marijn Haverbeke: A book that explores the basics of programming and the JavaScript language, with a focus on practical examples and exercises.
  • "Speaking JavaScript" by Shalabh Aggarwal: A book that provides an introduction to the JavaScript language, covering its syntax, semantics, and best practices for writing effective code.
Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more