JavaScript for beginners comes down to six ideas: variables, data types, functions, arrays, loops and events. Learn these in a browser console and you can read and write most small scripts.
This page walks through each idea with a short example. Open your browser's developer console (F12, then the Console tab) and paste the snippets in as you read. Nothing needs installing.
What is JavaScript, and where does it run?
JavaScript is the programming language that web pages use to react to the user: opening a menu, validating a form, updating a number without reloading. It runs inside the browser, and the same language also runs on servers through runtimes such as Node.js. If you are unsure whether it is switched on in your browser, see how to enable JavaScript in your browser. It is unrelated to Java; the two share a name and little else.
Variables: let and const
A variable is a named container for a value. Modern JavaScript has three keywords to declare one. MDN describes let as declaring a block-scoped variable and const as declaring a block-scoped variable that cannot be re-assigned. var is the older form, and it is only local to the function (or global scope) that contains it, not to the block.
const siteName = "larely"; // cannot be re-assigned
let visits = 0; // can change
visits = visits + 1;
siteName = "other"; // TypeError: Assignment to constant variable.
A const must be given a value when you declare it; leaving it out is a SyntaxError. Also, const only prevents re-assignment. It does not stop you from changing what is inside an array or object that the constant points to. A good beginner habit is to write const everywhere and switch to let only when the compiler, or your own logic, tells you the value has to change.
Data types
MDN lists eight data types in the current ECMAScript standard: seven primitives and Object. The primitives are Boolean, null, undefined, Number, BigInt, String and Symbol. As a beginner you will use four of them constantly:
| Type | Example | Typical use |
|---|---|---|
| Number | 42, 3.14 | Arithmetic, counters, prices |
| String | "hello" | Text |
| Boolean | true, false | Conditions |
| undefined | a variable with no value yet | "Nothing has been assigned" |
Objects group related values under names, and they are what most real data looks like:
const user = { name: "Sam", age: 30 };
console.log(user.name); // "Sam"
When you compare values, prefer === over ==. The difference is covered in double vs triple equals in JavaScript.
Functions
A function is a block of code you give a name and can run as many times as you like. MDN shows three ways to define one. A function declaration is a statement, and because of hoisting you can call it before it appears in the file:
function square(number) {
return number * number;
}
console.log(square(5)); // 25
A function expression stores a function in a variable. Unlike a declaration, it is not hoisted, so calling it too early throws ReferenceError: Cannot access 'square' before initialization. An arrow function is a shorter expression form:
const double = (number) => number * 2;
console.log(double(4)); // 8
The return statement specifies the value the function hands back. With a concise arrow body (no braces), the expression's value is returned for you. With braces, you must write return yourself. If you forget, the call produces undefined, which is one of the most common beginner bugs.
Arrays
An array is an ordered list of values in square brackets. Items are numbered from zero, and length tells you how many there are:
const shopping = ["bread", "milk", "cheese"];
console.log(shopping[0]); // "bread"
console.log(shopping.length); // 3
Four array methods cover most early needs. push() adds items to the end and returns the new length. pop() removes the last item and returns it. map() calls a function on each item and returns a new array of the results. filter() returns a new array with only the items for which the function returns true.
const numbers = [5, 2, 7, 6];
const doubled = numbers.map((n) => n * 2); // [10, 4, 14, 12]
const big = numbers.filter((n) => n > 5); // [7, 6]
Both map() and filter() leave the original array unchanged, which makes them safe to chain.
Conditions and loops
An if statement runs code only when a condition is true. When you only need to pick between two values, the ternary operator is a compact alternative:
const age = 20;
if (age >= 18) {
console.log("adult");
} else {
console.log("minor");
}
A loop repeats code. The classic for loop has three parts: a starting point, a condition and a step. For walking through every item in an array, for...of is shorter:
for (const item of shopping) {
console.log(item);
}
The full syntax, including break, continue and the let versus var trap, is in the JavaScript for loop guide. If you ever leave out the condition, the loop never stops by itself, so make sure something in the body ends it.
Making a page respond: the DOM and events
The DOM is the browser's live model of the page. You find an element with document.querySelector(), which per MDN returns the first element matching a CSS selector, or null if there is no match. It does not throw when nothing matches, so a typo in the selector shows up later as an error about null. An invalid selector string, on the other hand, throws a SyntaxError.
The addEventListener() method sets up a function that will be called whenever the specified event is delivered to the target. The first argument is a case-sensitive event name, the second is the function:
<button id="counter">Clicked 0 times</button>
<script>
const button = document.querySelector("#counter");
let clicks = 0;
button.addEventListener("click", () => {
clicks = clicks + 1;
button.textContent = "Clicked " + clicks + " times";
});
</script>
Save that as an .html file and open it in a browser. Each click runs the function, increments the variable and rewrites the button text. This one example uses a variable, a function, an event and the DOM together, which is why it is a good first project to retype from memory.
What to learn after these basics
Two topics usually come next. The first is asynchronous code, because anything that talks to a server waits for a response. Start with promises, then move to async and await. The second is reading error messages carefully. Most beginner problems show up in the console as a named error, such as ReferenceError or TypeError, with a line number. Search the exact message text, and compare your code against the MDN reference for the feature involved.
A practical way to practise is to take a small page, such as a tip calculator or a to-do list, and build it using only the six ideas above. Resist reaching for a framework until you can do that without help.
Frequently asked questions
- How long does it take to learn JavaScript as a beginner?
- There is no reliable single number, because it depends on your time and prior experience. The concepts on this page (variables, types, functions, arrays, loops, events) are a realistic first milestone. Once you can write small programs that use all of them without copying, you are ready for larger topics such as asynchronous code.
- Do I need to install anything to start with JavaScript?
- No. Every modern browser has a developer console where you can type JavaScript and see the result immediately. In most browsers, press F12 or Ctrl+Shift+J (Cmd+Option+J on macOS) to open the tools, then choose the Console tab.
- Should I use var, let or const?
- Use const by default and let when a variable must be reassigned. MDN describes let and const as block-scoped, while var is only scoped to the enclosing function or the global scope. That difference is the reason var causes surprises, so beginners can skip it.
- Is JavaScript the same as Java?
- No. They are separate languages with different syntax, type systems and runtimes. The similar name is a historical accident, and knowing one does not mean you know the other.