Why JavaScript?
Meet JavaScript: learn how it adds behavior to web pages, where it runs, what makes it approachable, and why it is not the same language as Java.
- 01The three layers of a web pageSwitch HTML, CSS, and JavaScript on and off, and see what each one does.
- 02Where JavaScript runsSort real apps by where their JavaScript runs: a browser, a server, a phone, or a desktop computer.
- 03Your first programStep through five lines of code, and guess what they print.
Watch the video lectures
Full course on YouTube (opens in a new tab) ↗- Lecture 2Is JavaScript for me? Reasons to learn itWatch on YouTube (opens in a new tab) ↗
- Lecture 3What is programming?Watch on YouTube (opens in a new tab) ↗
What is JavaScript?
JavaScript is a programming language. A programming language is a way to write instructions for a computer. The computer follows the instructions one step at a time.
JavaScript is special because of where it runs. Every modern web browser can run it: Chrome, Safari, Firefox, and Edge. Each browser has a JavaScript engine. That is the part of the browser that reads JavaScript and runs it. So JavaScript is the language browsers use to make a page react when you click, type, or wait.
console.log("Hello, JavaScript!");This one line uses console.log. It prints a value in the console. The console is a panel in the browser where developers see messages from their code. Here it prints Hello, JavaScript!. This single line is already a whole program: one instruction, and one result you can see.
Programs get more useful when they work with a value. This example saves a person's name, then uses the name in a message:
const user = "Asha";
console.log("Welcome, " + user);Line 1 saves the text Asha under the name user. Line 2 joins Welcome, and that name, and prints Welcome, Asha.
A web page can do the same with something a person chose. Here, the person chose tea:
const item = "tea";
console.log("Added " + item);Line 1 saves the item name tea. Line 2 joins the word Added and the item name, and prints Added tea. A shopping page could show this message when someone puts tea in their cart.
When a website changes without loading a whole new page, JavaScript is usually doing the work. For example:
- A Like count that goes up as soon as you tap it.
- A menu that slides open, or photos you can swipe through.
- A form that warns “That email looks wrong” before you press Send.
- A map you can drag around, or a game that runs in a browser tab.
HTML puts things on the page. CSS decides how they look. JavaScript makes them do things. The next section shows all three.
A recipe is a list of steps in order: crack the eggs, mix them, heat the pan. The cook does each step exactly, from top to bottom. A program works the same way. It is a list of instructions for a computer. JavaScript is the language the recipe is written in. Every browser is a cook that can read it.
- In real life: The recipe card
- In JavaScript: Your program: a file of JavaScript
- In real life: One step, like “crack two eggs”
- In JavaScript: One instruction, like
let likes = 0; - In real life: A cook who follows the steps in order
- In JavaScript: The browser’s JavaScript engine
- In real life: The finished dish
- In JavaScript: What you see: a changed page, or a message in the console
The language of the web: HTML, CSS & JavaScript
INTERACTIVEMost web pages are built from three kinds of code. We call them the three layers of a page. Each layer has its own job:
- HTML (HyperText Markup Language) is the content: headings, paragraphs, pictures, and buttons.
- CSS (Cascading Style Sheets) is the looks: colors, sizes, spacing, and where things sit on the page.
- JavaScript is the behavior: what happens when you click, type, scroll, or wait.
A house starts with walls, rooms, and doors. Then paint and furniture make it nice to live in. Last, the wiring makes it work: you flip a switch, and a light comes on. A house with no wiring still stands. But nothing happens when you flip a switch.
- In real life: Walls, rooms, and doors
- In JavaScript: HTML: the content of the page
- In real life: Paint, curtains, and furniture
- In JavaScript: CSS: colors, spacing, and where things sit
- In real life: Wiring: flip a switch and a light comes on
- In JavaScript: JavaScript: click a button and something happens
Here is one small job for the JavaScript layer. A form can use JavaScript to check what someone typed before it is sent. This code does one tiny check:
const email = "asha@example.com";
console.log(email.includes("@"));Line 1 saves an example email address. Line 2 uses includes, which asks: is this piece of text inside that one? The text has an @ sign, so line 2 prints true.
This is only a quick hint for the person typing. It does not prove that the address is real. The website's server still checks important form data. A server is a computer that runs the website and stores its data.
Now try a tiny page with a Like button. Its HTML is always on. Switch CSS and JavaScript on and off. Click Like each time, and watch what changes.
<div class="card"> <p>Learning JavaScript today!</p> <button id="like">Like</button> <span id="count">0 likes</span></div>.card { padding: 16px; border: 1px solid silver; border-radius: 12px;}#like { padding: 6px 14px; border: none; border-radius: 999px; background: royalblue; color: white; font-weight: bold;}const button = document.querySelector("#like");const count = document.querySelector("#count");let likes = 0; button.addEventListener("click", () => { likes = likes + 1; count.textContent = likes + " likes";});Learning JavaScript today!
0 likesOnly HTML is on. The text and the button appear, with no styling. Click Like. Does anything happen? Then switch on CSS and JavaScript, one at a time.
What did you notice?
- HTML alone shows the text and the button. But clicking the button does nothing, because no code is waiting for the click.
- CSS changes only the looks. A nicer button still does nothing when you click it.
- JavaScript adds the behavior. It waits for clicks and updates the count. It works even when CSS is off.
Here is the JavaScript layer, line by line:
- Lines 1 and 2 find two things on the page: the Like button and the count text.
- Line 3 makes
likes, a name that holds a number. It starts at 0. - Line 5 tells the browser: "When someone clicks the button, run the code inside the curly braces."
- Line 6 adds one to
likes. - Line 7 writes the new number onto the page.
After one click, the page says "1 likes". That is a small mistake in the English. Fixing it needs an if, which you'll learn in the Control flow module.
You don't need to understand every symbol yet. Each one gets its own lesson. For now, remember these three steps. A lot of web page code follows them:
- Find something on the page.
- Wait for an event: something that happens, like a click.
- Change the page.
Your first program: five lines of JavaScript
STEP THROUGHThe Like button used a few small steps. Here is a program that counts likes with no web page at all. First, meet each piece:
let likes = 0;makes a variable. A variable is a name that holds a value. Here the name islikesand the value is 0.=means "put the value on the right into the name on the left." It is not the equals sign from math class.+adds two numbers. With text, it joins the pieces of text together.const messagemakes another variable.constmeans this variable will not get a new value later.console.log(...)prints a value in the console, the panel you met at the start of this lesson.
Guess what line 5 prints. Then click the blue line, or press Step, to run the program one small step at a time. After that, change how many likes lines 2 and 3 add, and guess again.
Guess what line 5 prints. Then click the blue line, or press Step, to run one small step at a time.
script
likes = likes + 1;likes = likes + 1;const message = "Liked " + likes + " times";console.log(message);In math, likes = likes + 1 can't be true: no number equals itself plus one. In JavaScript it is an instruction, and you read it from the right. First, work out likes + 1. Then put the answer in likes. Say it as "likes becomes likes plus one."
likes. Lines 2 and 3 each work out likes + 1, then put the answer back in the same box.The computer did exactly what each line said, in order, and nothing else. That makes a program easy to predict: if you follow the steps, you know the result.
Where JavaScript runs: front end, back end, phone & desktop
JavaScript started in the browser in 1995. Today it runs in other places too. Two words help here:
- The front end is the part of a website that runs on your device, in the browser. It is the page you see and click.
- The back end is the part that runs on a server: a computer far away that stores data and does work for the website.
The table shows four places where JavaScript runs. Read each row as: "Here, JavaScript does this job, for example in these apps."
| Where it runs | What JavaScript does there | Real examples |
|---|---|---|
| In the browser (front end) | It makes web pages react when you click or type. | Menus, forms, maps, and web apps like Gmail and Google Docs. |
| On a server (back end) | It runs with a program such as Node.js, Deno, or Bun, on computers in big buildings called data centers. | Saving data, checking logins, and sending emails. |
| In a phone app | It builds iPhone and Android apps, with tools such as React Native or Ionic. | One set of code that works on both kinds of phone. |
| In a desktop app | It builds programs for your computer, with a tool called Electron. | Visual Studio Code, Slack, and Discord. |
The JavaScript language is the same in each place. But each place gives it different extra tools. These extra tools are called the host API. The host is the place that runs your code. An API is a set of ready-made tools that your code can use. In a browser, one of these tools is document. It lets JavaScript reach the web page itself:
const button = document.querySelector("#order");
console.log(button.textContent);The page has one button that says Order tea. Line 1 uses document to find that button. Line 2 reads the button's text and prints Order tea. A Node.js server has its own useful tools. But it has no web page, so it has no document.
Now test yourself. Where does the JavaScript in each example run?
- A search box that suggests results as you type on a website
- Checking a password against the accounts stored in a database
- An iPhone and Android app written once with React Native
- Visual Studio Code, the code editor you install
- Warning that an email field is empty before a form is sent
- Sending you a password-reset email
- A phone app built with Ionic, which puts web code inside an app
- The Slack app you install on your laptop
Choose where each example’s JavaScript runs. Each answer comes with a short reason, so a wrong guess still teaches you something.
JavaScript can also control other apps. Google Apps Script adds new features to Google Sheets and Google Docs, and it is JavaScript.
What makes it a friendly first language
Many languages can build great software. Here is why JavaScript is a good first language:
- Nothing to install. Your browser already runs JavaScript. You can open the browser's console and start typing. Exercise 1 shows you how.
- Fast results. Change a line and see the new result in seconds, like in the experiments on this page.
- Flexible. You don't have to say what kind of value a variable holds, such as a number or text. JavaScript works it out while the program runs. This is called dynamic typing.
- Useful in many places. The same language builds web pages, servers, and apps. So what you learn here keeps helping you later.
- Lots of help. Millions of developers use JavaScript. There are free guides like MDN. There are also millions of free code packages: code that other people wrote and share for anyone to use. Someone has usually solved your problem before.
Being flexible has a downside. Sometimes JavaScript changes a value from one kind to another when you didn't ask it to. Guess each result below, then step through to check. Two results are easy. Two are surprising.
Guess each result before you step. Two are easy. Two show JavaScript changing a value when you didn't ask it to.
script
"Hello, " + "world";"5" + 3;"5" - 3;5 is a number, so + adds and you get 8. With quotes, "5" is text. Then + joins the two pieces, and you get the text "53".When a value should be a number, turn it into a number yourself. Don't hope that JavaScript guesses right. This matters for forms: a form field gives you text, even when the person typed a number.
const scoreText = "5";
const score = Number(scoreText);
console.log(score + 3);Line 1 saves text, because the value has quotes around it. Line 2 uses Number to turn that text into the number 5. Line 3 adds 3 and prints 8.
Number can't turn every piece of text into a number. For example, a price field might be empty, or have a word in it by mistake:
const priceText = "tea";
const price = Number(priceText);
console.log(Number.isNaN(price));Line 1 saves tea, which is not a price. Line 2 tries to turn it into a number and gets NaN. NaN is a special value. Its name is short for "not a number". Line 3 uses Number.isNaN to ask: is price the value NaN? It is, so line 3 prints true. So check the numbers that come from a form before you use them in a sum. Later, the Type conversion lesson shows more ways to handle text that is not a number.
"5" + 3 gives "53". The quotes make "5" text, and + joins text. The Type conversion lesson explains when JavaScript changes values, and how to change them yourself so nothing surprises you.
JavaScript is not Java
The names sound alike, but JavaScript and Java are two different languages. Different people made them, for different jobs. Here is how JavaScript got its name:
- In 1995, a company called Netscape made a popular web browser. Netscape wanted a simple language for that browser.
- Brendan Eich, who worked at Netscape, built the first version in about ten days.
- The language was first called Mocha, and then LiveScript.
- Then Netscape renamed it JavaScript, mostly to help sell it. Java was a new and popular language at the time. Netscape also had a deal with Sun Microsystems, the company that made Java.
The table compares the two languages. Read across each row to see how they differ.
| Question | Java | JavaScript |
|---|---|---|
| Who made it? | James Gosling’s team at Sun Microsystems, in 1995. | Brendan Eich at Netscape, in 1995. |
| Where is it used most? | On servers, in Android apps, and in large business systems. | In web browsers, and also on servers and in apps. |
| Do you write down the kind of value? | Yes, before you use it: int score = 10;. Here int means a whole number. | No. JavaScript works it out while the program runs: let score = 10;. |
| How does it run? | First it is turned into a special format called bytecode. Then a program called the Java Virtual Machine runs it. | A JavaScript engine runs the code you wrote, inside a browser or a program like Node.js. |
| How do you print a message? | System.out.println("Hi"); | console.log("Hi"); |
Can you tell them apart? Sort each line of code by language. Use the clues in the table.
System.out.println("Hello");console.log("Hello");int score = 10;let score = 10;public static void main(String[] args) {document.querySelector("#like");String name = "Ada";const greet = () => "Hi";
Pick the language each line is written in. Words that name a kind of value, like int and String, are a strong clue for Java.
A small real-world calculation
A shopping page can use JavaScript to update the total when you change how many items you want. Here, the item is a cup of tea:
const teaPrice = 3;
const quantity = 2;
const total = teaPrice * quantity;
console.log("Total: " + total);Line 1 sets the price of one cup to 3. Line 2 sets the number of cups, the quantity, to 2. Line 3 multiplies them with *, the multiply sign. Line 4 prints Total: 6.
Real orders often add one more cost. This version adds a delivery charge of 1:
const teaPrice = 3;
const quantity = 2;
const delivery = 1;
console.log(teaPrice * quantity + delivery);Lines 1 and 2 are the same as before, so the tea costs 6. Line 3 saves the delivery charge, 1. Line 4 works out teaPrice * quantity + delivery and prints 7. JavaScript multiplies first and adds second, like in math class. You may add round brackets, (teaPrice * quantity) + delivery, if that makes the sum easier to read. The answer is the same.
Now change the number of cups with the slider. The price stays at 3 per cup.
Price of one cup: 3
Number of cups: 2
Total: 6
At 3 per cup, 2 cups cost 6. Reset sets the cups back to 2.
The slider shows the answer right away. To watch the four lines of the first example make Total: 6 one step at a time, use this replay:
This replays the same four lines of the tea example, one step at a time.
script
const quantity = 2;const total = teaPrice * quantity;console.log("Total: " + total);The table shows the total for three different numbers of cups. The price is always 3.
| Price of one cup | How many cups | Total |
|---|---|---|
| 3 | 1 | 3 |
| 3 | 2 | 6 |
| 3 | 4 | 12 |
A browser check is not security
JavaScript in a web page runs on the visitor's own device: their phone or computer. That makes it good for quick hints. For example, it can tell someone that their password is too short before they send the form.
const passwordLength = 5;
const looksLongEnough = passwordLength >= 8;
console.log(looksLongEnough);Line 1 saves a sample length: 5 characters. Line 2 uses >=, which means "is greater than or equal to". It asks: is 5 at least 8? The answer is no. So line 3 prints false.
This check is only a helpful hint. Visitors can change the JavaScript in their own browser. So the website's server must check important rules again.
The browser can also turn that check into a friendly message:
const passwordLength = 5;
const message = passwordLength >= 8 ? "Looks long enough" : "Use a longer password";
console.log(message);Line 1 uses the same sample length. Line 2 picks one of two messages with ? :. Read it like this: "If the part before ? is true, use the first message. If not, use the second message." Here the part before ? is false, so line 3 prints Use a longer password.
This code can't sign anyone in, and it doesn't decide whether a password is safe. A long password is not always a safe one. The code only gives an early hint. The server checks the real rule and keeps the password safe.
Choose a sample length below, then step through the check. With 8 or more characters, it prints true. It is still only a hint in the browser, not a security decision.
This replays the sample length check, one step at a time. It is not a security check for a real password.
script
const looksLongEnough = passwordLength >= 8;console.log(looksLongEnough);Never put passwords, secret keys, or important checks about who may do what in JavaScript that goes to a browser. People can read and change code on their own device. The server must make the final decision.
Common misconceptions
“JavaScript only runs in web browsers.”
It started in browsers. Today Node.js, Deno, and Bun run it on servers and laptops. Tools like React Native and Electron use it to build phone apps and desktop apps. You sorted eight real examples above.
“JavaScript is a simpler version of Java.”
They are two different languages with similar names. The word "Java" in JavaScript was chosen in 1995 to help sell it. The two languages are not related.
“HTML is a programming language, so I already code.”
HTML is a markup language. That means it describes what is on a page. On its own, HTML can't make choices, repeat steps, or react to a click. JavaScript can. Knowing HTML still helps a lot, because JavaScript often changes the HTML on a page.
“JavaScript is a toy for small effects.”
It runs full apps like Gmail, Google Docs, and Visual Studio Code, and many, many servers. It has grown a lot since its first ten-day version.
“You need to learn another language first.”
No. JavaScript is one of the most popular first languages. Everything you need to start is already in your browser.
Practice: your first JavaScript
5 EXERCISESEach exercise takes a few minutes. Try it yourself first. If you get stuck, open a hint. Open the solution last.
- Open your browser's console. In Chrome or Edge, press
F12. You can also pressCtrl+Shift+Jon Windows or Linux, orCmd+Option+Jon a Mac. In Firefox, pressCtrl+Shift+K, orCmd+Option+Kon a Mac. - Click next to the
>sign, type2 + 2, and press Enter.
The console runs what you type and shows the result right away: 2 + 2 is 4. You just ran JavaScript! Next, try "Hello, " + "world".
Don't run this program yet. First, work out what it prints. Then check your answer below.
let likes = 3;
likes = likes + 2;
likes = likes + 2;
console.log("Liked " + likes + " times");Line 1 puts 3 in likes. Line 2 makes it 5, and line 3 makes it 7. Line 4 joins the pieces of text, so the console prints Liked 7 times. Paste the code into your console to check.
Look at the Like button from the experiment. For each change below, which layer would you edit?
- Make the Like button green.
- Add a second button that says Share.
- Make each click add 10 likes instead of 1.
/* 1. CSS: change the button's look */
#like { background: green; }
<!-- 2. HTML: add new content -->
<button id="share">Share</button>
// 3. JavaScript: change the behavior
likes = likes + 10;A color is about looks, so the first change is CSS. A new button is new content, so the second change is HTML. What a click does is behavior, so the third change is JavaScript: change likes + 1 to likes + 10.
- Open any website. A news site or an online shop works well.
- Open the developer tools (
F12). Choose the Network tab, and reload the page. The Network tab lists every file the page downloads. - Click the JS filter to show only JavaScript files.
How many JavaScript files did the page load? Is that more or fewer than you expected?
Most websites load several JavaScript files. Big web apps can load dozens or even hundreds. Each file adds behavior, such as a menu, a video player, a visitor counter, or a chat box. Each one runs on the same kind of JavaScript engine you used in Exercise 1.
In your console, write a program that:
- makes a variable named
scorethat holds 10, - adds 5 to it, and
- prints it with
console.log.
Tip: press Shift + Enter to start a new line in the console without running the code yet.
let score = 10;
score = score + 5;
console.log(score);let makes score and puts 10 in it. Line 2 works out score + 5, which is 15, and puts it back in score. console.log(score) prints 15. The console may then show undefined. That is not a mistake: it is the value that the console.log call gives back.
Quiz: check your understanding
7 QUESTIONSYour score counts only your first try at each question. Every choice has a short explanation, so read the ones for wrong answers too.
Question 1 of 7Which layer of a web page makes a button do something when you click it?
Choose an answer to see the explanation.
Question 2 of 7What does this program print?
Read the code, then predictlet likes = 10; likes = likes + 5; console.log(likes);Choose an answer to see the explanation.
Question 3 of 7Where can JavaScript run today?
Choose an answer to see the explanation.
Question 4 of 7Why is JavaScript called JavaScript?
Choose an answer to see the explanation.
Question 5 of 7What does this line print?
Read the code, then predictconsole.log("5" + 3);Choose an answer to see the explanation.
Question 6 of 7Which statement about HTML is true?
Choose an answer to see the explanation.
Question 7 of 7What do you need to install before running your first line of JavaScript?
Choose an answer to see the explanation.
Key takeaways
- JavaScript is a programming language that every web browser can run. That is why web pages use it to react to you.
- HTML is the content, CSS is the looks, and JavaScript is the behavior.
- JavaScript also runs on servers (with Node.js, Deno, or Bun), in phone apps, and in desktop apps.
- It's a friendly first language: there is nothing to install, and you see results fast. Being flexible brings a few surprises, like
"5" + 3giving"53". - JavaScript and Java are different languages, even though their names sound alike.
Remember this one line.
HTML is what's on the page. CSS is how it looks. JavaScript is what it does.
Coming next: A short history of JavaScript. It tells how a language built in ten days became the language of the web, and why a new version comes out every year.