S/Shortutorial
Home / Programming / JavaScript basics
Programming · JavaScript

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.

Beginner~20 min6 lessonsLive code runner + exercises
01

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

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.

02

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}`);
TypeExampleUse it for
String"hello"Text
Number42, 3.5Math, counts, prices
Booleantrue, falseYes or no answers
Array[1, 2, 3]A list of values (lesson 4)
Object{ name: "Sam" }Labeled values that belong together
undefined / nullundefined“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").

03

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.");
}
OperatorMeansExample (true)
===is equal to5 === 5
!==is not equal to5 !== 4
> <greater / less than9 > 2
>= <=or equal5 >= 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.

04

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 end

A 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.

05

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
06

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";
});

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.

Try it · JavaScript code runner
Console
Mini page

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.

MORESources

NEXTKeep learning