DEV Community

rajeshwari rajeshwari
rajeshwari rajeshwari

Posted on

JavaScript Basics: Variables, Global Scope & the DOM

Sure! Here's a beginner-friendly blog-style post that explains JavaScript variables, global variables, and DOM (Document Object Model) concepts in a simple way:


🌐 JavaScript Basics: Variables, Global Scope & the DOM

JavaScript is one of the most powerful tools for making web pages interactive. If you're starting out, you’ve probably already come across terms like variables, global scope, and the DOM. Let’s break these down in a simple and practical way!


πŸ“¦ 1. What is a Variable?

A variable in JavaScript is like a box that stores data. You can name the box and use it to hold numbers, text, or even more complex things like objects and arrays.

πŸ”Ή Declaring a variable:

let name = "Alex";
const age = 25;
var city = "New York";
Enter fullscreen mode Exit fullscreen mode

βœ… Keywords:

  • let – for variables that can change.
  • const – for variables that stay constant.
  • var – older way, avoid using in modern code unless needed.

🌍 2. What is a Global Variable?

A global variable is accessible from anywhere in your code.

let greeting = "Hello"; // global if declared outside a function

function sayHello() {
  console.log(greeting); // works!
}
Enter fullscreen mode Exit fullscreen mode

πŸ›‘ Be careful! Too many global variables can cause bugs. Functions or other scripts might accidentally change them.


🧱 3. The DOM (Document Object Model)

The DOM is how JavaScript sees your webpage. It’s like a tree that represents all elements (HTML tags) on the page.

Example HTML:

<h1 id="title">Welcome!</h1>
<button onclick="changeTitle()">Click Me</button>
Enter fullscreen mode Exit fullscreen mode

JavaScript to change the title:

function changeTitle() {
  document.getElementById("title").innerText = "Hello JavaScript!";
}
Enter fullscreen mode Exit fullscreen mode

βœ… document.getElementById() is a DOM method that lets you grab elements and interact with them.


✨ Final Tips

  • Use let and const for clean, modern code.
  • Keep global variables to a minimum.
  • Practice using the DOM to make your pages dynamic.

🧠 Want to try something fun?
Make a button that changes the background color of the page when clicked!

<button onclick="changeColor()">Change Color</button>

<script>
function changeColor() {
  document.body.style.backgroundColor = "lightblue";
}
</script>
Enter fullscreen mode Exit fullscreen mode

Keep coding and having fun with JavaScript! If you'd like this blog as a formatted HTML file or want to expand it with more topics like events or functions, just let me know!

Top comments (0)