JavaScript is the world's most popular programming language — and the only programming language that runs natively inside the web browser. It is the engine behind every interactive, dynamic, and modern website you visit every day.
JavaScript (often shortened to JS) is a lightweight, cross-platform scripting language that brings web pages to life. When you click a button, see a dropdown menu open, watch a live countdown timer, or submit a form without reloading the page — that is JavaScript at work.
Every modern web page is built with three core technologies, each playing a distinct role:
Think of it like a building: HTML is the walls and floors, CSS is the paint and furniture, and JavaScript is the electricity that makes everything functional and interactive.
JavaScript gives you enormous control over a web page. Here are some of the most common things it can do:
Here is a basic example that shows how JavaScript can change the content of an HTML element when a user clicks a button:
<!DOCTYPE html>
<html lang="en">
<body>
<h2>My First JavaScript</h2>
<p id="message">This text will change when you click the button.</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
document.getElementById("message").innerHTML = "Hello! JavaScript is working!";
}
</script>
</body>
</html>
<script> tag is where JavaScript code
lives inside an HTML file. You can also write JavaScript in a separate .js
file and link it — which is the recommended approach for larger projects.
myVariable and
myvariable are treated as two different things.;, though it is sometimes optional.onclick="doThis()" works, but scattering logic across dozens of attributes gets unmanageable fast. Move logic into a <script> block or a separate .js file as the page grows.
<script> before the HTML it targets. If a script tries to grab an element that hasn't been parsed yet, document.getElementById() returns null. Put scripts at the end of <body>, or use the defer attribute.
A second small example — this one tracks state (a running count) instead of just replacing text once:
<p id="count">Clicked 0 times</p>
<button onclick="increment()">Click Me</button>
<script>
let clicks = 0;
function increment() {
clicks++;
document.getElementById("count").innerHTML = "Clicked " + clicks + " times";
}
</script>
Rendered result:
Clicked 0 times
Q: Where should the <script> tag go — head or body?
A: Near the end of <body>, or in <head> with the defer attribute. Both ensure the HTML is fully parsed before your script tries to interact with it.
Q: Do I need a server to run JavaScript?
A: Not for learning — opening an .html file directly in a browser is enough for most examples. You'd only need a server (like Node.js) for things like file access or talking to a database.
Q: Is JavaScript the same as Java?
A: No — despite the name, they're unrelated languages with different syntax, runtimes, and use cases. See the MDN JavaScript guide for where JS actually comes from.