javascript

examples

examples.js
/**
 * ============================================
 * 1.1 Introduction to JavaScript - Examples
 * ============================================
 *
 * This file contains practical examples of the concepts
 * covered in the README. Run these in your browser console
 * or create an HTML file to see them in action.
 */

// ============================================
// EXAMPLE 1: Your First JavaScript Program
// ============================================

console.log('Hello, World!');
// Output: Hello, World!

// This is the traditional first program in any language
// console.log() displays output in the browser's console

// ============================================
// EXAMPLE 2: JavaScript in HTML (save as .html file)
// ============================================

/*
<!DOCTYPE html>
<html>
<head>
    <title>My First JavaScript</title>
</head>
<body>
    <h1 id="greeting">Hello</h1>
    <button onclick="changeGreeting()">Click Me</button>
    
    <script>
        function changeGreeting() {
            document.getElementById('greeting').textContent = 'Welcome to JavaScript!';
        }
    </script>
</body>
</html>
*/

// ============================================
// EXAMPLE 3: Console Methods Demonstration
// ============================================

// Basic logging - Different types of console output
console.log('This is a regular log message');
console.info('This is an informational message');
console.warn('This is a warning message');
console.error('This is an error message');

// ============================================
// EXAMPLE 4: Console Table for Objects
// ============================================

const students = [
  { name: 'Alice', age: 22, grade: 'A' },
  { name: 'Bob', age: 24, grade: 'B' },
  { name: 'Charlie', age: 23, grade: 'A' },
];

console.table(students);
// Displays data in a nicely formatted table in the console

// ============================================
// EXAMPLE 5: Console Grouping
// ============================================

console.group('User Information');
console.log('Name: John Doe');
console.log('Email: john@example.com');
console.log('Age: 30');
console.groupEnd();

// Groups related console messages together

// ============================================
// EXAMPLE 6: Timing Code Execution
// ============================================

console.time('Loop Timer');

let sum = 0;
for (let i = 0; i < 1000000; i++) {
  sum += i;
}

console.timeEnd('Loop Timer');
// Output: Loop Timer: X.XXms
// Shows how long the code took to execute

// ============================================
// EXAMPLE 7: Counting Occurrences
// ============================================

for (let i = 0; i < 5; i++) {
  console.count('Loop iteration');
}
// Output:
// Loop iteration: 1
// Loop iteration: 2
// Loop iteration: 3
// Loop iteration: 4
// Loop iteration: 5

// ============================================
// EXAMPLE 8: Using typeof to Check Types
// ============================================

console.log(typeof 'Hello'); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (this is a known JavaScript quirk!)
console.log(typeof {}); // "object"
console.log(typeof []); // "object" (arrays are objects in JS)
console.log(typeof function () {}); // "function"

// ============================================
// EXAMPLE 9: Basic Arithmetic in Console
// ============================================

console.log('Basic Math Operations:');
console.log('5 + 3 =', 5 + 3); // 8
console.log('10 - 4 =', 10 - 4); // 6
console.log('6 * 7 =', 6 * 7); // 42
console.log('20 / 4 =', 20 / 4); // 5
console.log('17 % 5 =', 17 % 5); // 2 (remainder)
console.log('2 ** 8 =', 2 ** 8); // 256 (exponentiation)

// ============================================
// EXAMPLE 10: String Operations
// ============================================

console.log('String Operations:');
console.log('Hello' + ' ' + 'World'); // Concatenation
console.log('JavaScript'.length); // 10 (string length)
console.log('JavaScript'.toUpperCase()); // "JAVASCRIPT"
console.log('JavaScript'.toLowerCase()); // "javascript"

// ============================================
// EXAMPLE 11: Using the Debugger Statement
// ============================================

function calculateArea(width, height) {
  debugger; // Open DevTools, then run this function
  // Execution will pause here when DevTools is open
  const area = width * height;
  return area;
}

// Uncomment to test:
// calculateArea(5, 10);

// ============================================
// EXAMPLE 12: Call Stack Demonstration
// ============================================

function first() {
  console.log('First function - start');
  second();
  console.log('First function - end');
}

function second() {
  console.log('  Second function - start');
  third();
  console.log('  Second function - end');
}

function third() {
  console.log('    Third function - executing');
}

console.log('\n--- Call Stack Demo ---');
first();

/* Output:
--- Call Stack Demo ---
First function - start
  Second function - start
    Third function - executing
  Second function - end
First function - end
*/

// ============================================
// EXAMPLE 13: Synchronous Execution
// ============================================

console.log('\n--- Synchronous Execution Demo ---');
console.log('Step 1');
console.log('Step 2');
console.log('Step 3');
console.log('Step 4');
console.log('Step 5');

// Each line executes in order, one after another

// ============================================
// EXAMPLE 14: Console Assert
// ============================================

console.log('\n--- Console Assert Demo ---');

const age = 25;
console.assert(age >= 18, 'User is not an adult');
// No output because assertion passes

const minorAge = 15;
console.assert(minorAge >= 18, 'User is not an adult');
// Output: Assertion failed: User is not an adult

// ============================================
// EXAMPLE 15: Console Dir
// ============================================

console.log('\n--- Console Dir Demo ---');

const person = {
  name: 'John',
  age: 30,
  greet: function () {
    return 'Hello!';
  },
};

console.log(person); // Shows object
console.dir(person); // Shows object with expandable properties

// ============================================
// EXAMPLE 16: Console Trace
// ============================================

function outerFunction() {
  innerFunction();
}

function innerFunction() {
  deepFunction();
}

function deepFunction() {
  console.trace('Trace from deepFunction');
}

console.log('\n--- Console Trace Demo ---');
outerFunction();
// Shows the complete call stack leading to this point

// ============================================
// EXAMPLE 17: Checking JavaScript Engine
// ============================================

console.log('\n--- Browser/Engine Info ---');

// Check if running in a browser
if (typeof window !== 'undefined') {
  console.log('Running in a browser environment');
  console.log('User Agent:', navigator.userAgent);
}

// ============================================
// EXAMPLE 18: Clear Console
// ============================================

// console.clear();
// Uncomment the line above to clear the console
// Useful when you want a fresh start

// ============================================
// HOW TO RUN THESE EXAMPLES
// ============================================

/*
Method 1: Browser Console
1. Open Chrome/Firefox/Edge
2. Press F12 or Ctrl+Shift+I (Cmd+Option+I on Mac)
3. Go to Console tab
4. Copy and paste any example

Method 2: HTML File
1. Create a file named 'index.html'
2. Add this content:

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Examples</title>
</head>
<body>
    <h1>Open Console (F12) to see output</h1>
    <script src="examples.js"></script>
</body>
</html>

3. Open the HTML file in your browser
4. Open DevTools (F12) and check the Console tab

Method 3: VS Code Live Server
1. Install "Live Server" extension in VS Code
2. Create index.html as shown above
3. Right-click and select "Open with Live Server"
4. Open DevTools in the browser
*/
Examples - JavaScript Tutorial | DeepML