javascript

examples

examples.js
/**
 * ============================================
 * 1.2 Basic Syntax - Examples
 * ============================================
 *
 * This file demonstrates the fundamental syntax concepts
 * covered in the README. Run in browser console or HTML file.
 */

// ============================================
// STATEMENTS VS EXPRESSIONS
// ============================================

console.log('=== STATEMENTS VS EXPRESSIONS ===\n');

// --- Expressions (they produce values) ---

// Arithmetic expressions
console.log('Arithmetic expression: 5 + 3 =', 5 + 3);

// String expressions
console.log('String expression:', 'Hello' + ' ' + 'World');

// Logical expressions
console.log('Logical expression: 5 > 3 is', 5 > 3);

// Ternary expression (conditional expression)
let age = 20;
let status = age >= 18 ? 'adult' : 'minor';
console.log('Ternary expression result:', status);

// Assignment expression (assigns AND returns the value)
let x;
console.log('Assignment expression returns:', (x = 10)); // Returns 10

// Function call expression
function getGreeting() {
  return 'Hello!';
}
console.log('Function call expression:', getGreeting());

// --- Statements (they perform actions) ---

// Variable declaration statement
let myVariable = 100;

// If statement (cannot be used where a value is expected)
if (myVariable > 50) {
  console.log('If statement executed: value is greater than 50');
}

// For loop statement
console.log('For loop statement:');
for (let i = 1; i <= 3; i++) {
  console.log('  Loop iteration:', i);
}

// --- Expression Statements ---
// Expressions can be used as statements

console.log('\n--- Expression Statements ---');
5 + 3; // Valid but does nothing useful
x = 20; // Assignment expression as statement
console.log(x); // Function call expression as statement

// ============================================
// IDENTIFIERS
// ============================================

console.log('\n=== IDENTIFIERS ===\n');

// Valid identifier examples
let userName = 'John'; // camelCase (recommended for variables)
let _privateData = 'secret'; // Starts with underscore
let $element = 'DOM element'; // Starts with dollar sign
let firstName = 'Jane'; // camelCase
let user2 = 'Second user'; // Contains number
let snake_case = 'also valid'; // Underscores

console.log('Valid identifiers:');
console.log('  userName:', userName);
console.log('  _privateData:', _privateData);
console.log('  $element:', $element);

// Case sensitivity
let Name = 'uppercase N';
let name = 'lowercase n';
let NAME = 'all uppercase';

console.log('\nCase sensitivity:');
console.log('  Name:', Name);
console.log('  name:', name);
console.log('  NAME:', NAME);

// Naming conventions demonstration
const MAX_SIZE = 100; // Constants: UPPER_SNAKE_CASE
const API_BASE_URL = 'https://api.com';

class UserProfile {} // Classes: PascalCase
class ShoppingCart {}

let isLoggedIn = true; // Booleans: is/has/can prefix
let hasPermission = false;
let canEdit = true;

function getUserById() {} // Functions: verb prefix
function calculateTotal() {}

console.log('\nNaming conventions:');
console.log('  Constant MAX_SIZE:', MAX_SIZE);
console.log('  Boolean isLoggedIn:', isLoggedIn);

// ============================================
// WHITESPACE RULES
// ============================================

console.log('\n=== WHITESPACE RULES ===\n');

// Whitespace generally doesn't matter
let a = 5 + 3;
let b = 5 + 3;
let c = 5 + 3;

console.log('Whitespace flexibility:');
console.log('  a=5+3 →', a);
console.log('  b = 5 + 3 →', b);
console.log('  c  =  5  +  3 →', c);

// But whitespace in strings is preserved!
let str1 = 'Hello World';
let str2 = 'Hello  World';
let str3 = 'Hello   World';

console.log('\nWhitespace in strings is preserved:');
console.log("  'Hello World' length:", str1.length);
console.log("  'Hello  World' length:", str2.length);
console.log("  'Hello   World' length:", str3.length);

// Tab and newline in strings
let formatted = 'Line 1\n\tLine 2 (tabbed)';
console.log('\nFormatted string with \\n and \\t:');
console.log(formatted);

// ============================================
// SEMICOLONS AND ASI
// ============================================

console.log('\n=== SEMICOLONS AND ASI ===\n');

// Explicit semicolons (recommended)
let explicit1 = 'first';
let explicit2 = 'second';
console.log('Explicit semicolons:', explicit1, explicit2);

// ASI (Automatic Semicolon Insertion) adds them automatically
let implicit1 = 'third';
let implicit2 = 'fourth';
console.log('ASI adds semicolons:', implicit1, implicit2);

// DANGEROUS: Return statement with ASI
function dangerousReturn() {
  return;
  {
    name: 'John';
  }
}
console.log('\nDangerous return (ASI issue):', dangerousReturn()); // undefined!

// SAFE: Return statement on same line
function safeReturn() {
  return {
    name: 'John',
  };
}
console.log('Safe return:', safeReturn()); // {name: "John"}

// When semicolons are NOT used
function noSemicolonNeeded() {
  console.log('After function blocks, no semicolon needed');
}

if (true) {
  console.log('After if blocks, no semicolon needed');
}

for (let i = 0; i < 1; i++) {
  console.log('After for loops, no semicolon needed');
}

// ============================================
// COMMENTS
// ============================================

console.log('\n=== COMMENTS ===\n');

// This is a single-line comment
console.log('Code after single-line comment executes');

/* This is a 
   multi-line comment
   spanning several lines */
console.log('Code after multi-line comment executes');

/**
 * This is a JSDoc comment
 * Used for documentation
 * @param {string} name - The name to greet
 * @returns {string} The greeting message
 */
function greet(name) {
  return 'Hello, ' + name + '!';
}
console.log('JSDoc documented function:', greet('World'));

// Comments can explain WHY
// Using bitwise OR for fast floor operation (performance optimization)
let quickFloor = 5.7 | 0;
console.log('Bitwise floor of 5.7:', quickFloor);

// ============================================
// EXPRESSION VS STATEMENT COMPARISON
// ============================================

console.log('\n=== EXPRESSION VS STATEMENT COMPARISON ===\n');

// Ternary (expression) vs if/else (statement)
let score = 85;

// Using ternary expression - can be assigned directly
let gradeExpr = score >= 90 ? 'A' : score >= 80 ? 'B' : 'C';
console.log('Ternary expression result:', gradeExpr);

// Using if/else statement - cannot be assigned directly
let gradeStmt;
if (score >= 90) {
  gradeStmt = 'A';
} else if (score >= 80) {
  gradeStmt = 'B';
} else {
  gradeStmt = 'C';
}
console.log('If/else statement result:', gradeStmt);

// Expressions can be used inside other expressions
console.log('Nested expression:', 2 * (score > 80 ? 10 : 5));

// ============================================
// IDENTIFIER CONVENTIONS IN ACTION
// ============================================

console.log('\n=== IDENTIFIER CONVENTIONS IN ACTION ===\n');

// Real-world naming example
const MAX_LOGIN_ATTEMPTS = 3;
const SESSION_TIMEOUT = 1800;

class UserAccount {
  constructor(username) {
    this._loginAttempts = 0;
    this.username = username;
    this.isActive = true;
  }

  canLogin() {
    return this._loginAttempts < MAX_LOGIN_ATTEMPTS;
  }

  incrementLoginAttempts() {
    this._loginAttempts++;
  }
}

let currentUser = new UserAccount('john_doe');
console.log('User can login:', currentUser.canLogin());
console.log('User is active:', currentUser.isActive);

// ============================================
// SEMICOLON EDGE CASES
// ============================================

console.log('\n=== SEMICOLON EDGE CASES ===\n');

// Safe: Using semicolons before IIFE
let value = 10;
(function () {
  console.log('IIFE executed safely');
})();

// Safe: Using semicolons before array
let arr = [1, 2, 3];
[4, 5, 6].forEach(function (n) {
  console.log('  Array item:', n);
});

// ============================================
// PRACTICAL EXAMPLES
// ============================================

console.log('\n=== PRACTICAL EXAMPLES ===\n');

// Good variable naming
let userFirstName = 'John';
let userLastName = 'Doe';
let userFullName = userFirstName + ' ' + userLastName;

let itemCount = 5;
let isCartEmpty = itemCount === 0;
let hasItems = itemCount > 0;

console.log('Full name:', userFullName);
console.log('Is cart empty:', isCartEmpty);
console.log('Has items:', hasItems);

// Function with good naming
function calculateTotalPrice(items, taxRate) {
  let subtotal = items.reduce((sum, item) => sum + item.price, 0);
  let tax = subtotal * taxRate;
  return subtotal + tax;
}

let cartItems = [
  { name: 'Book', price: 20 },
  { name: 'Pen', price: 5 },
];

console.log('Total price:', calculateTotalPrice(cartItems, 0.1));

// ============================================
// SUMMARY
// ============================================

console.log('\n=== SUMMARY ===');
console.log('1. Expressions produce values, statements perform actions');
console.log('2. Use camelCase for variables, UPPER_CASE for constants');
console.log('3. Whitespace is flexible except in strings');
console.log('4. Always use explicit semicolons (recommended)');
console.log('5. Comments should explain WHY, not WHAT');
Examples - JavaScript Tutorial | DeepML