JavaScript is the language/format for adding interactivity to a web
-
JavaScript Basics – MDN
There are literally millions of sites about JS, but let’s start with MDN. -
JavaScript – MDN
More MDN. -
Highest-scored ‘javascript’ Questions – Stack Overflow
It’s like Reddit for code! (Always check the year on answers. Some are old !) -
The Modern Javascript Tutorial
This reference goes very advanced/in-depth. -
Eloquent JavaScript
Also goes deep.
Going back to a very early analogy, JavaScript is the muscles of the web. Like HTML (the bones) and CSS (the skin), it is ultimately still just text that is parsed by our browsers. Like CSS, it can live within HTML documents, but is usually saved separately with the extension .js
.
JavaScript was first created by Brendan Eich over just 10 days in 1995, and has been through a myriad of evolutions, paths, missteps, and enhancements since then. It has nothing formally to do with Java, confusingly—other than being contemporaries and sort-of competitor, thus the name. (Coffee-culture was really big in the 90s!) JavaScript won the race, by every measure, and is ubiquitous on the modern web.
The idea was to make something that Web designers, people who may or may not have much programming training, could use to add a little bit of animation or a little bit of smarts to their Web forms and their Web pages.
Like HTML / CSS, JavaScript was a malleable, interpreted (not compiled) language running in the browser—meaning the source code could be seen by anyone, and anyone could borrow or modify it for their needs. You could always “pop the hood” to see how it worked. And then as our computers—and thus our browsers—became faster and cheaper, JS was used for more and more things.
Remember that now the tendrils of JavaScript are almost everywhere—running headless on servers, rendering whole sites, talking to hardware, processing NASA images, and so on. It’s web technologies, all the way down.
Libraries / Frameworks vs. Plain / Vanilla JS #
You’ll often hear folks talk about libraries or frameworks in the context of JavaScript—one of the ways it is so malleable. These are collections of Javascript code with their own specific purpose, ideas, paradigms, and syntax that expand upon what the language can do (or can do quickly or easily) on its own, out of the box.
Things like jQuery (very old-school, now), Node, React, Vue, Angular, D3, and p5 (to name some popular ones) are all written in and are interfaced with (so controlled by) JavaScript as well. They are often created to do something JavaScript doesn’t yet support on its own (in/famously, jQuery) or with a niche use/focus (like data-visualization, with D3). There are many, many frameworks and libraries.
When you write JS without libraries, it is usually called plain or vanilla JavaScript.
The language has evolved so much that we can do a lot, here, and this is where we’ll start. And while JS does many things, we’ll first just use it in the most simple way—to make our web pages more interactive.
Where Does JS Live? #
Very much like CSS, JavaScript code can live in several places:
- Inline as attributes
- Inside
<script>
elements within HTML documents - As separate/external
.js
files (the right way), viasrc
attributes
1. Inline Event Handlers #
JS was first added directly in attributes in HTML tags, just like CSS—but attached and “listening” for specific events:
<button onclick="alert('The button was clicked!');">Click here!</button>
Note the single quotes when nested/inside doubles!
This works for very, very simple things, but—for many of the same reasons as inline CSS—is brittle and doesn’t scale with complexity, or across multiple pages. Try writing a whole, elaborate function in there! No good.
2. Wrapped in <script>
Tags #
And again like CSS, JavaScript can be enclosed in its own special tag, the <script>
element. (These are also, somewhat confusingly, called inline scripts.) Anything inside the tag should be written in JavaScript syntax and will be executed right away—in the order/position of the tag within the HTML document.
-
<script>
The Script element – MDN
More minutia on using these in-HTML elements. -
Storing the information you need — Variables – MDN
Variables are always going to make your life easier.
Since this script isn’t directly on an element anymore (as above), we then have to identify the target element with a querySelector
, and then attach the click
event to it via addEventListener
:
// comment syntax
for JS! And we had to add cursor: pointer;
for the button in our CSS, to indicate it is actionable. Mind your affordances!
We also store (declare) the element here as a variable, to keep our code readable and reusable. These are a bit like their CSS counterparts. Ergonomics!
Oh Also, <noscript>
#
Some folks block/disable JavaScript—for performance or accessibility reasons, or to hide advertising/annoyances, and so on. This is less and less common these days, since so many sites completely rely on JS. It isn’t always feasible to replicate your site behavior entirely without JS, but you can use a special <noscript>
tag to show content only when scripting is turned off:
<noscript class="warning">
Our site uses JavaScript for some of its functionality, which is disabled in your browser.
</noscript>
You can test these by disabling JavaScript in your DevTools.
3. Separate / External .js
Files #
By far the most common, flexible way to include JavaScript is externally—again, like CSS. The difference here is that instead of a <link>
element, we still use a (now empty) <script>
tag, with the addition of a src="filename.js"
attribute:
-
Document:
querySelector()
method – MDN
This is how you target HTML elements in JS. -
EventTarget:
addEventListener()
method – MDN
And then listen for events happening on them.
<script defer src="script.js"></script>
I’ve never liked this empty-tag syntax, what can you do.
This will still run when the document gets to the <script>
(and in its place/defer
attribute allows it to “see” the HTML (not yet loaded) below it.
We can then move the script up into our <head>
, along with our other external files:
It’s the same JavaScript and behavior as the inline example above—but now moved over into a nice, separate, JS-syntax-highlighted file that can be re-used across pages. This is the way.
Adding / Removing a Class #
Okay, time for a more practical example: probably the most common thing you will use JS for—especially as we’re starting out—is simply to add or remove (toggle) a class from something when the user interacts with your page (such as clicking on a menu).
-
Element:
classList
property – MDN
Controls the CSS classes on an element.
Like with our transition examples, the element needs two states in your CSS: without the class and then with the class. The JavaScript interaction/event will just switch between them, and our CSS transition
will smooth out the… transition.
We’ll again use querySelector
and addEventListener
to listen for clicks, but then modify the classList
of a different element:
The class can be toggled on any element in your HTML (or sometimes, even just on document.body
itself)! querySelector
takes any CSS selector, even other classes. Also you an specifically use classList.add
and classList.remove
, if you don’t want the on-and-off behavior from classList.toggle
!
You can do many, many things with this basic “add a class” JS! It’s the basis for much of the interactivity you see online.
Opening a Modal #
You might also want to use JavaScript to “open” a modal dialog
element—which you might use for a menu, an overlay, or a lightbox. (In the software sense, a modal means your visitor must interact with the dialog
before they can do anything else.)
-
<dialog>
: The Dialog element – MDN
You used to have to write a lot more JS for these! -
::backdrop
– MDN
Style the overlays with these.
You could (and used to) do this by adding/removing classes, but this new(ish) approach gives us some nice “free” behaviors—making the rest of the page inert
, adding a ::backdrop
pseudo-element, stopping background scrolling, and even listening to Esc for dismissing/closing the element. It’s a lot of useful behavior without much code:
style.css
changes to make the dialog
appear as we want!
Watching for Scrolling #
Another very common use for JavaScript is to do something when an element enters or exits the viewport (scrolling into or out of view)—like fading or moving something in. (Remember, using/responding to the viewport is always very web-y! )
-
Intersection Observer API – MDN
Watch for things entering/exiting the viewport. -
if
…else
– MDN
Conditional logic blocks, “if this then that.”
Again we’ll need two states in our CSS—defined with/without a class. But now we’ll make use of the user’s scrolling, instead of a click, to toggle the between them.
This used to be unnecessarily hard in JavaScript, and was one of the things jQuery was created to help with. Nowadays we can easily use IntersectionObserver
to watch the element:
if
/ else
statement, an example of conditional logic!
Loops #
You will often want to use this on multiple elements—and remember, when in code, don’t repeat yourself!
-
Element:
querySelectorAll()
method – MDN
Gets multiple elements. -
forEach()
– MDN
And “loop” through them.
So we can use querySelectorAll
to select multiple forEach
loop to run the same class for each of them:
rootMargin
from the viewport/default, so the elements don’t transition immediately.
Some Miscellaneous JS Tips #
Alright, that is a lot. Like we’ve been
-
Using
alert(yourVariable)
for telemetry/debugging can quickly be pretty annoying—instead, you can useconsole.log(yourVariable)
to show messages in the DevTools console.A quick
console.log('Hello world!')
can check if things are plugged in right. The console will also show any JavaScript errors!In other languages, these functions are often, ironically, called print.
-
Search on Stack Overflow ! Someone has likely had your problem, before. Many people don’t really know JS (myself included)… so much as they really know how to find things on SO (and elsewhere).
-
This brings us back to LLM s, large language models (“artificial intelligence”)—tools like Chat GPT, GitHub Copilot, or the DeepSeek everyone is in a panic over. These can be useful; we use them ourselves. But much like Stack Overflow, you have to know what to look for, and need a level of understanding to do this to and to discern the value from the noise/code salad.
-
Ignore any examples that have lots of dollar signs, like
$("something").else
—it means this is jQuery, and so is pretty outdated! (Eric really, really doesn’t like jQuery.) -
To quickly get recent/modern, vanilla JavaScript results, instead include “ES 6 ” in your search—this refers to a more recent, easier-to-use syntax.
-
Relatedly, if you see “arrow functions” (with
=>
) it is a pretty good sign the answer is relatively recent. -
Like HTML/CSS, JS does not care about whitespace or tabbing. But it is case-sensitive! (The most common JS convention is camelCase.)
-
You’ll also see a lot of semicolons
;
but secretly you (almost never) actually need them! Declutter your code.
Any application that can be written in JavaScript, will eventually be written in JavaScript.