JS Tutorial

Learn the fundamentals of JavaScript and how it works in the browser. This tutorial guides you step by step from basic syntax to practical examples.

On this page

What is JavaScript?

JavaScript is the programming language of the web. It lets you add behavior to pages, respond to user actions, and update content dynamically.

JavaScript runs in the browser and can also run on servers (but this tutorial focuses on browser JavaScript).

How JavaScript runs

The browser reads your HTML, then executes JavaScript as it encounters it. A script can be inline in the page or loaded from an external file.

Add JavaScript to a page

You can write JavaScript in a <script> tag or link an external .js file.

<!-- Inline JavaScript -->
<script>
console.log("Hello from JavaScript!");
</script>

<!-- External JavaScript -->
<script src="app.js"></script>

Your first output

For learning and debugging, console.log() is the simplest output method.

console.log("Hello, world!");

You can also write into the page (DOM) when needed:

document.getElementById("demo").textContent = "Hello from the DOM";

Statements and semicolons

JavaScript code is made of statements. Semicolons are optional in many cases, but using them consistently can prevent edge cases.

let x = 5;
let y = 10;
console.log(x + y);

Variables in one minute

Use const for values that should not be reassigned, and let for values that change.

const siteName = "W4";
let visits = 0;

visits = visits + 1;
console.log(siteName, visits);

A tiny function example

Functions help you reuse logic. You can call them with different inputs.

function greet(name) {
  return "Hello, " + name + "!";
}

console.log(greet("Ozan"));

JavaScript and the HTML DOM

The DOM (Document Object Model) is how JavaScript reads and changes the page. You can select elements and update their content or styles.

const btn = document.querySelector("#btn");
const box = document.querySelector("#box");

btn.addEventListener("click", function () {
  box.classList.toggle("active");
});

Next steps

Continue with JS Syntax to learn the core rules of writing JavaScript, then move on to variables, operators, conditions, and loops.

JS Tutorial Examples (8)