Menu

HTML & JS Topic

JavaScript Basics

What is JavaScript?

JavaScript is:

  1. A programming language - Creates interactive web content

  2. Client-side - Runs in the browser (though Node.js runs on servers too)

  3. Interpreted - No compilation needed, runs line-by-line

  4. Dynamic - Can change HTML/CSS after page loads

  5. Multi-paradigm - Supports procedural, object-oriented, functional styles

What JavaScript Can Do:

html

<!-- BEFORE JavaScript -->
<p id="demo">Hello World!</p>
<button>Click me</button>

<!-- AFTER JavaScript runs -->
<p id="demo">Hello JavaScript!</p>
<!-- The button now actually does something -->

Key Characteristics:

  • Manipulates HTML/CSS (DOM manipulation)

  • Handles events (clicks, forms, keyboard)

  • Makes API calls (fetch data from servers)

  • Stores data (cookies, localStorage)

  • Animations & effects

Adding JavaScript to HTML

1. Internal JavaScript (Inline)

html

<!-- Using script tag in head -->
<!DOCTYPE html>
<html>
<head>
    <script>
        function showAlert() {
            alert('Hello from internal JS!');
        }
    </script>
</head>
<body>
    <button onclick="showAlert()">Click me</button>
</body>
</html>

2. Internal JavaScript (In body - Recommended)

html

<!DOCTYPE html>
<html>
<body>
    <p id="demo">Initial text</p>
    
    <script>
        // Script runs after HTML above is loaded
        document.getElementById("demo").innerHTML = "Changed by JS!";
    </script>
    
    <p>More HTML content</p>
</body>
</html>

3. External JavaScript File (Best Practice)

html

<!DOCTYPE html>
<html>
<head>
    <!-- Load external JS file -->
    <script src="script.js" defer></script>
    <!-- 'defer' loads script after HTML is parsed -->
</head>
<body>
    <p id="demo">External JS will change this</p>
</body>
</html>

javascript

// script.js (external file)
document.getElementById("demo").innerHTML = "Changed by external JS!";

4. Different Loading Strategies:

html

<!-- 1. Script in head (blocks rendering) -->
<head>
    <script src="script.js"></script>  <!-- BAD - blocks page -->
</head>

<!-- 2. Script at end of body (recommended) -->
<body>
    <!-- All HTML content -->
    <script src="script.js"></script>  <!-- GOOD - page loads first -->
</body>

<!-- 3. Using defer (modern approach) -->
<head>
    <script src="script.js" defer></script>  <!-- BEST - parallel load -->
</head>

<!-- 4. Using async (for independent scripts) -->
<script src="analytics.js" async></script>  <!-- Loads/executes async -->

Loading Order Examples:

html

<script>
    console.log("Script 1 - runs immediately");
</script>

<script src="external.js" defer></script>
<script src="another.js" defer></script>
<!-- Deferred scripts run in order after HTML parsing -->

<script src="async.js" async></script>
<!-- Async scripts load and run ASAP, order not guaranteed -->

Console & Debugging

Console Methods:

javascript

// 1. Basic logging
console.log("Hello Console!");          // General output
console.info("Information message");    // Informational
console.warn("Warning message");        // Warning (yellow)
console.error("Error message");         // Error (red)

// 2. Grouping
console.group("User Data");
console.log("Name: John");
console.log("Age: 30");
console.groupEnd();

// 3. Tables
const users = [
    { name: "Alice", age: 25 },
    { name: "Bob", age: 30 }
];
console.table(users);

// 4. Timing
console.time("Timer");
// Some code to measure
for(let i = 0; i < 1000000; i++) {}
console.timeEnd("Timer");

// 5. Counting
console.count("Button Click");  // Button Click: 1
console.count("Button Click");  // Button Click: 2

// 6. Tracing
function a() { b(); }
function b() { c(); }
function c() { console.trace(); }
a();  // Shows call stack

Debugging Techniques:

javascript

// 1. Using debugger statement
function calculate(x, y) {
    debugger;  // Pauses here in browser dev tools
    return x * y;
}
calculate(5, 3);

// 2. Conditional logging
const DEBUG = true;
if (DEBUG) {
    console.log("Debug info:", someVariable);
}

// 3. Assertions
console.assert(1 === 2, "Math is broken!");  // Shows error if false

// 4. String substitution
const name = "John";
const age = 30;
console.log("User: %s, Age: %d", name, age);  // Old way
console.log(`User: ${name}, Age: ${age}`);     // Modern way

Common Console Tricks:

javascript

// Clear console
console.clear();

// Style console output
console.log("%cStyled Text", "color: red; font-size: 20px;");

// View DOM elements
const elem = document.querySelector("p");
console.dir(elem);  // Shows DOM properties

// Log with context
const obj = { id: 1, name: "Test" };
console.log({ obj });  // Shows: {obj: {id: 1, name: "Test"}}

// Measure memory
console.memory;  // Shows memory usage

Variables

Variable Declaration Keywords:

1. var (Old way - Avoid in modern code)

javascript

var name = "John";  // Function-scoped or global
var name = "Jane";   // Can be redeclared (problem!)
name = "Bob";        // Can be reassigned

console.log(name);  // Bob

// Issues with var:
for (var i = 0; i < 3; i++) {
    setTimeout(function() {
        console.log(i);  // Prints 3, 3, 3 (not 0, 1, 2)
    }, 100);
}

2. let (Modern - Block-scoped)

javascript

let age = 30;        // Block-scoped
// let age = 31;     // ERROR: Cannot redeclare in same scope
age = 31;            // OK: Can reassign

if (true) {
    let message = "Hello";  // Only exists in this block
    console.log(message);   // "Hello"
}
// console.log(message);    // ERROR: message not defined

// Works correctly with loops:
for (let i = 0; i < 3; i++) {
    setTimeout(function() {
        console.log(i);  // Prints 0, 1, 2 correctly
    }, 100);
}

3. const (Modern - Constant reference)

javascript

const PI = 3.14159;          // Must initialize immediately
// PI = 3.14;                // ERROR: Cannot reassign
// const PI = 3.14;          // ERROR: Cannot redeclare

// Const with objects/arrays:
const person = { name: "John" };
person.name = "Jane";        // OK: Can modify properties
person.age = 30;             // OK: Can add properties
// person = { name: "Bob" }; // ERROR: Cannot reassign

const numbers = [1, 2, 3];
numbers.push(4);             // OK: Can modify array
numbers[0] = 10;             // OK: Can change elements
// numbers = [5, 6, 7];      // ERROR: Cannot reassign

Variable Examples:

javascript

// Declaration without initialization
let username;
console.log(username);  // undefined

// Multiple variables
let a = 1, b = 2, c = 3;

// Variable naming conventions
let firstName = "John";      // camelCase (most common)
let first_name = "John";     // snake_case
let FirstName = "John";      // PascalCase (for classes)
// let 1stName = "John";     // ERROR: Cannot start with number
let $price = 9.99;           // Allowed: starts with $
let _private = "secret";     // Allowed: starts with _
let firstName2 = "Jane";     // Allowed: contains number

// Reassigning variables
let score = 0;
score = 10;                 // Reassignment
score = score + 5;          // Now 15
score += 3;                 // Shorthand: Now 18

// Swapping values
let x = 1, y = 2;
[x, y] = [y, x];            // x=2, y=1 (ES6 destructuring)

Scope Examples:

javascript

// Global scope
var globalVar = "I'm global";
let globalLet = "I'm also global but block-scoped";

function test() {
    // Function scope
    var functionVar = "I'm function scoped";
    let functionLet = "I'm block-scoped in function";
    
    if (true) {
        // Block scope
        var blockVar = "I'm hoisted to function";  // Still accessible
        let blockLet = "I'm truly block-scoped";   // Only in block
        console.log(blockLet);  // Works
    }
    
    console.log(blockVar);  // Works (problem with var!)
    // console.log(blockLet);  // ERROR: Not defined
}

// Hoisting example
console.log(hoistedVar);     // undefined (var is hoisted)
// console.log(hoistedLet);  // ERROR (let is not hoisted)
var hoistedVar = "I exist";
let hoistedLet = "I exist";

Data Types

1. Primitive Data Types (7 types):

javascript

// String
let text = "Hello World";
let single = 'Single quotes';
let backticks = `Template literal ${text}`;

// Number (both integer and floating)
let integer = 42;
let decimal = 3.14;
let negative = -15;
let scientific = 2.5e6;  // 2,500,000
let infinity = Infinity;
let nan = NaN;  // Not a Number (type is still number!)

// Boolean
let isTrue = true;
let isFalse = false;

// Undefined
let notAssigned;          // undefined
let explicitly = undefined;

// Null
let empty = null;        // Intentional absence

// Symbol (ES6)
let sym1 = Symbol("id");
let sym2 = Symbol("id");
console.log(sym1 === sym2);  // false (unique)

// BigInt (ES2020)
let bigNumber = 123456789012345678901234567890n;
let bigFromInt = BigInt(999999999999999);

2. Object Type (Non-primitive):

javascript

// Object literal
let person = {
    name: "John",
    age: 30,
    isStudent: false
};

// Array
let colors = ["red", "green", "blue"];

// Function
function greet(name) {
    return `Hello ${name}`;
}

// Date
let today = new Date();

// Regular Expression
let pattern = /javascript/i;

Type Checking:

javascript

// typeof operator
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" (historical bug!)
console.log(typeof Symbol());     // "symbol"
console.log(typeof 123n);         // "bigint"
console.log(typeof {});           // "object"
console.log(typeof []);           // "object"
console.log(typeof function(){}); // "function"

// Better type checking
console.log(Array.isArray([]));           // true
console.log([] instanceof Array);         // true
console.log(null === null);               // true
console.log(Number.isNaN(NaN));           // true

Type Conversion:

javascript

// Implicit conversion (type coercion)
console.log(8 * null);          // 0 (null → 0)
console.log("5" - 3);           // 2 (string → number)
console.log("5" + 3);           // "53" (number → string)
console.log("five" * 2);        // NaN
console.log(false == 0);        // true (false → 0)
console.log(null == undefined); // true

// Explicit conversion
let str = "123";
console.log(Number(str));       // 123
console.log(parseInt(str));     // 123
console.log(parseFloat("3.14")); // 3.14

let num = 456;
console.log(String(num));       // "456"
console.log(num.toString());    // "456"
console.log(num.toString(2));   // "111001000" (binary)

let bool = "hello";
console.log(Boolean(bool));     // true
console.log(!!bool);            // true (double NOT)

// Truthy/Falsy values
console.log(Boolean(""));       // false (empty string)
console.log(Boolean(0));        // false (zero)
console.log(Boolean(null));     // false
console.log(Boolean(undefined));// false
console.log(Boolean(NaN));      // false
console.log(Boolean(false));    // false
// Everything else is truthy!

Practical Examples:

javascript

// User registration form data
const user = {
    username: "john_doe",       // String
    age: 25,                    // Number
    isPremium: true,            // Boolean
    joinedDate: new Date(),     // Date object
    skills: ["JS", "HTML", "CSS"], // Array
    preferences: {              // Nested object
        theme: "dark",
        notifications: true
    },
    id: Symbol("user_id"),      // Symbol
    bigId: 9007199254740991n    // BigInt
};

// Shopping cart
const cart = {
    items: [
        { name: "Laptop", price: 999.99, quantity: 1 },  // Mixed types
        { name: "Mouse", price: 29.99, quantity: 2 }
    ],
    total: null,        // Will be calculated
    currency: "USD",
    isEmpty: false,
    calculateTotal: function() {  // Method
        this.total = this.items.reduce((sum, item) => 
            sum + (item.price * item.quantity), 0);
        return this.total;
    }
};

console.log(cart.calculateTotal());  // 1059.97

Complete Example: Interactive Webpage

html

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Basics Demo</title>
    <style>
        body { font-family: Arial; max-width: 600px; margin: 50px auto; }
        .demo-box { padding: 20px; border: 2px solid #ddd; margin: 20px 0; }
        button { margin: 5px; padding: 10px 15px; }
    </style>
</head>
<body>
    <h1>JavaScript Basics Playground</h1>
    
    <!-- Variable Demo -->
    <div class="demo-box">
        <h2>Variable Types Demo</h2>
        <p id="varOutput">Initial value</p>
        <button onclick="demoVariables()">Show Variables</button>
    </div>
    
    <!-- Data Type Demo -->
    <div class="demo-box">
        <h2>Data Types Demo</h2>
        <p id="typeOutput">Check console for type info</p>
        <button onclick="demoDataTypes()">Check Types</button>
    </div>
    
    <!-- Interactive Demo -->
    <div class="demo-box">
        <h2>Interactive Demo</h2>
        <input type="text" id="userInput" placeholder="Enter your name">
        <button onclick="greetUser()">Greet Me</button>
        <p id="greeting"></p>
    </div>

    <script>
        // Using let for variables that change
        let clickCount = 0;
        const MAX_CLICKS = 10;  // Using const for constants
        
        // Variable demo function
        function demoVariables() {
            let message = "Variables in action!";
            const PI = 3.14159;
            
            // Increment click count
            clickCount++;
            
            // Update display
            document.getElementById("varOutput").innerHTML = 
                `Message: ${message}<br>
                 PI: ${PI}<br>
                 Clicks: ${clickCount}/${MAX_CLICKS}<br>
                 Type of PI: ${typeof PI}`;
            
            // Log to console
            console.log(`Clicked ${clickCount} times`);
        }
        
        // Data type demo function
        function demoDataTypes() {
            const data = {
                string: "Hello World",
                number: 42,
                boolean: true,
                array: [1, 2, 3],
                object: { key: "value" },
                nullValue: null,
                undefinedValue: undefined,
                function: function() { return "I'm a function"; }
            };
            
            // Log all types to console
            console.group("Data Types Demo");
            for (let key in data) {
                console.log(`${key}:`, data[key], `(type: ${typeof data[key]})`);
            }
            console.groupEnd();
            
            // Show in UI
            document.getElementById("typeOutput").innerHTML = 
                `String: "${data.string}"<br>
                 Array length: ${data.array.length}<br>
                 Function result: ${data.function()}`;
        }
        
        // Interactive greeting function
        function greetUser() {
            const input = document.getElementById("userInput");
            const name = input.value.trim();
            
            // Input validation
            if (!name) {
                document.getElementById("greeting").innerHTML = 
                    `<span style="color: red;">Please enter your name!</span>`;
                return;
            }
            
            // Greet the user
            const greeting = `Hello, ${name}! Welcome to JavaScript.`;
            document.getElementById("greeting").innerHTML = greeting;
            
            // Clear input
            input.value = "";
            
            // Log to console
            console.log(`User greeted: ${name}`);
            console.log(`Name type: ${typeof name}`);
            console.log(`Name length: ${name.length}`);
        }
        
        // Initial console messages
        console.log("=== JavaScript Basics Demo ===");
        console.log("Page loaded successfully!");
        console.log("Try clicking the buttons and check the console.");
        console.log("Current click count:", clickCount);
        
        // Show available functions in console
        console.log("Available functions:", {
            demoVariables,
            demoDataTypes,
            greetUser
        });
    </script>
</body>
</html>

Best Practices

Variables:

javascript

// ✅ DO:
const API_URL = "https://api.example.com";  // Constants in UPPER_CASE
let userName = "John";                       // Use let for variables
const user = { name: "John" };               // Use const for objects/arrays

// ❌ DON'T:
var oldVariable = "avoid this";              // Don't use var
PI = 3.14;                                   // Don't assign without declaring
let 1stName = "John";                        // Don't start with number

Data Types:

javascript

// Use strict equality
console.log(5 == "5");    // true (loose) - Avoid
console.log(5 === "5");   // false (strict) - Use this

// Check for null/undefined
if (value === null || value === undefined) { }
// Or modern:
if (value == null) { }  // checks for both null and undefined

// Default values
const name = userInput || "Guest";           // Old way
const name = userInput ?? "Guest";           // Nullish coalescing (modern)

Console Debugging:

javascript

// Use console.group for related logs
console.group("User Login");
console.log("Attempting login...");
console.log("Username:", username);
console.groupEnd();

// Use descriptive variable names
const userList = [];  // Good
const arr = [];       // Bad

// Clean up console.log in production
if (process.env.NODE_ENV === "development") {
    console.log("Debug info");
}

Quick Reference

Declaration:

javascript

let variable = value;     // Mutable, block-scoped
const CONSTANT = value;   // Immutable reference, block-scoped
var oldWay = value;       // Avoid (function-scoped, hoisted)

Data Types:

javascript

typeof "text"    // "string"
typeof 42        // "number"  
typeof true      // "boolean"
typeof undefined // "undefined"
typeof null      // "object" (bug)
typeof {}        // "object"
typeof []        // "object"
typeof Symbol()  // "symbol"
typeof 123n      // "bigint"
typeof function(){} // "function"

Console Methods:

javascript

console.log(), .info(), .warn(), .error()
console.table(), .group(), .time(), .trace()
console.clear(), .assert(), .count()
debugger  // Breakpoint in dev tools

This foundation covers about 80% of JavaScript you'll use daily. Practice by opening browser dev tools and experimenting in the console!

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?