JavaScript syntax refers to the set of rules, formatting conventions, and structural guidelines that dictate how a JavaScript program is constructed and how the ECMAScript engine interprets it. Designed to look familiar to developers coming from C-style languages (like C++, Java, and C#), JavaScript syntax balances readability with high flexibility, supporting both procedural and functional programming paradigms.
1. Case Sensitivity and Identifiers
JavaScript is strictly case-sensitive. This means that variable names, function names, and keywords must maintain consistent capitalization to avoid reference errors.
- Identifiers are the names you give to variables, functions, and objects.
Rules for Identifiers:
- Must begin with a letter, an underscore (
_), or a dollar sign ($). Subsequent characters can also include numbers (0-9). - Cannot use reserved keywords (e.g.,
class,function,return,let,const).
JavaScript
let accountBalance = 1000;
let AccountBalance = 2000; // Completely distinct variable
let _internalId = "A-99";
let $element = document.getElementById("app");
2. Statements, Expressions, and Semicolons
A JavaScript program is a sequence of statements executed by the browser or runtime environment.
- Expressions produce a value (e.g.,
5 * 10,x + y). - Statements perform an action (e.g.,
let x = 5;,if (x > 3) { ... }).
Automatic Semicolon Insertion (ASI)
JavaScript utilizes Automatic Semicolon Insertion (ASI) to automatically close statements if a newline is encountered and the parser cannot complete the current statement without a semicolon. However, relying entirely on ASI can lead to silent bugs, particularly when lines start with parentheses or square brackets.
JavaScript
// Risky ASI behavior
let a = b
(1 + 2).toString()
// The engine interprets this as b(1 + 2).toString(), throwing an error if b is not a function.
Best Practice: Explicitly terminate statements with semicolons (;) to ensure predictable parsing across all build tools and minifiers.
3. Comments and Documentation
Comments are ignored by the JavaScript engine but are essential for maintainability and developer communication.
- Single-line Comments: Prefixed with
//. - Multi-line Comments: Enclosed within
/* ... */. - JSDoc Comments: A standardized multi-line format (
/** ... */) used to document functions, parameter types, and return values, which modern IDEs parse for autocompletion and type checking.
JavaScript
/**
* Calculates the total price including tax.
* @param {number} subtotal - The base price.
* @param {number} taxRate - The applicable tax percentage.
* @returns {number} The final computed total.
*/
function calculateTotal(subtotal, taxRate) {
// Multiply subtotal by tax modifier
return subtotal * (1 + taxRate);
}
4. Variable Declarations
Modern JavaScript provides three keywords for declaring variables, each with distinct scoping and hoisting rules:
| Keyword | Scope | Hoisting Behavior | Reassignable? | Redeclarable? |
var |
Function Scope | Hoisted (initialized as undefined) |
Yes | Yes |
let |
Block Scope | Hoisted (Temporal Dead Zone) | Yes | No |
const |
Block Scope | Hoisted (Temporal Dead Zone) | No | No |
[Image of JavaScript block scope vs function scope memory allocation]
JavaScript
const API_URL = "https://api.example.com";
let currentUser = null;
if (true) {
let sessionActive = true; // Block-scoped to this if-statement
}
// console.log(sessionActive); // ReferenceError
5. Operators and Expressions
JavaScript features a rich suite of operators for manipulating data, evaluating conditions, and assigning values.
A. Arithmetic and Assignment
Standard mathematical operators (+, -, *, /, %, ** for exponentiation) combine with shorthand assignment operators (+=, -=, ++, --).
B. Comparison Operators
- Strict Equality (
===and!==): Compares both value and data type without performing implicit type coercion. Always use these. - Abstract Equality (
==and!=): Performs type coercion before comparing, frequently leading to non-intuitive logic (e.g.,0 == "" // true).
C. Modern Logical Operators
- Nullish Coalescing (
??): Returns the right-hand operand when the left-hand operand isnullorundefined, ignoring other falsy values like0or"". - Optional Chaining (
?.): Safely accesses nested object properties without throwing aTypeErrorif an intermediate property isnullorundefined.
JavaScript
const userProfile = { name: "Alice", settings: null };
const theme = userProfile.settings?.theme ?? "light"; // "light"
6. Control Flow Syntax
Controlling the execution path relies on standard conditional branching and iterative loops.
A. Conditionals
if...else if...else: Standard multi-branch decision tree.switch: Evaluates an expression against multiplecaseclauses, terminating with abreakstatement to prevent fall-through.- Ternary Operator (
cond ? trueExpr : falseExpr): A concise inline conditional expression.
B. Iteration (Loops)
for: Traditional counter-based loop.for...of: Iterates over iterable objects like Arrays, Strings, Maps, and Sets.for...in: Iterates over the enumerable property keys of an object.while/do...while: Evaluates a condition before or after executing a block.
JavaScript
const scores = [85, 92, 78];
for (const score of scores) {
console.log(score);
}
7. ES6+ Syntactic Sugar
Recent ECMAScript specifications introduced powerful syntactical shortcuts that drastically reduce boilerplate code:
-
Destructuring Assignment: Extract properties from objects or items from arrays into distinct variables with clean syntax.
JavaScript
const { name, role = "guest" } = user; -
Spread (
...) and Rest (...) Syntax: Expands iterables into individual elements or consolidates remaining parameters into an array.JavaScript
const combinedArray = [...arr1, ...arr2]; -
Template Literals: Enclosed in backticks (
`), allowing multi-line strings and embedded expressions via interpolation (${expression}).
