JavaScript Syntax, Statements, and Comments
Syntax rules, statements, semicolons, whitespace, comments, strict mode
JavaScript Syntax, Statements, and Comments
Every programming language has rules about how code must be written. These rules are called syntax. Understanding JavaScript syntax from the beginning prevents confusing errors and builds good habits that stay with you throughout your career.
Statements and Expressions
A JavaScript program is a sequence of statements. A statement is a complete instruction that the JavaScript engine can execute. For example, declaring a variable is a statement. Calling a function is a statement. An expression is a piece of code that produces a value, such as 2 + 3 or 'hello'.toUpperCase().
Semicolons
JavaScript has a feature called Automatic Semicolon Insertion (ASI) that adds semicolons in certain places automatically. However, relying on ASI can lead to subtle bugs. It is best practice to end every statement with a semicolon explicitly.
const name = 'Alice';
const age = 25;
console.log(name, age);Case Sensitivity and Whitespace
JavaScript is case-sensitive. The variables name, Name, and NAME are three different identifiers. Always be consistent. Whitespace — spaces, tabs, and line breaks — is mostly ignored by the engine but is essential for human readability. Use consistent indentation of two or four spaces.
Writing Comments
Comments are notes in your code that the JavaScript engine ignores. They explain why code exists, not just what it does. Use single-line comments with // and multi-line comments with /* */.
// This calculates the total price including tax
const price = 100;
const taxRate = 0.08;
const total = price + price * taxRate; // 108
/*
The following function formats a currency value.
It accepts a number and returns a formatted string.
*/
function formatCurrency(amount) {
return `$${amount.toFixed(2)}`;
}Strict Mode
Adding 'use strict'; at the top of a file or function activates strict mode, which prevents several common programming mistakes. For example, strict mode prevents you from using undeclared variables. It is a good habit to enable it.
'use strict';
const username = 'Bob'; // Fine
// undeclaredVar = 10; // Would throw a ReferenceError in strict modeModern JavaScript modules automatically run in strict mode, so as you progress to ES6 modules later in this course, strict mode will be applied by default.
