What JavaScript Is and Where It Runs
JavaScript is a programming language. A programming language is a way to give a computer step-by-step instructions. JavaScript is special because it runs inside every web browser, like Chrome, Firefox, or Safari. When a page shows a pop-up, updates without reloading, or checks your form, that is usually JavaScript at work.
JavaScript also runs outside browsers, for example on servers with a tool called Node.js. In this tutorial we focus on the browser.
Your First JavaScript: Running Code in the Browser
You can try JavaScript right now, with no setup:
- Open any web page in Chrome or Firefox.
- Press
F12(or right-click, then choose "Inspect"). - Click the Console tab.
- Type
2 + 2and press Enter.
The console is a place where you type code and see results. Let's print a message:
console.log('Hello, JavaScript!');console.log is an instruction that prints text to the console.
Values and Data Types
A value is a piece of data, like a number or a piece of text. Each value has a type. These are the core types:
| Type | Example | What it is |
|---|---|---|
| string | `'hello'` | Text, wrapped in quotes |
| number | `42`, `3.5` | Numbers, with or without a decimal point |
| boolean | `true` | Yes/no, only two values: true or false |
| undefined | `undefined` | A value that has not been set yet |
| null | `null` | A value set on purpose to mean "nothing" |
Strings use quotes: 'JavaScript' or "JavaScript".
Declaring Variables with let and const
A variable is a named box that stores a value. You create one with let (can change later) or const (cannot change):
const language = 'JavaScript';
let year = 1995;
year = year + 1;
console.log(`${language} was created in ${year - 1}`);const means constant: fixed. let means "let this change". The line with backticks builds text by dropping values into placeholders marked with ${}. This is called a template literal. Rule of thumb: use const by default, and let only when the value must change.
Operators and Expressions
An operator is a symbol that does work on values, like + or *. An expression is code that produces a value, like 2 + 3 (which gives 5).
Common operators:
+,-,*,/— do math%— remainder after dividing, like7 % 2gives1===— compares two values, gives true or false!==— checks that two values are not equal&&— and;||— or;!— not
console.log(5 + 3); // 8
console.log(10 % 3); // 1
console.log(5 === 5); // true
console.log(4 > 2 && 2 > 1); // trueAlways use === to compare. A looser operator == exists but can give surprising results.
Exercise
What does this print? const name = 'Ada'; console.log(Hello, ${name}!);
Show answer
It prints Hello, Ada! The template literal replaces ${name} with the value stored in the variable.
Spotted a mistake, or code that does not work?