JavaScript is one of the most widely-used programming languages for web development. Whether you're just getting started or brushing up on the basics, understanding how variables work and how to connect your code to HTML is essential. In this post, we’ll explore:
What are global and local variables?
How to link JavaScript in an HTML file.
A quick look at the DOM (Document Object Model).
Linking JavaScript to HTML
Before you can run JavaScript, you need to link it to your HTML file. There are two common ways to do this:
1. Inline JavaScript(not recommended for large projects)
<!DOCTYPE html>
<html>
<head>
<title>Inline JavaScript</title>
</head>
<body>
<script>
alert("Hello from JavaScript!");
</script>
</body>
</html>
2. External JavaScript File (best practice)
Create a file named script.js:
// script.js
console.log("Hello from external JavaScript!");
Link it in your HTML file:
<!DOCTYPE html>
<html>
<head>
<title>External JS</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>Welcome to my website</h1>
</body>
</html>
Tip:
Use the defer attribute to ensure your JavaScript runs after the HTML is fully loaded.
Global vs Local Variables
Global Variable
A global variable is declared outside of any function. It can be accessed and modified anywhere in the code.
let globalMessage = "I'm a global variable!";
function showMessage() {
console.log(globalMessage); // Accessible here
}
showMessage();
console.log(globalMessage); // Also accessible here
Local Variable
A local variable is declared inside a function. It can only be accessed within that function.
function showLocalMessage() {
let localMessage = "I'm a local variable!";
console.log(localMessage); // Accessible here
}
showLocalMessage();
console.log(localMessage); // ❌ Error: localMessage is not defined
Remember:
Avoid unnecessary global variables to keep your code clean and bug-free.
Introduction to the DOM (Document Object Model)
The DOM is a programming interface for HTML and XML documents. It represents the page so that programs (like JavaScript) can change the document structure, style, and content.
Example:
Changing the text of an HTML element using JavaScript.
HTML:
<p id="demo">Hello!</p>
<button onclick="changeText()">Click Me</button>
JavaScript:
function changeText() {
document.getElementById("demo").innerText = "You clicked the button!";
}
When the button is clicked, the
text will change — thanks to JavaScript and the DOM.
Top comments (0)