JavaScript Statements and Syntax
A JavaScript program is a list of instructions called statements, written using a few simple rules called syntax.
Statements
Each statement tells the browser to do one thing. The browser runs them one by one, from top to bottom.
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let price = 250; // statement 1
let quantity = 3; // statement 2
let bill = price * quantity; // statement 3
document.getElementById("demo").innerHTML = "Bill: Rs " + bill; // statement 4
</script>
</body>
</html>Try it Yourself »Bill: Rs 750
Semicolons
A semicolon ; ends a statement. JavaScript can often guess where a statement ends without it, but adding semicolons is a good habit and avoids strange bugs.
Example
let a = 5; let b = 10; let c = a + b;Several statements can be on one line if they are separated by semicolons, but one statement per line is easier to read.
White Space and Line Length
JavaScript ignores extra spaces. These two lines do the same thing:
Example
let city="Karachi"; // hard to read
let town = "Karachi"; // easier to readAdd spaces around operators like = and + to make code readable. Keep lines short (under about 80 characters).
Code Blocks
Statements can be grouped inside curly brackets { }. A group like this is called a code block. You will see blocks in functions, conditions and loops.
Example
function welcome() {
let name = "Ali";
console.log("Welcome, " + name);
}Values: Literals and Variables
JavaScript works with two kinds of values:
- Literals are fixed values written directly, like
100,3.5or"Hello" - Variables are named boxes that store values, like
priceorname
Text (a string) is written inside double or single quotes: "Karachi" or 'Karachi'.
Keywords
Some words have a special meaning in JavaScript and cannot be used as names.
| Keyword | Meaning |
|---|---|
let, const | Create a variable |
if, else | Run code only when a condition is true |
for, while | Repeat code |
function | Create a function |
return | Send a value back from a function |
Comments
Comments are notes for humans. JavaScript ignores them.
Example
// This is a one line comment
let fee = 5000; // a comment at the end of a line
/*
This is a comment
on several lines
*/Comments are also handy for switching off a line while testing.
Identifiers (Names)
Names you give to variables and functions are called identifiers.
- They can contain letters, digits,
_and$ - They cannot start with a digit
- They are case sensitive:
totalandTotalare different
Most JavaScript developers use camelCase: the first word is lowercase and each next word starts with a capital letter, like studentName or totalFee.
A missing bracket or quote is the most common beginner error. If nothing happens when you run your code, open the console (F12) and read the red error message.
Exercise
Exercise
Which of these is a valid variable name in JavaScript?
