Writing Your First Statements
When you're just starting with JavaScript, one of the first things you'll do is write a few simple statements. These statements tell the browser what to do—like show a message or do a calculation. In this lesson, we'll break down the basics of how JavaScript code is written and how it’s read by the browser.
Code structure
JavaScript code is read from top to bottom, line by line. Each line usually performs one small action. For example:
console.log('Hello, world!');
This simple line is a *statement*. It tells the browser to print a message to the console. When you write a script, you’ll often start by writing a series of these statements to perform different tasks. You can place these statements inside a <script>
tag if you're writing inside an HTML file, or in a .js
file if you're working with JavaScript separately.
<script>
console.log('Welcome to JavaScript!');
</script>
The key idea is: code is made up of small instructions, and you usually write one per line.
Semicolons, line breaks, indentation
JavaScript statements often end with a semicolon (;
). This tells the browser, "this instruction is done." While JavaScript doesn’t *require* semicolons for every line, it’s considered good practice to use them to avoid unexpected issues.
let name = 'Jane';
let age = 30;
console.log(name, age);
You can also put multiple statements on the same line if you separate them with semicolons:
let x = 10; let y = 20; console.log(x + y);
However, for better readability, it's best to keep one statement per line and use indentation to show structure—especially inside blocks like if
statements or functions:
function greet() {
console.log('Hi there!');
}
Indentation (adding spaces or tabs at the beginning of a line) helps you and others quickly understand which lines of code belong together.
Statement vs. expression
A statement is a complete instruction that performs an action. It can stand on its own and usually ends with a semicolon. Examples include let
, if
, for
, and console.log()
.
An expression is a piece of code that produces a value. For example:
5 + 10
This expression returns the value 15
, but by itself, it doesn’t do anything unless it's part of a statement:
let sum = 5 + 10;
Here, the expression 5 + 10
is used inside a statement that stores the result in a variable.
Think of it like this: expressions make values, and statements do things. You’ll use both all the time in JavaScript.