JavaScript Syntax and Fundamentals
1. JavaScript Syntax Structure and Statements
| Statement Type | Syntax | Description | Example |
|---|---|---|---|
| Expression Statement | expression; |
Any valid expression followed by semicolon (ASI applies) | x = 5; 2 + 2; |
| Declaration Statement | var/let/const name; |
Declares variables with specific scope and mutability | let x; const y = 10; |
| Block Statement | { statements } |
Groups multiple statements; creates block scope for let/const | { let x = 1; } |
| Empty Statement | ; |
Does nothing; useful in loop bodies or as placeholder | while(condition); |
| Labeled Statement | label: statement |
Adds identifier to statement for break/continue targeting | loop1: for(...) {...} |
| Function Declaration | function name() {} |
Hoisted function definition, available before declaration | function add(a,b) { return a+b; } |
| Class Declaration | class Name {} |
Declares class; not hoisted like functions | class User { constructor() {} } |
| Import Statement | import x from 'mod'; |
Loads module exports; hoisted and executed first | import { func } from './module'; |
| Export Statement | export default x; |
Exposes values/functions from module | export { func, var }; |
Example: Statement types in action
// Expression statements
x = 5;
y = x + 10;
// Block statement with local scope
{
let blockScoped = 'local';
const PI = 3.14159;
}
// Labeled statement for loop control
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break outer;
}
}
ASI (Automatic Semicolon Insertion): JavaScript automatically inserts semicolons in certain
cases, but relying on it can cause bugs. Always use explicit semicolons for clarity.
2. Variable Declarations (var, let, const)
| Declaration | Scope | Hoisting | Reassignment | Redeclaration | TDZ |
|---|---|---|---|---|---|
| var LEGACY | Function scope | Yes (undefined) | ✓ Allowed | ✓ Allowed | ✗ No |
| let ES6 | Block scope | Yes (uninitialized) | ✓ Allowed | ✗ SyntaxError | ✓ Yes |
| const ES6 | Block scope | Yes (uninitialized) | ✗ TypeError | ✗ SyntaxError | ✓ Yes |
| Feature | var | let | const |
|---|---|---|---|
| Global Object Property | ✓ Creates property on window/global | ✗ Does not create property | ✗ Does not create property |
| Loop Binding | Single binding (shared) | New binding per iteration | New binding per iteration |
| Initialization Required | ✗ Optional | ✗ Optional | ✓ Required at declaration |
| Object/Array Mutation | Allowed | Allowed | Allowed (reference is const) |
Example: Variable declaration differences
// var: function-scoped, hoisted
console.log(x); // undefined (hoisted)
var x = 5;
if (true) {
var x = 10; // Same variable
}
console.log(x); // 10
// let: block-scoped, TDZ
// console.log(y); // ReferenceError: Cannot access before initialization
let y = 5;
if (true) {
let y = 10; // Different variable
console.log(y); // 10
}
console.log(y); // 5
// const: block-scoped, immutable binding
const z = 5;
// z = 10; // TypeError: Assignment to constant
const obj = { a: 1 };
obj.a = 2; // ✓ OK: mutation allowed
// obj = {}; // ✗ TypeError: reassignment not allowed
Warning:
const creates an immutable binding, not an
immutable value. Object properties can still be modified.
3. Identifier Rules and Naming Conventions
| Rule | Description | Valid Examples | Invalid Examples |
|---|---|---|---|
| First Character | Letter (a-z, A-Z), underscore (_), or dollar sign ($) | _var, $elem, myVar |
1var, -name, @value |
| Subsequent Characters | Letters, digits (0-9), underscore, dollar sign | var1, _temp2, $el3 |
my-var, my.var, my var |
| Case Sensitivity | JavaScript is case-sensitive; myVar ≠ myvar | myVar, MyVar, MYVAR |
All are different variables |
| Unicode Support | Unicode letters allowed (international characters) | μ, café, 変数 |
Avoid for portability |
| Reserved Words | Cannot use JavaScript keywords as identifiers | myClass, _return |
class, return, if |
| Convention | Usage | Example | Purpose |
|---|---|---|---|
| camelCase | Variables, functions, methods | myVariable, getUserData() |
Standard for most identifiers |
| PascalCase | Classes, constructors, components | UserProfile, DataService |
Distinguishes classes from functions |
| UPPER_SNAKE_CASE | Constants, configuration values | MAX_SIZE, API_URL |
Indicates immutable values |
| _privateConvention | Private/internal members (convention) | _internalCache, _helper() |
Signals internal use only |
| #privateFields ES2022 | True private class fields | #privateValue |
Language-level privacy |
Example: Naming conventions in practice
// Constants
const MAX_RETRY_COUNT = 3;
const API_BASE_URL = 'https://api.example.com';
// Variables and functions (camelCase)
let userName = 'John';
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price, 0);
}
// Classes (PascalCase)
class UserProfile {
#privateData; // True private field
constructor(name) {
this._internalId = Math.random(); // Convention-based private
this.#privateData = name;
}
}
// Boolean variables (descriptive prefix)
const isActive = true;
const hasPermission = false;
const canEdit = user.role === 'admin';
4. Comments and Documentation Syntax
| Comment Type | Syntax | Usage | Example |
|---|---|---|---|
| Single-line | // comment |
Brief explanations, inline notes | // Calculate sum |
| Multi-line | /* comment */ |
Longer explanations, block comments | /* This is a multi-line comment */ |
| JSDoc Block | /** @tag */ |
API documentation, type annotations | /** @param {string} name */ |
| Hashbang | #!/usr/bin/env node |
Shebang for executable scripts (line 1 only) | Node.js CLI scripts |
| HTML-style LEGACY | <!-- comment --> |
Legacy browser compatibility (avoid) | Only in embedded scripts |
| JSDoc Tag | Purpose | Syntax | Example |
|---|---|---|---|
| @param | Function parameter documentation | @param {type} name description |
@param {number} age User's age |
| @returns | Return value description | @returns {type} description |
@returns {boolean} True if valid |
| @typedef | Custom type definition | @typedef {Object} TypeName |
@typedef {Object} User |
| @type | Variable type annotation | @type {type} |
@type {string[]} |
| @deprecated | Mark as deprecated | @deprecated Use newFunc instead |
Signals obsolete code |
| @example | Usage examples | @example functionCall() |
Provides code samples |
| @throws | Documents exceptions | @throws {Error} description |
@throws {TypeError} |
Example: JSDoc documentation
/**
* Calculates the total price with tax
* @param {number} price - Base price of item
* @param {number} taxRate - Tax rate as decimal (e.g., 0.08)
* @returns {number} Total price including tax
* @throws {TypeError} If parameters are not numbers
* @example
* calculateTotal(100, 0.08); // Returns 108
*/
function calculateTotal(price, taxRate) {
if (typeof price !== 'number' || typeof taxRate !== 'number') {
throw new TypeError('Parameters must be numbers');
}
return price * (1 + taxRate);
}
/**
* @typedef {Object} User
* @property {string} name - User's full name
* @property {number} age - User's age
* @property {string[]} roles - User roles
*/
/** @type {User} */
const user = {
name: 'John Doe',
age: 30,
roles: ['admin', 'user']
};
5. Strict Mode ("use strict") and Effects
| Aspect | Non-Strict Mode | Strict Mode | Impact |
|---|---|---|---|
| Activation | Default behavior | 'use strict'; at file/function start |
Enables stricter parsing and error handling |
| Implicit Globals | Creates global variable | ReferenceError | Prevents accidental globals from typos |
| Assignment to Non-writable | Silently fails | TypeError | Throws error on read-only property assignment |
| Delete Variables | Returns false | SyntaxError | Cannot delete variables, functions, or arguments |
| Duplicate Parameters | Allowed (last wins) | SyntaxError | Prevents function param name conflicts |
| Octal Literals | 0123 allowed |
SyntaxError | Use 0o123 instead |
| this in Functions | Global object (window) | undefined |
Prevents accidental global modifications |
| with Statement | Allowed | SyntaxError | Banned due to scope ambiguity |
| eval Scope | Creates variables in surrounding scope | Own scope only | Prevents eval from polluting scope |
| Reserved Words | Some allowed as identifiers | Stricter: implements, interface, let, package, private, protected, public, static, yield |
Future-proofs code for new keywords |
Example: Strict mode effects
'use strict';
// 1. Prevents implicit globals
// mistypedVariable = 17; // ReferenceError (without strict: creates global)
// 2. Prevents duplicate parameters
// function sum(a, a, c) { } // SyntaxError (without strict: allowed)
// 3. Makes 'this' undefined in functions
function showThis() {
console.log(this); // undefined (without strict: window/global)
}
showThis();
// 4. Prevents assignment to non-writable properties
const obj = {};
Object.defineProperty(obj, 'x', { value: 42, writable: false });
// obj.x = 9; // TypeError (without strict: silently fails)
// 5. Prevents deleting variables
let x = 10;
// delete x; // SyntaxError (without strict: returns false)
// 6. Safer eval
eval('var y = 2;');
// console.log(y); // ReferenceError (without strict: y accessible)
// 7. Octal literals banned
// const octal = 0123; // SyntaxError
const octalCorrect = 0o123; // ✓ Use 0o prefix
Note: ES6 modules and classes automatically use strict mode. No need to add
'use strict'; explicitly.
6. JavaScript Reserved Words and Keywords
| Category | Keywords | Description |
|---|---|---|
| Control Flow | if, else, switch, case, default, break, continue, return |
Conditional execution and flow control |
| Loops | for, while, do, in, of |
Iteration constructs |
| Declarations | var, let, const, function, class |
Variable and function definitions |
| Exception Handling | try, catch, finally, throw |
Error handling constructs |
| Object-Oriented | new, this, super, extends, static |
OOP keywords |
| Type/Value | null, undefined, true, false, NaN, Infinity |
Primitive values and special values |
| Operators | typeof, instanceof, void, delete, in |
Special operators |
| Module System | import, export, from, as, default |
ES6 module syntax |
| Async | async, await, yield |
Asynchronous programming keywords |
| Other | debugger, with DEPRECATED |
Debugging and legacy features |
| Future Reserved (Strict Mode) | Status | Notes |
|---|---|---|
implements, interface, package |
Reserved | Reserved for potential future use in strict mode |
private, protected, public |
Reserved | Access modifiers reserved for future features |
enum |
Reserved (all modes) | Reserved for enumeration type (not yet implemented) |
arguments, eval |
Restricted in strict mode | Cannot be used as identifiers or assigned to |
Warning: While some keywords like
undefined and NaN are not
technically reserved, they reference global properties and should not be used as variable names to avoid
confusion.
Section 1 Summary
- JavaScript uses various statement types for different purposes (expressions, declarations, blocks)
- Use let/const over
varfor block scoping and better error detection - Follow naming conventions: camelCase for variables/functions, PascalCase for classes, UPPER_SNAKE_CASE for constants
- JSDoc comments provide type information and documentation for better IDE support
- Strict mode catches common mistakes and prevents unsafe actions (auto-enabled in modules/classes)
- Avoid using reserved keywords as identifiers; they're reserved for language features