1.2-Basic-Syntax
1.2 Basic Syntax
š Table of Contents
Statements vs Expressions
Understanding the difference between statements and expressions is fundamental to understanding how JavaScript code works.
Expressions
An expression is any valid unit of code that produces a value.
// All of these are expressions - they produce values
5; // ā 5
5 + 3; // ā 8
('Hello'); // ā "Hello"
'Hello' + ' World'; // ā "Hello World"
x; // ā value of x
x > 5; // ā true or false
x ? 'yes' : 'no'; // ā "yes" or "no"
myFunction()[(1, 2, 3)]; // ā return value of function // ā array
{
name: 'John';
} // ā object
Types of Expressions:
| Type | Example | Result |
|---|---|---|
| Arithmetic | 5 + 3 * 2 | 11 |
| String | "Hello" + " World" | "Hello World" |
| Logical | true && false | false |
| Primary | this, myVariable | The value |
| Left-hand-side | obj.property | Property value |
| Assignment | x = 5 | 5 |
| Unary | !true, typeof x | Depends on operator |
| Ternary | x > 5 ? "big" : "small" | One of the values |
Key Insight: Expressions Can Be Used Anywhere a Value Is Expected
// Expressions can be:
// 1. Assigned to variables
let result = 5 + 3;
// 2. Passed as function arguments
console.log(5 + 3);
// 3. Used in other expressions
let total = (5 + 3) * 2;
// 4. Returned from functions
function add() {
return 5 + 3;
}
Statements
A statement is an instruction that performs an action. Statements do NOT produce values that can be used elsewhere.
// These are statements - they perform actions
// Variable declaration statement
let x = 5;
// If statement
if (x > 3) {
console.log('Big');
}
// Loop statement
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Function declaration statement
function sayHello() {
console.log('Hello');
}
// Switch statement
switch (x) {
case 1:
break;
default:
break;
}
Types of Statements:
| Statement Type | Example |
|---|---|
| Declaration | let x = 5; |
| Assignment | x = 10; (also an expression!) |
| Conditional | if (condition) {...} |
| Loop | for, while, do...while |
| Jump | break, continue, return |
| Try-Catch | try {...} catch {...} |
| Import/Export | import x from 'module' |
The Critical Difference
// ā This WON'T work - if statement doesn't produce a value
let result = if (true) { 5 }; // SyntaxError!
// ā
This WORKS - ternary expression produces a value
let result = true ? 5 : 0; // result = 5
// ā This WON'T work - can't use a statement where expression is expected
console.log(if (true) { 5 }); // SyntaxError!
// ā
This WORKS - expressions can be used as arguments
console.log(true ? 5 : 0); // 5
Expression Statements
Some expressions can stand alone as statements:
// These are expression statements (expressions used as statements)
5 + 3; // Valid but useless
x = 5; // Assignment expression as statement
myFunction(); // Function call expression as statement
x++; // Increment expression as statement
Visual Summary:
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā EXPRESSIONS ā
ā ⢠Produce values ā
ā ⢠Can be used anywhere values are expected ā
ā ⢠Examples: 5 + 3, "hello", x > 5, fn() ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā STATEMENTS ā
ā ⢠Perform actions ā
ā ⢠Cannot be used where values are expected ā
ā ⢠Examples: if, for, while, function declaration ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Identifiers
Identifiers are names given to variables, functions, classes, and other entities in your code.
Rules for Identifiers:
| Rule | Valid Examples | Invalid Examples |
|---|---|---|
Must start with letter, _, or $ | name, _private, $element | 123abc, #tag |
Can contain letters, digits, _, $ | user2, first_name | user-name, my.var |
| Case-sensitive | Name ā name ā NAME | ā |
| Cannot be reserved words | ā | if, for, class |
Valid Identifiers:
// All of these are valid
let name;
let Name;
let NAME;
let _private;
let $jquery;
let camelCase;
let snake_case;
let PascalCase;
let user123;
let _123;
let $_$;
Invalid Identifiers:
// These will cause errors
let 123user; // Cannot start with number
let my-variable; // Cannot contain hyphen
let my.variable; // Cannot contain dot
let my variable; // Cannot contain space
let class; // Reserved word
let if; // Reserved word
let for; // Reserved word
Reserved Words (Cannot Be Used as Identifiers):
// Keywords
break case catch class const
continue debugger default delete do
else export extends finally for
function if import in instanceof
let new return static super
switch this throw try typeof
var void while with yield
// Future reserved words (strict mode)
implements interface package private protected
public
// Literals
null true false
// Special (avoid using)
undefined NaN Infinity arguments eval
Naming Conventions (Best Practices):
// Variables and functions: camelCase
let userName = 'John';
let firstName = 'Jane';
function calculateTotal() {}
function getUserById() {}
// Constants: UPPER_SNAKE_CASE
const MAX_SIZE = 100;
const API_BASE_URL = 'https://api.example.com';
const DEFAULT_TIMEOUT = 3000;
// Classes: PascalCase
class UserAccount {}
class ShoppingCart {}
class HttpRequest {}
// Private members (convention): _prefix or #prefix
let _privateVar = 'internal';
class MyClass {
#privateField = 'truly private';
}
// Boolean variables: is/has/can prefixes
let isActive = true;
let hasPermission = false;
let canEdit = true;
// Functions: verb prefixes
function getUser() {}
function setName() {}
function validateInput() {}
function calculatePrice() {}
function handleClick() {}
Meaningful Names:
// ā Bad - Unclear meaning
let x = 5;
let temp = 'John';
let data = [1, 2, 3];
function fn() {}
// ā
Good - Clear and descriptive
let userAge = 5;
let userName = 'John';
let productPrices = [1, 2, 3];
function calculateDiscount() {}
Whitespace Rules
JavaScript is generally whitespace-insensitive, but there are important rules to understand.
Where Whitespace Doesn't Matter:
// These are all equivalent:
let x = 5 + 3;
let x = 5 + 3;
let x = 5 + 3;
// These are equivalent:
function greet(name) {
return 'Hello ' + name;
}
function greet(name) {
return 'Hello ' + name;
}
function greet(name) {
return 'Hello ' + name;
}
Where Whitespace Matters:
1. Inside Strings
// Whitespace is preserved inside strings
let message1 = 'Hello World'; // Has one space
let message2 = 'Hello World'; // Has two spaces
let message3 = 'Hello World'; // Has three spaces
// These are NOT equal
'Hello World' === 'Hello World'; // false
2. Between Keywords and Identifiers
// ā
Correct - space required
let x = 5;
typeof x;
return value;
new Object();
// ā Wrong - no space causes errors or different meaning
letx = 5; // Error: letx is not defined
typeofx; // Error: typeofx is not defined
returnvalue; // Error: returnvalue is not defined
3. Line Breaks Can Affect Behavior (ASI)
// Watch out for automatic semicolon insertion!
// ā This returns undefined, not the object!
function getObject() {
return;
{
name: 'John';
}
}
// ā
This returns the object correctly
function getObject() {
return {
name: 'John',
};
}
Types of Whitespace Characters:
| Character | Name | Escape Sequence |
|---|---|---|
| Space | Space | |
| Tab | Horizontal Tab | \t |
| Newline | Line Feed | \n |
| Carriage Return | Carriage Return | \r |
Indentation Best Practices:
// Use consistent indentation (2 or 4 spaces)
// 2-space indentation
function example() {
if (true) {
console.log('Hello');
}
}
// 4-space indentation
function example() {
if (true) {
console.log('Hello');
}
}
// Avoid mixing tabs and spaces!
Semicolons and ASI
Semicolons in JavaScript
Semicolons (;) are used to terminate statements in JavaScript.
// Statements with semicolons
let x = 5;
let y = 10;
console.log(x + y);
Automatic Semicolon Insertion (ASI)
JavaScript has a feature called Automatic Semicolon Insertion (ASI) that automatically inserts semicolons in certain situations.
// JavaScript automatically inserts semicolons here:
let x = 5; // ; inserted
let y = 10; // ; inserted
console.log(x + y); // ; inserted
When ASI Inserts Semicolons:
- ā¢Before a line break (if the next token would cause an error)
- ā¢Before a closing brace
} - ā¢At the end of the program
ASI Rules in Detail:
// Rule 1: Before line break when next line would cause error
let a = 1;
let b = 2;
// Becomes: let a = 1; let b = 2;
// Rule 2: Before closing brace
if (true) {
return 5;
}
// Becomes: if (true) { return 5; }
// Rule 3: After return, break, continue, throw + line break
return;
5;
// Becomes: return; 5; (NOT return 5!)
Dangerous ASI Cases:
Case 1: Return Statement
// ā DANGER! Returns undefined, not the object
function getUser() {
return;
{
name: 'John';
}
}
// ASI makes it: return; { name: "John" };
// ā
CORRECT - Start object on same line
function getUser() {
return {
name: 'John',
};
}
Case 2: Lines Starting with (, [, /
// ā DANGER! These can cause problems without semicolons
let x = 5(function () {
console.log('IIFE');
})();
// Interpreted as: let x = 5(function() {...})() - Error!
let y = (10)[(1, 2, 3)].forEach((n) => console.log(n));
// Interpreted as: let y = 10[1, 2, 3].forEach(...) - Error!
// ā
SAFE - Add semicolons
let x = 5;
(function () {
console.log('IIFE');
})();
let y = 10;
[1, 2, 3].forEach((n) => console.log(n));
Case 3: No ASI After These Tokens
ASI does NOT insert semicolons after:
- ā¢
++and-- - ā¢
for,while,if,switch,try - ā¢Empty statements
// These work across lines:
x;
++y;
// Becomes: x++; y; (NOT x; ++y;)
The Great Semicolon Debate
There are two camps in JavaScript:
Team Semicolons (Always Use Them)
// Explicit semicolons - safer and clearer
let name = 'John';
let age = 30;
function greet() {
return 'Hello';
}
Team No Semicolons (Rely on ASI)
// No semicolons - cleaner looking
let name = 'John';
let age = 30;
function greet() {
return 'Hello';
}
Recommendation for Beginners:
Always use semicolons. Here's why:
- ā¢Makes code intentions explicit
- ā¢Avoids subtle bugs from ASI
- ā¢More consistent with other languages
- ā¢Easier to debug and read
- ā¢Most style guides recommend them
When Semicolons Are NOT Used:
// After function declarations
function greet() {
console.log('Hello');
} // No semicolon needed here
// After if/else blocks
if (true) {
console.log('Yes');
} // No semicolon needed here
// After for/while loops
for (let i = 0; i < 5; i++) {
console.log(i);
} // No semicolon needed here
// After class declarations
class Person {
constructor() {}
} // No semicolon needed here
// BUT semicolons ARE used after:
// - Variable declarations: let x = 5;
// - Expression statements: console.log("Hi");
// - Function expressions: let greet = function() {};
// - Class expressions: let Person = class {};
Comments
Comments are used to explain code and make it more readable. JavaScript ignores comments during execution.
Single-Line Comments
Use // for single-line comments:
// This is a single-line comment
let x = 5; // This comment is at the end of a line
// You can have multiple
// single-line comments
// for longer explanations
Multi-Line Comments
Use /* */ for multi-line comments:
/* This is a
multi-line comment
spanning multiple lines */
/*
* This is a common style
* for multi-line comments
* with asterisks for alignment
*/
/* Single line using multi-line syntax */
Documentation Comments (JSDoc)
JSDoc comments use /** */ and are used for documentation:
/**
* Calculates the sum of two numbers.
*
* @param {number} a - The first number
* @param {number} b - The second number
* @returns {number} The sum of a and b
* @example
* // Returns 8
* add(5, 3);
*/
function add(a, b) {
return a + b;
}
/**
* Represents a person.
* @class
*/
class Person {
/**
* Create a person.
* @param {string} name - The person's name.
* @param {number} age - The person's age.
*/
constructor(name, age) {
this.name = name;
this.age = age;
}
}
Common JSDoc Tags:
| Tag | Purpose | Example |
|---|---|---|
@param | Document a parameter | @param {string} name - User's name |
@returns | Document return value | @returns {number} The result |
@type | Specify a type | @type {string} |
@example | Provide usage example | @example add(1, 2) |
@deprecated | Mark as deprecated | @deprecated Use newMethod instead |
@throws | Document exceptions | @throws {Error} If invalid input |
@see | Reference related items | @see OtherClass |
@todo | Mark incomplete work | @todo Add validation |
When to Comment:
ā Good Comments - Explain WHY
// Using bitwise OR for fast floor operation
// This is faster than Math.floor() in performance-critical code
let floored = 5.7 | 0;
// Workaround for Safari flexbox bug (issue #234)
container.style.minHeight = '1px';
// Rate limit to prevent API abuse
// Max 100 requests per minute
if (requestCount > 100) {
throw new Error('Rate limit exceeded');
}
ā Bad Comments - Explain WHAT (Code Already Says This)
// Bad - explains the obvious
let x = 5; // Set x to 5
i++; // Increment i
arr.push(item); // Add item to array
// Good - no comment needed, code is self-explanatory
let userAge = 5;
currentIndex++;
shoppingCart.push(newItem);
Comment Best Practices:
// 1. Keep comments up to date with code changes
// ā Outdated comment
// Returns the user's full name
function getUser() {
return { firstName: 'John', lastName: 'Doe' }; // Actually returns object!
}
// 2. Use comments to explain complex logic
// Calculate compound interest: A = P(1 + r/n)^(nt)
// Where: P = principal, r = rate, n = compounds per year, t = years
function compoundInterest(principal, rate, compounds, years) {
return principal * Math.pow(1 + rate / compounds, compounds * years);
}
// 3. Mark temporary code or TODOs
// TODO: Refactor this to use async/await
// FIXME: This doesn't handle edge case when list is empty
// HACK: Temporary solution until API is fixed
// NOTE: This requires minimum browser version Chrome 80+
// 4. Use comments to section your code
// ==========================================
// USER MANAGEMENT
// ==========================================
function createUser() {
/* ... */
}
function deleteUser() {
/* ... */
}
// ==========================================
// DATA PROCESSING
// ==========================================
function processData() {
/* ... */
}
Commenting Out Code:
// You can use comments to temporarily disable code:
function calculate() {
let result = 0;
// Old implementation - keeping for reference
// result = complexCalculation();
// New faster implementation
result = optimizedCalculation();
return result;
}
/*
* Large block of code can be disabled like this
* function oldFunction() {
* // ...
* }
*/
VS Code Comment Shortcuts:
| Shortcut | Action |
|---|---|
Ctrl + / | Toggle line comment |
Shift + Alt + A | Toggle block comment |
Ctrl + K, Ctrl + C | Add line comment |
Ctrl + K, Ctrl + U | Remove line comment |
šÆ Key Takeaways
- ā¢Expressions produce values, statements perform actions
- ā¢Identifiers follow specific naming rules and conventions (camelCase for variables)
- ā¢Whitespace generally doesn't matter except in strings and certain contexts
- ā¢Semicolons can be automatic (ASI) but explicit semicolons are recommended
- ā¢Comments should explain WHY, not WHAT - use JSDoc for documentation
ā”ļø Next Module
Continue to Module 2: Variables & Data Types to learn about storing and working with data in JavaScript!