What Is JavaScript? A Practical Introduction for Web Beginners
What is JavaScript?
JavaScript is the programming language that makes web pages interactive. It runs in every modern browser, where it can read and change the page through the DOM, respond to clicks and key presses, and load data from servers without a full page reload. It also runs on servers through Node.js. HTML provides structure, CSS provides style and JavaScript provides behaviour.
Adding JavaScript to a page
Keep your code in a separate file and load it with a script tag. The defer attribute tells the browser to download the file in parallel and run it only after the HTML has been parsed, so your code can safely find elements on the page.
<script src="/js/app.js" defer></script>
<!-- or, for code that uses import/export -->
<script type="module" src="/js/main.js"></script>Module scripts are deferred automatically and let you split code into files that import from each other. Both approaches work in all current browsers.
Core language features you will use daily
Modern JavaScript, often described by its yearly ECMAScript editions, is much cleaner than older tutorials suggest. Use const by default, let when a value must change, and avoid var.
const user = { name: 'Asha', city: null };
const greet = (person) => `Hello, ${person.name}!`;
console.log(greet(user));
console.log(user.address?.pin ?? 'No PIN code');- Arrow functions give a short syntax for small functions.
- Template literals, written with backticks, insert values into strings without awkward concatenation.
- Optional chaining (
?.) stops withundefinedinstead of throwing an error when a property is missing. - Nullish coalescing (
??) supplies a default only when a value isnullorundefined, unlike||, which also replaces 0 and empty strings.
The DOM: reading and changing the page
The Document Object Model is the browser's live, tree-shaped representation of your HTML markup. JavaScript selects nodes from this tree with CSS-style selectors and then changes their text, attributes or classes.
const banner = document.querySelector('.banner');
banner.textContent = 'Sale ends tonight';
banner.classList.add('is-visible');You can also create elements from scratch with document.createElement, set their attributes and attach them with append, or remove them with remove(). Each change updates the page immediately, but many separate changes in a loop can be slow, so build new content first and insert it in one step where you can.
Toggling classes, rather than setting inline styles, keeps the appearance in your stylesheet where it belongs. Our CSS guide covers the styling side.
Events and fetching data
Events are signals that something happened: a click, a key press, a form submission. You attach a listener function that runs each time the event fires. The example below intercepts a search form, requests results from an API with fetch and displays them.
const form = document.querySelector('#search');
const list = document.querySelector('#results');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const q = new FormData(form).get('q');
try {
const res = await fetch(`/api/courses?q=${encodeURIComponent(q)}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const courses = await res.json();
list.replaceChildren(...courses.map((c) => {
const li = document.createElement('li');
li.textContent = c.title;
return li;
}));
} catch (err) {
list.textContent = 'Could not load results. Please try again.';
}
});preventDefault()stops the browser from reloading the page on submit.encodeURIComponentmakes the search text safe to place in a URL.fetchonly rejects on network failure, so you must checkres.okto catch 404 and 500 responses yourself.asyncandawaitlet asynchronous code read from top to bottom, andtry...catchhandles failures in one place.
The server side of this exchange, including status codes and JSON responses, is explained in our guide to APIs.
Displaying data safely
The example above sets textContent, never innerHTML, when inserting data that came from a server or a visitor. textContent treats the value as plain text. innerHTML parses it as markup, so a value containing a script tag or an event attribute could run code in your visitor's browser. This attack is called cross-site scripting (XSS).
The same principle applies on the server. Data stored in a database is only as trustworthy as whoever typed it, so escape it in PHP before it reaches the page and again in JavaScript when you insert it dynamically.
Debugging and next steps
Every browser ships with developer tools. The Console shows errors with the file and line number, the Sources panel lets you pause code at a breakpoint and inspect variables, and the Network panel shows every request your page makes, including the status code and response body of each fetch call.
- Build small features without libraries first: a dark mode toggle, a tabbed panel, a form that validates as you type.
- Load real data from a public JSON endpoint and render it as a list.
- Learn how modules and a bundler such as Vite organise larger projects.
- Explore a framework such as React or Vue only after plain DOM work feels comfortable.
If you want guided projects that connect front-end scripts to a PHP and MySQL back end, SkillNewton runs an online course that covers this full-stack web development path from fundamentals to advanced work.
Common mistakes
- Running scripts in the
<head>withoutdefer, soquerySelectorreturnsnullbecause the element does not exist yet. - Assuming
fetchthrows on an HTTP error and never checkingresponse.ok. - Inserting user-supplied text with
innerHTML, which opens the page to cross-site scripting. - Comparing values with
==, which converts types in surprising ways, instead of the strict===. - Forgetting
awaitbefore an asynchronous call and then working with a pending Promise instead of the data.
Frequently asked questions
Is JavaScript the same as Java?
No. They are separate languages with different designs and uses. The similar name came from marketing decisions in the 1990s. JavaScript runs in browsers and on Node.js; Java is commonly used for Android and enterprise back-end systems.
Should I learn TypeScript instead?
Learn JavaScript first. TypeScript is JavaScript with optional static types added, and it compiles to plain JavaScript. Once you are comfortable with the language, TypeScript helps catch errors in larger projects.
Does JavaScript affect SEO?
It can. Search engines can render JavaScript, but content that only appears after scripts run may be discovered later or missed. Important text and links should be present in the initial HTML wherever possible.