JavaScript Examples





Generated by AI, corrected by PeatSoft

  1. Hello World (Console)
    
    console.log("Hello, World!");
    

    This code prints "Hello, World!" to the console.

  2. Hello World (Browser)
    
    
    

    This code prints "Hello, World!" in the browser.

  3. Variables
    
    let name = "Alice";
    const age = 30;
    console.log(name + " is " + age + " years old.");
    

    This creates a variable `name` and a constant `age`, then logs a string to the console.

  4. Functions
    
    function add(a, b) {
        return a + b;
    }
    
    let sum = add(5, 3);
    console.log("The sum is: " + sum);
    

    This defines a function `add` that takes two parameters and returns their sum.

  5. Conditional Statements
    
    let score = 85;
    
    if (score >= 90) {
        console.log("Grade: A");
    } else if (score >= 80) {
        console.log("Grade: B");
    } else {
        console.log("Grade: C");
    }
    

    This code checks the `score` and logs the corresponding grade.

  6. Loops
    
    for (let i = 0; i < 5; i++) {
        console.log("Iteration number: " + i);
    }
    

    This loop iterates five times, printing the iteration number to the console.

  7. Arrays
    
    let fruits = ["apple", "banana", "cherry"];
    
    fruits.forEach(function(fruit) {
        console.log(fruit);
    });
    

    This code initializes an array of fruits and uses `forEach` to print each fruit.

  8. Objects
    
    let person = {
        name: "Bob",
        age: 25,
        greet: function() {
            console.log("Hello, my name is " + this.name);
        }
    };
    
    person.greet();
    

    This initializes an object `person` with properties and a method, then calls the `greet` method.

  9. Promises
    
    let fetchData = new Promise((resolve, reject) => {
        let success = true;
    
        if (success) {
            resolve("Data fetched successfully!");
        } else {
            reject("Error fetching data.");
        }
    });
    
    fetchData
        .then(response => console.log(response))
        .catch(error => console.log(error));
    

    This creates a simple promise that resolves or rejects based on a condition.

  10. Asynchronous Functions
    
    async function fetchData() {
        return "Data fetched!";
    }
    
    fetchData().then(response => console.log(response));
    

    This defines an asynchronous function that returns a string and uses `.then()` to log the result.