JavaScript Basics: Your First Steps
JavaScript is the language of the web. It runs in every browser, so you can start right now with nothing to install. Learn the core ideas and run real code in the editor on this page, with exercises that check your answer.
Hello, console
A program is a list of instructions the computer runs from top to bottom. The first instruction most people learn is console.log(). It prints whatever you put inside the parentheses to the console, a text area for messages from your code.
console.log("Hello, world!");
console.log("I am learning JavaScript");
console.log(2 + 3); // prints 5- Text goes in quotes:
"like this"or'like this'. Numbers don't. - Lines usually end with a semicolon
;. JavaScript often works without them, but using them is a good habit. - Anything after
//is a comment: a note for humans that the computer ignores.
Where else can I run JavaScript? In Chrome, Edge or Firefox on a computer, press F12 (or Cmd+Option+J in Chrome on a Mac) and click the Console tab. Type code and press Enter. Or just use the code runner on this page.
Variables and types
A variable is a named box that holds a value. Create one with let if the value will change, or const if it won't.
const name = "Sam"; // text (a string)
let age = 30; // a number
let isMember = true; // a boolean: true or false
age = age + 1; // let can change
console.log(name, age); // Sam 31
console.log(`Hi ${name}, next year you'll be ${age + 1}`);| Type | Example | Use it for |
|---|---|---|
| String | "hello" | Text |
| Number | 42, 3.5 | Math, counts, prices |
| Boolean | true, false | Yes or no answers |
| Array | [1, 2, 3] | A list of values (lesson 4) |
| Object | { name: "Sam" } | Labeled values that belong together |
| undefined / null | undefined | “No value yet” / “empty on purpose” |
The backtick string `Hi ${name}` is a template literal. Anything inside ${ } gets filled in. You can check a value's type with typeof: typeof 42 gives "number".
Watch out: "5" + 3 gives "53", not 8. When you add text and a number, JavaScript glues them together as text. Turn text into a number first with Number("5").
Making decisions with if/else
An if statement runs code only when a condition is true. Add else if and else for other cases.
const temp = 72;
if (temp > 85) {
console.log("Hot! Drink water.");
} else if (temp >= 60) {
console.log("Nice day.");
} else {
console.log("Bring a jacket.");
}| Operator | Means | Example (true) |
|---|---|---|
=== | is equal to | 5 === 5 |
!== | is not equal to | 5 !== 4 |
> < | greater / less than | 9 > 2 |
>= <= | or equal | 5 >= 5 |
&& | and (both true) | age > 12 && age < 20 |
|| | or (either true) | day === "Sat" || day === "Sun" |
! | not | !false |
Use three equals signs. = puts a value in a variable. === compares two values. There's also ==, which converts types first (so "5" == 5 is true). Most style guides recommend === to avoid surprises.
Arrays and loops
An array is a list in square brackets. Each item has a position number called an index, and counting starts at 0.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // apple
console.log(fruits.length); // 3
fruits.push("date"); // add to the endA loop repeats code. The classic for loop counts; for...of walks through every item in an array.
// count from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// every item in a list
for (const fruit of fruits) {
console.log("I like " + fruit);
}The for loop has three parts: start (let i = 1), keep going while (i <= 5), and after each round (i++, which adds 1). There's also while (condition) { … }, which repeats as long as the condition stays true.
Infinite loops: if the condition never becomes false, the loop never stops and the page freezes. Make sure something inside the loop moves it toward the end.
Functions
A function is a reusable recipe. You give it inputs (called parameters), it does some work, and it can hand back a result with return.
function addTax(price, rate) {
return price * (1 + rate);
}
console.log(addTax(20, 0.08)); // 21.6
console.log(addTax(100, 0.05)); // 105
// the same thing as an "arrow function"
const double = (n) => n * 2;
console.log(double(7)); // 14- Defining a function doesn't run it. You call it with its name and parentheses:
addTax(20, 0.08). returnsends a value back and ends the function. Without it, the function returnsundefined.- Arrays have handy built-in functions:
[1,2,3].map(n => n * 2)gives[2,4,6], and[5,12,8].filter(n => n > 6)gives[12,8].
Changing the web page (the DOM)
In a browser, JavaScript can read and change the page. The browser turns your HTML into a tree of objects called the DOM (Document Object Model), and document is your way in.
<!-- HTML -->
<h1 id="title">Hello</h1>
<button id="btn">Click me</button>
// JavaScript
const title = document.querySelector("#title");
const btn = document.querySelector("#btn");
btn.addEventListener("click", () => {
title.textContent = "You clicked!";
title.style.color = "tomato";
});document.querySelector("#id")finds an element using a CSS selector:#for an id,.for a class..textContentreads or changes the text inside it..stylechanges its CSS.addEventListener("click", function)runs your function each time something happens, like a click or a key press.
To use JavaScript in your own page, put it in a file like script.js and add <script src="script.js"></script> just before </body>. New to HTML? Start with HTML basics.
Code runner and exercises
Pick an exercise, write your code, and press Run (or Ctrl+Enter). Your console.log output appears below and is checked automatically. The mini page has an #title, a #btn button and an empty #out paragraph you can change with DOM code.
Your code runs in a locked-down sandbox frame, so it can't touch the rest of this site. If it runs longer than 3 seconds, it's stopped.
FAQCommon questions
Is JavaScript the same as Java?
No. They're different languages with a confusingly similar name. JavaScript runs in web browsers (and on servers with tools like Node.js). Java is mostly used for apps, Android and big business systems.
Should I use let, const or var?
Use const by default and let when you need to change the value. var is the older way. It still works, but it has quirks, so most modern code avoids it.
What do I need to start writing JavaScript?
Just a web browser and a text editor. A free code editor like Visual Studio Code makes it easier with colors and auto-complete. Save an HTML file with a <script> tag, open it in your browser, and check the console for output and errors.
My code doesn't work. How do I find the problem?
Read the error message: it usually names the problem and the line. Common causes are a typo in a name (JavaScript is case-sensitive, so Name and name are different), a missing bracket or quote, or using a variable before creating it. Add console.log() lines to see what your values really are.
What should I learn after the basics?
Objects, more array methods (map, filter, find), handling form input and events, then fetching data from the web with fetch(). Building small projects, like a tip calculator or a to-do list, is the fastest way to learn.