JavaScript Syntax
JavaScript syntax is the set of rules that defines how programs are written. A program is a list of statements that the engine executes one after another, top to bottom.
Statements and Semicolons
Each instruction is a statement. Statements usually end with a semicolon. JavaScript can insert missing semicolons automatically (ASI), but writing them yourself avoids rare surprises, and most style guides either always use them or use a formatter.
let a = 5;
let b = 7;
let sum = a + b;
console.log(sum);12
Values, Expressions and Identifiers
Literal values are fixed values written directly, like 42 or "text". An expression combines values, variables and operators into a new value. Identifiers are the names you give to variables and functions: they may contain letters, digits, _ and $, but cannot start with a digit.
JavaScript is case sensitive: total and Total are two different names. The common naming style is camelCase, such as firstName or totalPrice.
const price = 20;
const qty = 3;
console.log(price * qty); // expression
console.log("Total: " + price * qty);
const total = 1;
const Total = 2;
console.log(total, Total);60 Total: 60 1 2
JavaScript Comments
Comments are ignored by the engine. Use // for a single line and /* ... */ for several lines. Good comments explain why code does something, not what it obviously does.
// This is a single-line comment
/*
This comment
spans several lines
*/
console.log("Comments are skipped"); // trailing commentComments are skipped
Code Blocks and Whitespace
Curly braces { } group statements into a block, used by functions, if statements and loops. Extra spaces and line breaks are ignored, so use indentation (usually 2 spaces) to keep code readable.
const hour = 9;
if (hour < 12) {
console.log("Good morning");
console.log("Have a nice day");
}Good morning Have a nice day
Frequently asked questions
Are semicolons required in JavaScript?
Not strictly, because of automatic semicolon insertion. However, there are edge cases where a missing semicolon changes meaning, so many developers use them or let a formatter like Prettier decide.
Is JavaScript case sensitive?
Yes. Variable names, function names and keywords are all case sensitive, so myVar and myvar are different.
How do I comment out multiple lines in JavaScript?
Wrap them in /* and */. Most editors also toggle line comments on a selection with Ctrl+/ or Cmd+/.