Edit Template
  • Home
  • /
  • JS Window Object
Edit Template
  • Home
  • /
  • JS Window Object

JavaScript Window Object

In JavaScript, the window object is the global object for the browser. It represents the browser window or tab where the script is running. All global variables and functions are actually members of the window object.

What is the Window Object?

The window object is automatically available in your scripts and provides access to:

  • The current webpage (document)

  • The URL (location)

  • Dialog boxes (alert, prompt, confirm)

  • Timers (setTimeout, setInterval)

  • Browser actions (open, scrollTo, etc.)

1. Accessing Web Page Content with window.document

Although you usually write document.getElementById(...), it’s the same as:

				
					window.document.getElementById("demo").innerText = "Updated by Learn With Arshyan!";


				
			

Since document is a property of window, both versions are valid.

2. Managing URLs with window.location

Redirect to another page:
				
					window.location.href = "https://learnwitharshyan.com";


				
			
Get the current URL:
				
					console.log(window.location.href);

				
			

3. Showing Dialog Boxes

You can communicate with the user using built-in window methods:

				
					// Show an alert box
window.alert("Welcome to Learn With Arshyan!");

// Ask for confirmation
let leave = window.confirm("Do you really want to leave this page?");
console.log("User wants to leave?", leave);

// Prompt user for input
let name = window.prompt("Enter your name:");
console.log("Hello, " + name);

				
			

4. Timers with setTimeout and setInterval

Run code after a delay:
				
					window.setTimeout(() => {
  alert("This appeared after 2 seconds!");
}, 2000);

				
			
Repeat every second:
				
					let count = 0;
let timer = window.setInterval(() => {
  console.log("Count:", ++count);
  if (count === 5) clearInterval(timer);
}, 1000);

				
			

5. Scroll the Page

You can scroll the page programmatically using scrollTo():

				
					window.scrollTo(0, 500);  // Scroll down 500 pixels

				
			

6. Open and Close Windows

You can create new windows or tabs (note: browser popup blockers may block this):

				
					let newTab = window.open("https://learnwitharshyan.com", "_blank");
newTab.close(); // closes the newly opened tab

				
			

Conclusion

FeatureSyntax Example
Redirect URLwindow.location.href = "..."
Alertwindow.alert("Hello!")
Confirmwindow.confirm("Are you sure?")
Promptwindow.prompt("Enter name:")
Delay Executionwindow.setTimeout(fn, ms)
Repeat Executionwindow.setInterval(fn, ms)
Scroll Pagewindow.scrollTo(x, y)
Open New Windowwindow.open(url)
Scroll to Top