Author: Mateen

  • Transmission on Ubuntu

    So today I was looking for a Torrent client for my Ubuntu PC and I went through a lot of trouble and in the end I couldn’t really install any kind of client that would just simply work but the good news is that I have just found out that Ubuntu comes with its own Torrent client called Transmission.

  • How to create a React App and add Bootstrap to it

    Creating a React app with Bootstrap installed by default is straightforward! Here’s a step-by-step guide to do it in the Ubuntu terminal:


    Step 1: Install Node.js and npm

    React requires Node.js and npm (Node Package Manager). If you don’t already have them installed, run:

    sudo apt update
    sudo apt install nodejs npm

    Verify the installation:

    node -v
    npm -v

    Step 2: Create a React App

    Use create-react-app to set up a new React project. Run:

    npx create-react-app my-react-app

    Replace my-react-app with your desired project name.


    Step 3: Navigate to the Project Directory

    Move into the project folder:

    cd my-react-app

    Step 4: Install Bootstrap

    Install Bootstrap using npm:

    npm install bootstrap

    Step 5: Import Bootstrap in Your React App

    Open the src/index.js or src/App.js file and add the following line at the top to import Bootstrap:

    import 'bootstrap/dist/css/bootstrap.min.css';

    This imports the Bootstrap CSS file into your project.


    Step 6: Run the React App

    Start the development server to see your app in action:

    npm start

    Your app will open in the browser at http://localhost:3000.


    Step 7: Verify Bootstrap is Working

    To test if Bootstrap is working, replace the content of src/App.js with this simple Bootstrap-styled component:

    import React from 'react';
    import 'bootstrap/dist/css/bootstrap.min.css';
    
    function App() {
      return (
        <div className="container mt-5">
          <h1 className="text-primary">Hello, Bootstrap in React!</h1>
          <button className="btn btn-success">Click Me</button>
        </div>
      );
    }
    
    export default App;

    Save the file, and you should see a Bootstrap-styled heading and button in your browser.


    Optional: Install React-Bootstrap (Advanced)

    If you want to use React-Bootstrap (a library that provides Bootstrap components as React components), you can install it:

    npm install react-bootstrap

    Then, import components like this:

    import Button from 'react-bootstrap/Button';

    Summary

    1. Install Node.js and npm.
    2. Create a React app using create-react-app.
    3. Install Bootstrap with npm install bootstrap.
    4. Import Bootstrap’s CSS in index.js or App.js.
    5. Run the app with npm start.

    That’s it! You now have a React app with Bootstrap installed and ready to use. Let me know if you need further assistance! 🚀

  • 2025-02-10

    You know one of the things that I really should consider is that learning programming languages is just about staying around. Cuz it gets really boring or hard at times.

    I think learning to code is all about facing different kinds of problems and errors and trying to either bypass them or solve them.

    https://create-react-app.dev/docs/folder-structure

    What is the difference between props and states:

    In React, both props (properties) and state are essential for managing data and passing information between components. Props are used to pass data from a parent component to its children, ensuring a one-way data flow.234+3 They are immutable and cannot be modified within the child component.234+3 On the other hand, state allows components to manage and update their internal data, which can be modified within the component but not accessed from outside.234+3 State is mutable and can be updated using the setState method.234+3 Changes in props or state lead a component to re-render, and understanding when and how this happens is crucial for optimized React applications.456+1

    • Props: Used for passing data between components, typically from parent to child. They are immutable and cannot be changed within the component.234+3
    • State: Used for managing data within components. It allows components to change their output over time in response to user actions, network responses, or other events.234+3

    Understanding the differences between props and state is essential for building robust and scalable React applications.

    How to create a react app?

    npx create-react-app my-app

    How to run your app and see it live?

    npm start

    What is DOM?

    a programming interface for web documents that represents the page so that programs can change the document structure, style, and content.

    What are Classes in JS?

    A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside a constructor() method.
    https://www.w3schools.com/react/react_es6_classes.asp

    You can add your own methods in a class:

    How to create class inheritance?

    To create a class inheritance, use the extends keyword.

    A class created with a class inheritance inherits all the methods from another class:

    What is this?

    In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.

    How does React Display?

    The createRoot() function takes one argument, an HTML element.

    The purpose of the function is to define the HTML element where a React component should be displayed.

    The render() method is then called to define the React component that should be rendered.

    Display a paragraph inside an element with the id of “root”:

    const container = document.getElementById('root');
    const root = ReactDOM.createRoot(container);
    root.render(<p>Hello</p>);

    This will result in this:

    <body>
      <div id="root"></div>
    </body>

    Attribute class = className

    The class attribute is a much used attribute in HTML, but since JSX is rendered as JavaScript, and the class keyword is a reserved word in JavaScript, you are not allowed to use it in JSX.

    Use attribute className instead.

    How to use if in REACT

    const x = 5;
    
    const myElement = <h1>{(x) < 10 ? "Hello" : "Goodbye"}</h1>;
    

    Class Component

    A class component must include the extends React.Component statement. This statement creates an inheritance to React.Component, and gives your component access to React.Component’s functions.

    The component also requires a render() method, this method returns HTML.

    ExampleGet your own React.js Server

    Create a Class component called Car

    class Car extends React.Component {
      render() {
        return <h2>Hi, I am a Car!</h2>;
      }
    }

    Components can be passed as props, which stands for properties.

    Props are like function arguments, and you send them into the component as attributes.

    Props are arguments passed into React components.

    Props are passed to components via HTML attributes.

    There are two methods that we gonna use a lot:

    useEffect and useState

    useEffect runs with each refresh

  • 2025-02-07

    Here are A few algebraic equations I have taken from ChatGPT to solve using SymPy in Google Colab. Each equation is structured in a way that you can easily plug it into your existing code. ChatGPT has provided a variety of linear equations, quadratic equations, and some simple polynomial equations to give you a broad range of problems.

    You can access them both on Google Colab or Github:

    https://github.com/mateenkhadem/College-Algebra/blob/main/2025_02_07.ipynb

    https://colab.research.google.com/drive/19jKNZlaX-Xs85Qe__95nQVAW19YJVVT4?usp=sharing

  • Some Function Exercises from The Odin Project

    Let’s write some functions! Write these in the script tag of a skeleton HTML file. If you’ve forgotten how to set it up, review our instructions on how to run JavaScript code.

    For now, just write each function and test the output with console.log.

    Write a function called add7 that takes one number and returns that number + 7.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Some Function Exercises from The Odin Project</title>
    </head>
    <body>
        <script>
            function add7(number){
                return number + 7;
            }
        </script>
    </body>
    </html>

    Write a function called multiply that takes 2 numbers and returns their product.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Some Function Exercises from The Odin Project</title>
    </head>
    <body>
        <script>
            function multiply(number1, number2){
                return number1 * number2;
            }
        </script>
    </body>
    </html>

    Write a function called capitalize that takes a string and returns that string with only the first letter capitalized. Make sure that it can take strings that are lowercase, UPPERCASE or BoTh.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Some Function Exercises from The Odin Project</title>
    </head>
    <body>
        <script>
            function capitalize(string){
                return string[0].toUpperCase();
            }
        </script>
    </body>
    </html>

    Write a function called lastLetter that takes a string and returns the very last letter of that string:

    lastLetter("abcd") should return "d"

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Some Function Exercises from The Odin Project</title>
    </head>
    <body>
        <script>
            function add7(string){
                return string[string.length()-1];
            }
        </script>
    </body>
    </html>

    This is how you write a variable inside a string:

            console.log(`It's a tie! You both chose ${humanChoice}.`);

    This is how you write multiple conditions:

    else if (
            (humanChoice === "rock" && computerChoice === "scissors") ||
            (humanChoice === "paper" && computerChoice === "rock") ||
            (humanChoice === "scissors" && computerChoice === "paper")
        )
  • A Note on Conditional Operators

    There are a few things that I have learned today and I would like to mention them here so I can come back to them in the future.

    The Difference Between == And ===

    First of all, the difference between these two in JavaScript is that the first one compares whether the value of two things are the same but the second one also compares the datatype. So it’s like the second one is Value & Data Type (in a logical way).

    Comparison operators return a boolean value.

    Strings are Immutable!

    Meaning that when you use a string method, the method doesn’t change the string but rather it actually creates a new string.

    The boolean NOT operator is represented with an exclamation sign !

    Another Way to write conditions

    let accessAllowed = (age > 18) ? true : false;

  • 2025-02-05

    Basic Output & Interaction

    Console Logging a Message

    Exercise: Display a simple message in the browser console.

    Steps:

    Use the console logging function to send a string message.

    Open your browser’s developer tools to see the output.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    console.log("Hello! This is a message!");
    </script>
    </body>
    </html>

    Alert Pop-up

    Exercise: Show a pop-up message when the page loads.

    Steps:

    Use the function that triggers a window alert.

    Insert a text message inside the alert function.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    window.alert("Let's code together!");
    </script>
    </body>
    </html>

    Writing to the Document

    Exercise: Output text on the HTML web page dynamically.

    Steps:

    Choose the document helper that writes to the HTML.

    Output your chosen text on the page.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    document.write("This is a dynamic text");
    </script>
    </body>
    </html>

    Prompt for Input

    Exercise: Ask the user for their name and store the input.

    Steps:

    Use the prompt function to request input.

    Save the value in a variable.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let name = prompt("What is your name?: ");
    </script>
    </body>
    </html>

    Modify Inner HTML of an Element

    Exercise: Change the text of an element with a given ID.

    Steps:

    Access the element using its unique identifier.

    Change the element’s inner text to a new message.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <p id="paragraph">Before Change</p>
    <script>
    function changeParagraph() {
    document.getElementById("paragraph").innerHTML = "After Change";
    }
    </script>
    <button onclick="changeParagraph()">Change!</button>
    </body>
    </html>

    Variables & Declarations

    Declare Variables with Let and Var

    Exercise: Create two variables with let and var using different values.

    Steps:

    Use the let keyword to declare one variable.

    Use the var keyword to declare another variable, assigning a distinct value.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let a = "Value1";
    var b = "Value2";
    </script>
    </body>
    </html>

    Usage of Const

    Exercise: Create a constant and assign a string value that will not change.

    Steps:

    Declare a constant using the correct keyword.

    Ensure that its value cannot be changed later in the code.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    const text = "This is a string";
    </script>
    </body>
    </html>

    Variable Reassignment

    Exercise: Reassign a variable declared with let, then try with const and notice the difference.

    Steps:

    Change the value of a let variable.

    Attempt to change a const variable and observe the error or the behavior in your browser console.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let variable = "A variable";
    variable = "This and that";
    const text = "This is a string";
    text = "This won't work!";
    </script>
    </body>
    </html>

    Understanding Variable Scope

    Exercise: Explain the difference in scope between var and let by describing possible outcomes in different blocks.

    Steps:

    Create a variable with var inside a block (e.g., an if statement).

    Create a variable with let inside the same block.

    Describe in words or comments how they behave differently outside the block.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    a = 0;
    b = 0;
    if (a == b){
    let c = 1;
    var d = 2;
    }
    document.write(d);
    //It seems like var works in a global scope so it works outside the block too!
    </script>
    </body>
    </html>

    Explaining Data Types

    Exercise: List and explain the basic JavaScript data types.

    Steps:

    Write a comment or note that enumerates each type: String, Number, BigInt, Boolean, Undefined, Null, Symbol, and Object.

    Provide a short description of each type.


    Working with Arrays

    Create and Log an Array

    Exercise: Initialize an array with a few string elements and log it to the console.

    Steps:

    Use the array literal format to create an array.

    Output the array to the console using your logging function.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let theCities = ["Teheran", "Qom", "Isfahan"];
    console.log(theCities);
    </script>
    </body>
    </html>

    Appending Elements to an Array

    Exercise: Add a new element at the end of an array using the method you know.

    Steps:

    Identify the function that appends an element to an array.

    Use it to add a new string to the array.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let theCities = ["Teheran", "Qom", "Isfahan"];
    theCities.push("Tabriz");
    console.log(theCities);
    </script>
    </body>
    </html>

    Removing the Last Element of an Array

    Exercise: Remove the last element from an array.

    Steps:

    Use the appropriate array method to remove the last element.

    Optionally log the modified array to confirm removal.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let theCities = ["Teheran", "Qom", "Isfahan"];
    theCities.pop();
    console.log(theCities);
    </script>
    </body>
    </html>

    Working with Array Operations

    Exercise: Create an array with three items, then add one more using push and finally remove one using pop.

    Steps:

    Declare an array with three elements.

    Use the method to add another item.

    Use the removal method to remove the last added item.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let theCities = ["Teheran", "Qom", "Isfahan"];
    theCities.push("Mashhad");
    theCities.pop();
    console.log(theCities);
    </script>
    </body>
    </html>

    Swap Two Elements in an Array

    Exercise: Write steps to switch the positions of the first two elements in an array.

    Steps:

    Access the element at the first position.

    Access the element at the second position.

    Swap their positions logically, and then verify the new order by outputting the array.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let theCities = ["Teheran", "Qom", "Isfahan"];
    let a = theCities[0];
    let b = theCities[1];
    theCities = [b, a, "Isfahan"];
    console.log(theCities);
    </script>
    </body>
    </html>

    Understanding Arithmetic Operators

    Simple Math Operation

    Exercise: Use addition to combine two numbers.

    Steps:

    Identify two numeric variables or values.

    Use the addition operator to sum them.

    Log the result.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let a = 2;
    let b = 3; 
    console.log(a + b);
    </script>
    </body>
    </html>

    Subtraction Operation

    Exercise: Subtract one number from another and display the result.

    Steps:

    Select two numbers.

    Use the subtraction operator between them.

    View the outcome.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let a = 2;
    let b = 3; 
    console.log(a - b);
    </script>
    </body>
    </html>

    Multiplication and Division

    Exercise: Multiply two numbers and then divide the product by a given number.

    Steps:

    Multiply two selected numbers.

    Divide the multiplication result by another number.

    Log the final answer.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let a = 2;
    let b = 3; 
    let c = a * b;
    let d = c / 2;
    console.log(d);
    </script>
    </body>
    </html>

    Modulus Operation

    Exercise: Find the remainder of a division operation using modulus.

    Steps:

    Choose two numbers where one is not a multiple of the other.

    Apply the modulus operator and then log the remainder.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let a = 2;
    let b = 3; 
    let c = a * b;
    let d = c % 2;
    console.log(d);
    </script>
    </body>
    </html>

    Exponentiation Operation

    Exercise: Raise a number to a certain power using exponentiation.

    Steps:

    Select a base number and an exponent.

    Use the exponentiation operator to calculate the power.

    Log/display the result.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let a = 2;
    let b = 3; 
    console.log(a ** b);
    </script>
    </body>
    </html>

    Incrementing a Number

    Exercise: Increase a variable’s value by one using the increment operator.

    Steps:

    Start with a numeric variable.

    Increase it by one.

    Output the new number.

    Decrementing a Number

    Exercise: Decrease a variable’s value by one using the decrement operator.

    Steps:

    Use a numeric variable.

    Decrease it by one.

    Validate by logging the value.

    Chaining Arithmetic Operations

    Exercise: Combine addition, multiplication, and division in one expression.

    Steps:

    Decide on three numerical values.

    Form an expression mixing several arithmetic operators.

    Compute and log the final value.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let a = 2;
    let b = 4;
    let c = 6;
    let d = a + b * 3 / 6;
    console.log(d);
    </script>
    </body>
    </html>

    Arithmetic with Variables

    Exercise: Declare two number variables and perform several arithmetic operations between them.

    Steps:

    Create two variables with numbers.

    Add, subtract, multiply, and divide them in successive steps.

    Log each result separately.

    Calculate the Area of a Rectangle

    Exercise: Write down the steps to calculate the area from given length and width values.

    Steps:

    Define variables for length and width.

    Multiply them to get the area.

    Output the computed area.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    let height = 200;
    let width = 100;
    let area = height * width;
    console.log(area);
    </script>
    </body>
    </html>

  • 2025-02-04

    1. Display a Message with console.log()

    Task: Use console.log() to display a simple greeting message.

    Steps to Solve:

    Identify what message you want to show (e.g., “Hello, JavaScript!”).

    Use the console.log() method with your message as the argument.

    Run your code in the browser’s console or an editor to see the output.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    console.log("Hello, There!");
    </script>
    </body>
    </html>

    2. Alert a Message with window.alert()

    Task: Display an alert box with a custom greeting.

    Steps to Solve:

    Determine the text content for the alert.

    Call window.alert() or simply alert() with your text.

    Test the code in your browser to see the popup.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    window.alert("This is a message from the people of the earth");
    </script>
    </body>
    </html>

    3. Manipulate HTML Content using document.getElementById()

    Task: Change the text content of an HTML element by its id.

    Steps to Solve:

    Create an HTML element with a unique id attribute.

    Use document.getElementById() to access this element.

    Modify its innerHTML or textContent property.

    Refresh your page to observe the change.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <h1 id="heading1">This is the title before change</h1>
    <script>
    function change() {
    document.getElementById("heading1").innerHTML = "This is the title after change";
    }
    </script>
    <button onclick="change()">Click here to Change!</button>
    </body>
    </html>

    4. Understanding let Variable Declaration

    Task: Declare a variable using let and assign it a value.

    Steps to Solve:

    Choose a variable name that follows valid naming conventions.

    Use the let keyword to declare the variable.

    Assign an initial value.

    Optionally, display its value using console.log().

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <h1 id="heading1">This is the title before change</h1>
    <script>
    let a = 15;
    let b = 15;
    console.log(a + b);
    </script>
    </body>
    </html>

    5. Understanding var Variable Declaration

    Task: Declare a variable using var and assign it a value.

    Steps to Solve:

    Use the var keyword to declare a variable.

    Assign a value to the variable.

    Observe how var variables differ in scoping compared to let.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <h1 id="heading1">This is the title before change</h1>
    <script>
    var a = 15;
    var b = 15;
    console.log(a + b);
    </script>
    </body>
    </html>

    6. Using const for Constant Variables

    Task: Declare a constant using const and assign it a value.

    Steps to Solve:

    Use the const keyword to declare a variable that won’t change.

    Try to assign a new value later to see how JavaScript handles it.

    Log the result if needed.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <h1 id="heading1">This is the title before change</h1>
    <script>
    const variable = "value";
    variable = "secondvalue";
    console.log(variable);
    </script>
    </body>
    </html>

    7. Basic Arithmetic Operations (Addition)

    Task: Use basic arithmetic (addition) between two variables.

    Steps to Solve:

    Declare two numeric variables.

    Create a third variable to hold the sum of the first two.

    Use console.log() to display the result.

    Validate your solution by checking basic math.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <h1 id="heading1">This is the title before change</h1>
    <script>
    var firstNumber = 12;
    var secondNumber = 12;
    function sum() {
    let thirdNumber = firstNumber + secondNumber;
    window.alert(thirdNumber);
    }
    </script>
    <button onclick="sum()">Click on me!</button>
    </body>
    </html>

    8. Other Arithmetic Operations: Subtraction, Multiplication, Division, and Modulus

    Task: Perform subtraction, multiplication, division, and modulus operations.

    Steps to Solve:

    Declare two numerical variables.

    Compute subtraction, multiplication, division, and remainder using appropriate operators.

    Log each result.

    Ensure that division by zero is avoided.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <h1 id="heading1">This is the title before change</h1>
    <script>
    var firstNumber = 12;
    var secondNumber = 12;
    var sub = firstNumber - secondNumber;
    var mult = firstNumber * secondNumber;
    var div = firstNumber / secondNumber;
    console.log(div);
    </script>
    </body>
    </html>
  • 2025-02-03

    Exercise 1: Display “Hello, World!” with innerHTML

    Task:
    Create an HTML element (like a div or span) with an id, and using JavaScript, insert the text “Hello, World!” into it with innerHTML.

    Steps to Solve:

    In your HTML file, create an element with a unique id (for example, <div id="output"></div>).

    In your JavaScript, select the element using document.getElementById("output").

    Set the element’s innerHTML to “Hello, World!” (i.e., element.innerHTML = "Hello, World!";).

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    <div id="output"></div>
    document.getElementById("output").innerHTML = "Hello, World!";
    </script>
    </body>
    </html>

    Exercise 2: Write a Message Using document.write()

    Task:
    Use document.write() to display a line of text on the page when it loads.

    Steps to Solve:

    Open your JavaScript file or script tag.

    Call document.write("This is a message from document.write()!");

    Save and open your HTML file in a browser to see the output.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    document.write("This is a message from document.write()!");
    </script>
    </body>
    </html>

    Exercise 3: Alert a Greeting

    Task:
    Use window.alert() to display a greeting message when the page loads.

    Steps to Solve:

    Create a JavaScript file or add a <script> section in your HTML.

    Use window.alert("Welcome to learning JavaScript!");

    Refresh your page to see the alert popup.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    window.alert("Welcome to learning JavaScript!");
    </script>
    </body>
    </html>

    Exercise 4: Log a Message to the Browser Console

    Task:
    Use console.log() to print a message to the browser’s console.

    Steps to Solve:

    Open your script file or <script> tag in your HTML.

    Write console.log("Logging a test message"); in your code.

    Open your browser’s developer console (usually by pressing F12 or right-clicking and selecting “Inspect”) to see the message.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    console.log("Logging a test message");
    </script>
    </body>
    </html>

    Exercise 5: Display a Variable via innerHTML

    Task:
    Declare a variable containing your favorite quote and output it into an HTML element using innerHTML.

    Steps to Solve:

    Declare a variable, for example: var quote = "The only limit is your mind.";

    In your HTML, create an element with an id (e.g., <p id="quoteArea"></p>).

    Use document.getElementById("quoteArea").innerHTML = quote; in JavaScript.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <h2 id="h2"></h2>
    <script>
    var theQuote = "This is a Quote";
    document.getElementById("h2").innerHTML = theQuote;
    </script>
    </body>
    </html>

    Exercise 6: Concatenate Two Strings and Display Using document.write()

    Task:
    Write two different strings (e.g., first name and last name), concatenate them, and then use document.write() to display the full name.

    Steps to Solve:

    Declare two variables:
    var firstName = "John";
    var lastName = "Doe";

    Concatenate the strings (e.g., var fullName = firstName + " " + lastName;).

    Use document.write("Full Name: " + fullName); to display the result.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <h2 id="h2"></h2>
    <script>
    var stringOne = "Mateen";
    var stringTwo = "Khadem";
    document.write(stringOne + " " + stringTwo);
    </script>
    </body>
    </html>

    Exercise 7: Array of Favorite Movies Displayed via innerHTML

    Task:
    Create an array of your favorite movies and display them as a comma-separated list in an HTML element.

    Steps to Solve:

    Declare an array:
    var movies = ["Inception", "The Matrix", "Interstellar"];

    Join the array into a string using movies.join(", ").

    In the HTML, create an element with an id (e.g., <div id="moviesList"></div>).

    Set the element’s innerHTML to the joined string:
    document.getElementById("moviesList").innerHTML = movies.join(", ");


    Exercise 8: Display Array Length in the Console

    Task:
    Create an array and use console.log() to print the length (number of elements) of the array.

    Steps to Solve:

    Declare an array: var colors = ["red", "green", "blue"];

    Determine the length: var length = colors.length;

    Log the length: console.log("Array length is: " + length);

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    var ser = ["Ratched", "The Silo", "Severance"];
    var length = ser.length;
    console.log("The Array is " + length + " Series Long!");
    </script>
    </body>
    </html>

    Exercise 9: Change HTML Content on Click

    Task:
    Create a button in HTML that, when clicked, will change the content of a paragraph using innerHTML.

    Steps to Solve:

    In HTML, create a button (<button onclick="changeText()">Click Me</button>) and a paragraph (<p id="para">Original Text</p>).

    In your script, write the function:function changeText() { document.getElementById("para").innerHTML = "Text has been changed!"; }

    Test by clicking the button.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <p id="paragraph">This is Before Change</p>
    <script>
    function change(){
    document.getElementById("paragraph").innerHTML = "This is After Change";
    }
    </script>
    <button onclick="change()">Change!</button>
    </body>
    </html>

    Exercise 10: Alert Array Elements

    Task:
    Create an array of three fruits and use window.alert() to display the first fruit in the array.

    Steps to Solve:

    Declare an array: var fruits = ["Apple", "Banana", "Cherry"];

    Select the first element (fruits[0]).

    Use window.alert("The first fruit is " + fruits[0]);.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    var fruits = ["Orange", "Apple", "Banana"];
    window.alert(fruits[0]);
    </script>
    </body>
    </html>

    Exercise 11: Check if a Variable is Undefined

    Task:
    Declare a variable without assigning a value and use console.log() to print out a message saying whether the variable is undefined or not.

    Steps to Solve:

    Declare a variable: var myVar;

    Use an if-statement to check if it is undefined:if (typeof myVar === "undefined") { console.log("myVar is undefined"); } else { console.log("myVar is defined"); }

    Run it and check the console.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    var variable;
    if (typeof variable === "undefined"){
    console.log("variable is undefined");
    } else {
    console.log("variable is defined");
    }
    </script>
    </body>
    </html>

    Exercise 12: Simple Calculator with Prompt Input

    Task:
    Prompt the user to enter two numbers, add them together, and display the result via an alert.

    Steps to Solve:

    Use prompt() to get two numbers:var num1 = parseFloat(prompt("Enter first number:")); var num2 = parseFloat(prompt("Enter second number:"));

    Calculate the sum: var sum = num1 + num2;

    Then use window.alert("The sum is " + sum);.


    Exercise 13: Swap the Content of Two HTML Elements

    Task:
    Use two HTML elements (like two paragraphs), and write a function that swaps their innerHTML values when a button is clicked.

    Steps to Solve:

    Create two paragraphs with different ids (e.g., <p id="first">First</p> and <p id="second">Second</p>) and a button with an onclick event (e.g., <button onclick="swapContent()">Swap</button>).

    In JavaScript, write a function:function swapContent() { var first = document.getElementById("first").innerHTML; var second = document.getElementById("second").innerHTML; document.getElementById("first").innerHTML = second; document.getElementById("second").innerHTML = first; }

    Test by clicking the button.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <p id="p1">This is The First Paragraph</p>
    <p id="p2">This is The Second Paragraph</p>
    <script>
    function swapContent() {
    var first = document.getElementById("p1").innerHTML;
    var second = document.getElementById("p2").innerHTML;
    document.getElementById("p1").innerHTML = second;
    document.getElementById("p2").innerHTML = first;
    }
    </script>
    <button onclick="swapContent()">Swap</button>
    
    </body>
    </html>

    Exercise 14: Prompt User Name and Display a Personalized Message

    Task:
    Prompt the user to enter their name, then display a welcome congratulatory message on the page using innerHTML.

    Steps to Solve:

    Use prompt() to get the user’s name:
    var userName = prompt("Please enter your name:");

    Construct a message, for example: var message = "Welcome, " + userName + "!";

    Use innerHTML to display:
    document.getElementById("welcomeMessage").innerHTML = message;

    In HTML, add an element: <div id="welcomeMessage"></div>.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <h1 id="welcome"></h1>
    <script>
    var name = prompt("What is your name: ");
    document.getElementById("welcome").innerHTML = "Welcome to your own website " + name;
    </script>
    </body>
    </html>

    Exercise 15: Change Text Color Using JavaScript

    Task:
    Create a button that when pressed will change the color of the text in an HTML element using JavaScript.

    Steps to Solve:

    In your HTML file, add an element with text (e.g., <p id="colorText">Change my color!</p>) and a button (<button onclick="changeColor()">Change Color</button>).

    In your JavaScript, write a function:function changeColor() { document.getElementById("colorText").style.color = "blue"; }

    Click the button to see the text color update.


    Exercise 16: Create and Use Multiple Variables in an Alert

    Task:
    Declare three variables (name, age, and city), then combine them into a sentence and display the sentence using an alert.

    Steps to Solve:

    Declare the variables, for example:var name = "Bob"; var age = 30; var city = "New York";

    Construct a sentence:var message = name + " is " + age + " years old and lives in " + city + ".";

    Use window.alert(message); to display it.

    Test by opening your web page.

    <html>
    <head>
    <title>Exercise</title>
    </head>
    <body>
    <script>
    var name = prompt("What is your name? ");
    var age = prompt("How old are you? ");
    var city = prompt("Where are you from? ");
    window.alert("So you are " + name + ", you are " + age + " and from " + city);
    </script>
    </body>
    </html>
  • 2025-02-02

    Basic Variable Declaration and Logging

    Declare and Log a String Variable

    Create a variable named greeting and assign it the value "Hello, World!".

    Log greeting to the console.

    let greeting = "Hello, World!";
    console.log(greeting);

    Declare and Log a Number Variable

    Create a variable named year and assign it your birth year.

    Log year to the console.

    let year = 2001;
    console.log(year);

    Declare and Log a Boolean Variable

    Create a variable named isStudent and assign it true or false.

    Log isStudent to the console.

    Through testing and playing around with the code in LeetCode Playground I have found out something! That in order for the variables value to be boolean it needs to be started with a small case;

    Declare Multiple Variables

    Create three variables: firstNamelastName, and fullName.

    Assign your first and last names to firstName and lastName.

    Log firstName and lastName to the console.

    let firstName;
    let lastName;
    let fullName;
    firstName = "Mateen";
    lastName = "Khadem";
    fullName = firstName + " " + lastName;
    console.log(fullName);

    Update a Variable’s Value

    Create a variable named temperature and assign it 25.

    Change the value of temperature to 30.

    Log the updated temperature to the console.

    let temperature = 25;
    temperature = 30;
    console.log(temperature);

    Working with Arrays

    Create and Log an Array of Colors

    Create an array named colors containing three color names.

    Log the colors array to the console.

    let colors = ["Red", "Green", "Blue"];
    console.log(colors);

    Accessing Array Elements

    Using the colors array from the previous exercise, log the first color.

    Log the last color in the array.

    let colors = ["Red", "Green", "Blue"];
    console.log(colors[0]);

    Array Length

    Create an array named numbers with five numbers.

    Log the length of the numbers array to the console.

    Not that here length is a property not a function!

    Empty Array and Logging

    Create an empty array named emptyArray.

    Log emptyArray to the console.

    let emptyArray = [];
    console.log(emptyArray);

    Array with Mixed Data Types

    Create an array named mixed containing a string, number, and boolean.

    Log the mixed array to the console.

    let mixed = ["Coding", 192, true];
    console.log(mixed);

    Combining Variables and Arrays

    Assigning Variable to Array Element

    Create an array named pets with two pet names.

    Assign the first pet name to a variable called firstPet.

    Log firstPet to the console.

    let pets = ["Cat", "Dog"];
    let firstPet = pets[0];
    console.log(firstPet);

    Updating Array Elements

    Create an array named cities with three city names.

    Change the second city to a different name.

    Log the updated cities array.

    let cities = ["Tehran", "Qom", "New York"];
    cities[1] = "Isfahan";
    console.log(cities);

    Using Variables in Arrays

    Create variables item1item2, and item3 with any values.

    Create an array named items that includes item1item2, and item3.

    Log the items array.

    let item1 = "Food";
    let item2 = "Sleep";
    let item3 = "Medicine";
    let items = [item1, item2, item3];
    console.log(items);

    Array of Variables

    Create three variables: drink1drink2drink3 with your favorite beverages.

    Create an array named drinks containing these three variables.

    Log drinks to the console.

    let drink1 = "Chai";
    let drink2 = "Coca";
    let drink3 = "Water";
    let drinks = [drink1, drink2, drink3];
    console.log(drinks);

    Logging Specific Array Elements Using Variables

    Create an array named books with four book titles.

    Create a variable thirdBook that holds the third element of the books array.

    Log thirdBook to the console.

    let books = ["Bible", "Notes from Underground", "The Idiot", "Harry Potter"];
    console.log(books[2]);

    Basic Array Operations

    Adding Elements to an Array

    Create an array named languages with two programming languages.

    (Note: Since you’re only using let, you might simulate adding by reassigning.)

    Log the updated languages array.

    let languages = ["JavaScript", "Python"];
    languages[2] = "PHP";
    console.log(languages);

    Removing Elements from an Array

    Create an array named animals with three animal names.

    Remove the last animal by setting its index to undefined or another method.

    Log the updated animals array.

    let animals = ["Cat", "Dog", "Ant"];
    animals[2] = undefined;
    console.log(animals);

    This method doesn’t actually remove the last animal but the following method does.

    Replacing Array Elements

    Create an array named vehicles with three types of vehicles.

    Replace the second vehicle with a different one.

    Log the vehicles array.

    let vehicles = ["Car", "Bike", "Train"];
    vehicles[1] = "Airplane";
    console.log(vehicles);

    Accessing Array Elements by Index

    Create an array named letters with letters "A""B""C""D".

    Log the letter at index 2 to the console.

    let letters = ["A", "B", "C", "D"];
    console.log(letters[2]);

    Logging All Array Elements Individually

    Create an array named numbers with four numbers.

    Log each number separately using its index.

    let numbers = [1, 2, 3, 4];
    console.log(numbers[0]);
    console.log(nubmers[1]);
    console.log(nubmers[2]);
    console.log(nubmers[3]);

    Combining Multiple Variables and Arrays

    Creating a Profile Object with Variables (Simulated with Arrays)

    Create variables nameage, and city.

    Create an array named profile that includes these variables.

    Log the profile array.

    let name = "Mateen";
    let age = 23;
    let city = "Qom";
    let profile = [name, age, city];

    Swapping Variable Values Using an Array

    Create two variables a and b with different values.

    Use an array to swap their values.

    Log both a and b after swapping.

    let a = 23;
    let b = "Abc";
    let c = [23, "Abc"];
    a = c[1];
    b = c[0];
    console.log(a);
    console.log(b);

    Storing Student Names in an Array

    Create three variables student1student2student3 with student names.

    Create an array students containing these variables.

    Log the students array.

    let student1 = "Ali";
    let student2 = "Muhammad";
    let student3 = "Jason";
    let students = [student1, student2, student3];
    console.log(students);

    Calculating the Total Using Variables and an Array

    Create three number variables: num1num2num3.

    Create an array nums containing these variables.

    Log nums to the console.

    let num1 = 1;
    let num2 = 2;
    let num3 = 3;
    let nums = [num1, num2, num3]
    console.log(nums);

    Favorite Movies Array

    Create five variables movie1 to movie5 with your favorite movies.

    Create an array favoriteMovies containing these variables.

    Log favoriteMovies.

    let movie1 = "The Notebook";
    let movie2 = "The Social Network";
    let movie3 = "Harry Potter";
    let movie4 = "How I met Your Mother";
    let movie5 = "Whatever";
    let favoriteMovies = [movie1, movie2, movie3, movie4, movie5];
    console.log(favoriteMovies);

    Advanced Variable and Array Manipulations

    Nested Arrays (Arrays within Arrays)

    Create two arrays: breakfast with foods and lunch with foods.

    Create a main array meals that contains breakfast and lunch arrays.

    Log the meals array.

    let breakfast = ["Eggs", "Salami", "Tea"];
    let lunch = ["Pizza", "Burger"];
    let meals = [breakfast, lunch];
    console.log(meals);

    Accessing Elements in Nested Arrays

    Using the meals array from the previous exercise, log the first item of the lunch array.

    let breakfast = ["Eggs", "Salami", "Tea"];
    let lunch = ["Pizza", "Burger"];
    let meals = [breakfast, lunch];
    console.log(lunch[0]);

    Creating an Array of Arrays with Variables

    Create three arrays each containing different types of data (e.g., numbers, strings, booleans).

    Create a main array collection that holds these three arrays.

    Log collection to the console.

    let a = "Abc";
    let b = 2;
    let c = false;
    let collection = [a, b, c];
    console.log(collection);

    Assigning Array Elements to Separate Variables

    Create an array coordinates with three numbers representing x, y, z.

    Assign each element to separate variables xy, and z.

    Log xy, and z individually.

    let coordinates = [2, 23,234];
    let x = coordinates[0];
    let y = coordinates[1];
    let z = coordinates[2];
    console.log(x);
    console.log(y);
    console.log(z);

    Combining Strings from Variables and Arrays

    Create a variable greeting with the value "Hello".

    Create an array names with three different names.

    Log a greeting message for each name, e.g., "Hello, Alice!" using console.log.

    let greeting = "Hello";
    let names = ["Ali", "Muhammad", "Hussain"];
    console.log(greeting + ", " + names[0] + "!")
    console.log(greeting + ", " + names[1] + "!")
    console.log(greeting + ", " + names[2] + "!")