JavaScript for absolute beginners: variables, functions, and the DOM
JavaScript is the programming language of the web. Every browser has a built-in JavaScript engine, every web page can run JavaScript, and that means the page can react to what the user does, fetch new data, animate itself, and update its own content. In this beginner lesson we will start from zero, write our first script, and by the end of it you will know how to make a button change a paragraph on a page when it is clicked.
Where JavaScript lives
JavaScript is most often written in a separate file with the extension .js and loaded by the HTML page. Just like CSS, you link it from the <head> or the bottom of the <body>.
<code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;My first script&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1 id="greeting"&gt;Hello&lt;/h1&gt;
&lt;button id="btn"&gt;Click me&lt;/button&gt;
&lt;script src="app.js"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code>
The <script> tag at the bottom of the body is a deliberate choice. It loads after the HTML elements, so your script can find them on the very first run. If you put the script in the <head> instead, the elements would not exist yet, and the script would fail to find them.
Your first script: variables, strings, and alerts
Create a file called app.js and put this inside.
<code>// This is a comment. It is ignored by the browser.
// The next line stores a piece of text in a variable.
let name = "Hadi";
// Show it in a popup
alert("Hello, " + name + "!");
// Or write it into the page
document.body.innerHTML = "&lt;p&gt;Welcome, " + name + "&lt;/p&gt;";
</code>
Open the HTML page. You should see a popup that says "Hello, Hadi!" and the body of the page should be replaced with a paragraph that says "Welcome, Hadi!".
The keyword let declares a variable. Think of a variable as a labelled box. The label is the name (name), and the box holds a value ("Hadi"). You can read the value later or change it.
The plus sign + joins strings together. This is called concatenation. Note the spaces inside the quotes around the comma: ", " and "! ". Without those spaces the message would be "Hello,Hadi!" with no space.
Numbers, booleans, and basic math
JavaScript is not just for text. Numbers work the way you would expect.
<code>let age = 30; // a whole number
let price = 9.99; // a decimal
let name = "Hadi"; // a string (in quotes)
let isActive = true; // a boolean (true or false)
let nothing = null; // intentional "no value"
let unknown; // undefined (no value yet)
let sum = 2 + 2; // 4
let diff = 10 - 3; // 7
let product = 6 * 7; // 42
let quotient = 20 / 4; // 5
let remainder = 17 % 5; // 2 (17 divided by 5 leaves remainder 2)
let power = 2 ** 10; // 1024
</code>
The four primitive types you will use most are string (text), number, boolean (true or false), and null or undefined (no value). You can check the type of any value with typeof: typeof 42 is "number".
Conditions: if, else if, else
Programs need to make decisions. The if statement runs a block of code only when a condition is true.
<code>let hour = 14;
if (hour &lt; 12) {
console.log("Good morning");
} else if (hour &lt; 18) {
console.log("Good afternoon");
} else {
console.log("Good evening");
}
</code>
You can combine conditions with && (and) and || (or), and negate with !. A double-equals == checks value equality, and a triple-equals === checks both value and type. Use === by default. It is faster and catches more bugs.
<code>if (age &gt;= 18 &amp;&amp; hasTicket) { /* allow entry */ }
if (role === "admin" || role === "owner") { /* show admin tools */ }
if (!isLoading) { /* render the page */ }</code>Loops: doing something many times
The for loop runs a block of code a specific number of times. It has three parts: a starting value, a condition, and an update.
<code>for (let i = 0; i &lt; 5; i++) {
console.log("Step " + i);
}
// Prints: Step 0, Step 1, Step 2, Step 3, Step 4</code>Arrays, which we will see in a moment, almost always come with a loop. The modern way to loop over an array is with for...of.
<code>let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}</code>
Arrays and objects: collections of things
An array is a list. An object is a map from keys to values. You will use both constantly.
<code>// Array
let colors = ["red", "green", "blue"];
colors[0]; // "red"
colors.length; // 3
colors.push("yellow"); // add to the end
colors.includes("green"); // true
// Object
let user = {
name: "Hadi",
age: 30,
isAdmin: true,
hobbies: ["coding", "reading"]
};
user.name; // "Hadi"
user["age"]; // 30
user.email = "..."; // add a new key
</code>
Objects and arrays can be nested. A real article object on this site looks like { title: "...", content: "...", category: { name: "..." } }. Get comfortable reaching into nested structures with dot or bracket notation.
Functions: reusable blocks of code
A function is a named, reusable block of code. You define it once and call it whenever you need it.
<code>// Define
function greet(name) {
return "Hello, " + name + "!";
}
// Call
greet("Hadi"); // "Hello, Hadi!"
// Modern arrow function syntax
const add = (a, b) =&gt; a + b;
add(2, 3); // 5
</code>
The return keyword sends a value back to whoever called the function. Functions without an explicit return statement return undefined.
The DOM: making the page react
The Document Object Model is the browser's in-memory representation of your page as a tree of objects. Every <div>, every <p>, every <img> is an object you can read and modify with JavaScript.
<code>// Find an element by its id
const btn = document.getElementById("btn");
const greeting = document.getElementById("greeting");
// Listen for a click on the button
btn.addEventListener("click", function () {
greeting.textContent = "You clicked the button!";
});
</code>
That is a real, working interactive page. Put the script in app.js, save, refresh. Click the button. The text on the page changes. You just made a webpage react to a user.
Common beginner mistakes
Forgetting let or const. If you write name = "Hadi" without a declaration, you are creating an implicit global variable. Always use let or const in front.
Using == instead of ===. The double-equals does type coercion that almost always leads to subtle bugs. Use ===.
Putting the script in the head without defer or DOMContentLoaded. If you do, the script runs before the HTML is ready, and getElementById returns null. Either put the script at the bottom of <body>, or add the defer attribute to the <script> tag, or wrap your code in document.addEventListener("DOMContentLoaded", function() { ... }).
What is next
You can now make a page react to clicks, store and read data, write functions, and use the DOM. In the intermediate lesson we go deeper: asynchronous code with fetch and promises, modern ES modules, and how to structure a real interactive feature without creating spaghetti.
← More in JavaScript