Hacks Below

  • Data Type Hacks
  • DOM Hacks
  • Javascript Hacks
  • Input Hacks
  • Output Hacks

Data Type Hacks

%%javascript
// Object representing Vibha
let vibha = {    
    name: "Vibha",
    age: 15,
    currentClasses: ["AP Chem", "AP Calc", "AP Seminar", "AP CSP",],
    interests: ["reading", "baking"],
    favoriteColor: "Purple",
    favoriteArtists: ["Dua Lipa", "Sabrina Carpenter"]
};

// Print the entire object
console.log("Original object:", vibha);

// Manipulate arrays within the object
console.log("Object: mutating the key favoriteColor from purple to blue")
vibha.favoriteColor = "blue"

// Print the modified object and specific changed key
console.log("Modified favoriteColor:", vibha.favoriteColor);

// Perform mathematical operations
let yearsTill18 = 18 - vibha.age;
console.log("Years until Vibha turns 18:", yearsTill18);

let classCount = vibha.currentClasses.length;
console.log("Number of classes Vibha is taking:", classCount);

// Use typeof to determine the types of fields
console.log("Type of name:", typeof vibha.name);
console.log("Type of age:", typeof vibha.age);
console.log("Type of currentClasses:", typeof vibha.currentClasses);

<IPython.core.display.Javascript object>

DOM Hacks

%%html

<div style="background-color: #da95f5">
    <a id="aboutLink" href="/vibha_mandayam/about/">
        <button class="block"><b>About Page</b></button>
    </a>
    <p></p>
    <a id="indexLink" href="/vibha_mandayam/">
        <button class="block"><b>Index Page</b></button>
    </a>
    <p></p>
    <p style="color: black;">Use the buttons above to navigate to important pages on this site.</p>
    <p style="color: black;" id="switchedParagraph">Not Switched Yet!</p>
    
    <!-- Switch button placed outside the links -->
    <button class="block" id="switchLinks"><b>Switch!</b></button>
</div>

<script>
    const aboutLink = document.getElementById("aboutLink");
    const indexLink = document.getElementById("indexLink");
    const switchedText = document.getElementById("switchedParagraph");
    const switchButton = document.getElementById("switchLinks");

    const switchLinks = () => {
        // Swap the hrefs of the links
        const aboutHref = aboutLink.href;
        const indexHref = indexLink.href;

        aboutLink.href = indexHref;
        indexLink.href = aboutHref;

        // Change the text of the paragraph
        switchedText.textContent = "Switched!";
    };

    // Add an event listener to the "Switch!" button
    switchButton.addEventListener("click", switchLinks);
</script>

Use the buttons above to navigate to important pages on this site.

Not Switched Yet!

JavaScript Hacks

%%javascript
let a = 2;
let b = 7;

if (a > b) {
    console.log("a is greater");
} else if (b > a) {
    console.log("b is greater");
} else {
    console.log("both are equal");
}

let x = 10;
let y = 5;

// Addition
let addition = x + y;
console.log("Addition: " + addition);

// Subtraction
let subtraction = x - y;
console.log("Subtraction: " + subtraction);

// Multiplication
let multiplication = x * y;
console.log("Multiplication: " + multiplication);

// Division
let division = x / y;
console.log("Division: " + division);

// Modulo
let modulo = x % y;
console.log("Modulo: " + modulo);

// Exponentiation
let exponentiation = x ** y;
console.log("Exponentiation: " + exponentiation);

<IPython.core.display.Javascript object>

Input Hacks

%%html
<style>
    pre {
        background-color: #1e1e1e; /* Dark background for code blocks */
        color: #dcdcdc; /* Light text color */
        border: 1px solid #333; /* Border around code blocks */
        border-radius: 5px; /* Rounded corners */
        padding: 10px; /* Padding inside code blocks */
        overflow-x: auto; /* Horizontal scroll for long lines */
        white-space: pre-wrap; /* Wrap long lines */
    }
    code {
        color: #dcdcdc; /* Light text color for inline code */
    }
</style>

<style>
    /* Styles for the tool check title and overall layout */
    .container {
        background-color: #f9f9f9;
        padding: 20px;
        border-radius: 10px;
        border: 1px solid #ddd;
        width: 400px;
        margin: auto;
    }
    .title {
        color: black; /* Black text color for the title */
        font-size: 1.5em;
        margin-bottom: 15px;
    }
    .stats-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 10px;
    }
    .stats-table th, .stats-table td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: center;
    }
    .stats-table th {
        background-color: #4CAF50;
        color: white; /* White text color for table headers */
    }
    .stats-table td {
        background-color: #f4f4f4;
        color: black; /* Black text color for table data */
    }
    .input-container {
        margin-top: 20px;
    }
    .input-container label {
        font-weight: bold;
        color: black; /* Black text color for labels */
    }
    .input-container input {
        margin: 5px 0;
        color: black; /* Black text color for input fields */
        background-color: white; /* White background color for input fields */
        border: 1px solid #ddd; /* Light border for input fields */
        padding: 5px; /* Padding for input fields */
        border-radius: 4px; /* Rounded corners for input fields */
    }
</style>

<div class="container">
    <div class="title">Grade Calculator</div>
    
    <!-- Help Message -->
    <h3 style="color: black;">Input scores, press tab to add each new number.</h3>
    
    <!-- Stats Table -->
    <table class="stats-table">
        <tr>
            <th>Total</th>
            <th>Count</th>
            <th>Average</th>
        </tr>
        <tr>
            <td id="total">0.0</td>
            <td id="count">0.0</td>
            <td id="average">0.0</td>
        </tr>
    </table>

    <!-- Rows added using scores ID -->
    <div id="scores" class="input-container">
        <!-- JavaScript generated inputs -->
    </div>

    <script>
    // Executes on input event and calculates totals
    function calculator(event) {
        var key = event.key;
        // Check if the pressed key is the "Tab" key (key code 9) or "Enter" key (key code 13)
        if (key === "Tab" || key === "Enter") { 
            event.preventDefault(); // Prevent default behavior (tabbing to the next element)
       
            var array = document.getElementsByName('score'); // setup array of scores
            var total = 0;  // running total
            var count = 0;  // count of input elements with valid values

            for (var i = 0; i < array.length; i++) {  // iterate through array
                var value = array[i].value;
                if (parseFloat(value)) {
                    var parsedValue = parseFloat(value);
                    total += parsedValue;  // add to running total
                    count++;
                }
            }

            // update totals
            document.getElementById('total').innerHTML = total.toFixed(2); // show two decimals
            document.getElementById('count').innerHTML = count;

            if (count > 0) {
                document.getElementById('average').innerHTML = (total / count).toFixed(2);
            } else {
                document.getElementById('average').innerHTML = "0.0";
            }

            // adds newInputLine, only if all array values satisfy parseFloat 
            if (count === document.getElementsByName('score').length) {
                newInputLine(count); // make a new input line
            }
        }
    }

    // Creates a new input box
    function newInputLine(index) {

        // Add a label for each score element
        var title = document.createElement('label');
        title.htmlFor = index;
        title.innerHTML = (index + 1) + ". ";    
        document.getElementById("scores").appendChild(title); // add to HTML

        // Setup score element and attributes
        var score = document.createElement("input"); // input element
        score.id =  index;  // id of input element
        score.onkeydown = calculator // Each key triggers event (using function as a value)
        score.type = "number"; // Use text type to allow typing multiple characters
        score.name = "score";  // name is used to group all "score" elements (array)
        score.style.textAlign = "right";
        score.style.width = "5em";
        score.style.color = "black"; // Black text color for input fields
        score.style.backgroundColor = "white"; // White background color for input fields
        score.style.border = "1px solid #ddd"; // Light border for input fields
        score.style.padding = "5px"; // Padding for input fields
        score.style.borderRadius = "4px"; // Rounded corners for input fields
        document.getElementById("scores").appendChild(score);  // add to HTML

        // Create and add blank line after input box
        var br = document.createElement("br");  // line break element
        document.getElementById("scores").appendChild(br); // add to HTML

        // Set focus on the new input line
        document.getElementById(index).focus();
    }

    // Creates 1st input box on Window load
    newInputLine(0);

    </script>
</div>

Grade Calculator

Input scores, press tab to add each new number.

Total Count Average
0.0 0.0 0.0

Output

%%js

console.log("Classroom object");

/* class: Person
 * Description: A collection of Person data
*/
class Person {
  /* method: constructor
   * parameters: name, ghID - GitHub ID, classOf - Graduation Class 
   * description: returns object when "new Person()" is called with matching parameters
   * assignment: this.name, this.ghID, ... are properties retained in the returned object
   * default: this.role is a default property retained in object, it is set to "Student"
  */
  constructor(name, ghID, classOf, role="Student") {
    this.name = name;
    this.ghID = ghID;
    this.classOf = classOf;
    this.role = role;
  }

  /* method: setter
   * parameters: role - role in classroom
   * description: this.role is updated from default value to value contained in role parameter
  */
  setRole(role) {
    this.role = role;
  }
  
  /* method: getter
   * description: turns properties of object into JSON object
   * return value: JSON object
  */
  getJSON() {
    const obj = {type: typeof this, name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};
    const json = JSON.stringify(obj);
    return json;
  }

  /* method: logIT
   * description: this Person object is logged to console
  */
  logIt() {
    //Person Object
    console.info(this);
    // HTML output tag
    document.getElementById("output").textContent = this.getJSON();

    //Log to Jupter
    element.append("Person json <br>");
    element.append(this.getJSON() + "<br>"); 

    //alert(this.getJSON());
  }
    
}

/* class: Classroom
 * Description: A collection of Person objects
*/
class Classroom {
  /* method: constructor
   * parameters: teacher - a Person object, students - an array of Person objects
   * description: returns object when "new Classroom()" is called containing properties and methods of a Classroom
   * assignment: this.classroom, this.teacher, ... are properties retained in the returned object
  */
  constructor(teacher, students) {
    /* spread: this.classroom contains Teacher object and all Student objects
     * map: this.json contains of map of all persons to JSON
    */
    this.teacher = teacher;
    this.students = students;
    this.classroom = [teacher, ...students]; // ... spread option
    this.json = '{"classroom":[' + this.classroom.map(person => person.getJSON()) + ']}';
  }

  /* method: logIT
   * description: this Classroom object is logged to console
  */
  logIt() {
    //Classroom object
    console.log(this);

    // HTML output
    document.getElementById("data").textContent = this.json;
    document.getElementById("output").textContent = this.json;

    //Classroom json
    element.append("Classroom object in JSON: ");
    element.append(this.json);

    //alert(this.json);
  }
}

/* function: constructCompSciClassroom
 * Description: Create data for Classroom and Person objects
 * Returns: A Classroom Object
*/
function constructCompSciClassroom() {
    // define a Teacher object
    const teacher = new Person("Mr M", "jm1021", 1977, "Teacher");  // optional 4th parameter

    // define a student Array of Person objects
    const students = [ 
        new Person("Risha", "blackstar3092", 2027),
        new Person("Vibha", "vibha1019", 2027),
        new Person("Ava", "ava-dn", 2025),
    ];

    // make a CompSci classroom from formerly defined teacher and student objects
    return new Classroom(teacher, students);  // returns object
}

// assigns compsci to the object returned by "constructCompSciClassroom()" function
const compsci = constructCompSciClassroom();
// output of Objects and JSON in CompSci classroom
compsci.logIt();


console.log("Classroom Web Page");

// extract JSON text from output element in HTML page
const jsonText = document.getElementById("data").innerHTML;

// convert JSON text to a JavaScript Object to process
const classroom = JSON.parse(jsonText).classroom;
console.log(classroom);

// make an HTML Out format for pretty display
/* Template literals (`), can make HTML generation more concise;
 * the map functions generates row strings and the join method combines them;
 * this replaces longer and ugly for loop and string concatenation.
*/
const htmlOut = `
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>GitHub ID</th>
                <th>Class Of</th>
                <th>Role</th>
            </tr>
        </thead>
        <tbody>
            ${classroom.map(row => `
                <tr>
                    <td>${row.name}</td>
                    <td>${row.ghID}</td>
                    <td>${row.classOf}</td>
                    <td>${row.role}</td>
                </tr>
            `).join('')}
        </tbody>
    </table>
`;

// assign/set htmlOut to output element in HTML page
document.getElementById("output").innerHTML = htmlOut;

// show raw HTML
console.log(htmlOut);
element.append(htmlOut);

<IPython.core.display.Javascript object>

Using console.log() for Debugging

console.log() is a simple but effective way to debug code by helping you track the flow of execution and inspect values of variables at different points. Here’s how it can help find errors:

1. Check variable values

By logging variables, you can check if they hold the expected values at different stages. If they don’t, you can trace where things go wrong.

let result = calculate(5, 10);
console.log(result); // Check what `result` holds

2. Trace execution flow

Adding console.log() statements at key points in your code helps you verify which parts are being executed and in what order, which is useful for identifying logic errors.

console.log("Before calling function");
myFunction();
console.log("After calling function");

3. Identify undefined or null values

If a variable is undefined or null, logging it will highlight potential issues such as missing data or improper initialization.

console.log(someVar); // If `someVar` is `undefined`, you'll catch it here

4. Debug loops and conditionals

By placing console.log() inside loops or conditionals, you can check whether they are working as expected and how often they run.

for (let i = 0; i < 5; i++) {
  console.log(i); // Check each iteration value
}