Skip to content

navya-javascript-control-structure-and-loops-assignments#543

Open
navya-1417 wants to merge 1 commit intoaptyInc:mainfrom
navya-1417:navya-control-structures-and-loops-assignments
Open

navya-javascript-control-structure-and-loops-assignments#543
navya-1417 wants to merge 1 commit intoaptyInc:mainfrom
navya-1417:navya-control-structures-and-loops-assignments

Conversation

@navya-1417
Copy link
Copy Markdown

@navya-1417 navya-1417 commented Nov 10, 2025

Terms and Conditions

  • I Accept losing points if my PR does not follow the best practices mentioned below, which will impact my overall performance in training

HTML Best Practices

  • File Naming Convention:

  • Follow consistent and descriptive naming (e.g., dashboard.html, user-profile.html).

  • Use lowercase letters and hyphens instead of spaces.

  • Page Title:

  • Ensure the <title> tag is descriptive and aligns with the page content.

  • Include meaningful keywords for SEO if applicable.

  • Semantic Markup:

  • Use appropriate tags like <header>, <footer>, <section>, <article> for better readability and accessibility.

  • Accessibility Standards:

  • Ensure the use of alt attributes for images and proper labels for form elements.

  • Use ARIA roles where necessary.

  • Validation:

  • Ensure the code passes HTML validation tools without errors or warnings.

  • Structure and Indentation:

  • Maintain consistent indentation and proper nesting of tags.

  • Attributes:

  • Ensure all required attributes (e.g., src, href, type, etc.) are correctly used and not left empty.

CSS Best Practices

  • File Organization:

  • Use modular CSS files if applicable (e.g., base.css, layout.css, theme.css).

  • Avoid inline styles unless absolutely necessary.

  • Naming Conventions:

  • Use meaningful class names following BEM or other conventions (e.g., block__element--modifier).

  • Code Reusability:

  • Avoid duplicate code; use classes or mixins for shared styles.

  • Responsive Design:

  • Ensure proper usage of media queries for mobile, tablet, and desktop views.

  • Performance Optimization:

  • Minimize the use of unnecessary CSS selectors.

  • Avoid overly specific selectors and ensure selectors are not overly deep (e.g., avoid #id .class1 .class2 p).

  • Consistency:

  • Follow consistent spacing, indentation, and use of units (rem/em vs. px).

  • Maintain a single coding style (e.g., always use double or single quotes consistently).

Javascript Best Practices

  • File Organization:

  • Ensure scripts are modular and logically separated into files if needed.

  • Avoid mixing inline JavaScript with HTML.

  • Logic Optimization:

  • Check for redundancy and ensure the code is optimized for performance.

  • Avoid unnecessary API calls or DOM manipulations.

  • Solution Approach:

  • Confirm that the code solves the given problem efficiently.

  • Consider scalability for future enhancements.

  • Readability:

  • Use clear variable and function names.

  • Add comments for complex logic or algorithms.

  • Error Handling:

  • Ensure proper error handling for API calls or user input validation.

  • Code Quality:

  • Check for potential bugs (e.g., missing await, mishandling of null/undefined values).

  • Avoid unnecessary console.log statements in production code.

  • Security:

  • Avoid hardcoding sensitive data.

  • Sanitize user input to prevent XSS and other vulnerabilities.

  • Best Practices:

  • Use const and let instead of var.

  • Follow ES6+ standards where applicable.

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello @navya-1417, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a comprehensive set of JavaScript assignments designed to reinforce fundamental programming concepts, specifically control structures and loops. It provides interactive web-based solutions for a variety of common programming tasks, ranging from basic arithmetic and conditional logic to more complex iterative processes and data manipulation. The changes are structured to offer clear, demonstrable examples of each concept, all accessible through a single, organized index page.

Highlights

  • Conditions Assignments: Six new assignments demonstrating JavaScript control structures have been added, including a grading system, leap year checker, basic calculator, largest number finder, odd/even checker, and a simple interest calculator. Each assignment features an interactive HTML interface.
  • Loops Assignments: Eight new assignments focusing on JavaScript loops have been implemented. These cover generating multiplication tables, summing numbers, calculating factorials, processing arrays for sum and average, counting character frequencies, finding prime numbers, generating pyramid patterns, and displaying ASCII art using 2D arrays.
  • Centralized Index Page: A main index.html file has been introduced to serve as a consolidated entry point for all the new assignments. It organizes them into collapsible sections using <details> tags, with each assignment embedded via an <iframe> for easy access and demonstration.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds several small projects for JavaScript control structures and loops assignments. The implementations are mostly correct and functional. However, there are several areas for improvement regarding web development best practices, code correctness, and security. My review includes feedback on:

  • HTML Best Practices: Moving inline JavaScript onclick handlers to separate script files, avoiding <br> tags for layout, and improving accessibility by linking <label>s to inputs.
  • Security: I found a critical Cross-Site Scripting (XSS) vulnerability due to improper use of innerHTML. I've also pointed out other instances where textContent should be preferred over innerHTML for safety.
  • Correctness & Robustness: Some scripts lack proper input validation, leading to incorrect behavior with empty or non-numeric inputs. I've also identified an incorrect loop usage (for...in on a string).
  • Code Quality & Efficiency: I've suggested using more modern or efficient JavaScript features where applicable, such as Math.max(), Array.prototype.reduce(), and using a mathematical formula instead of a loop for summation. I also noted a case of unnecessary code left over from debugging.

Overall, the assignments are well-attempted, and addressing the feedback will significantly improve the code quality and adherence to modern web standards.

Comment on lines +20 to +25
let display = "<h3>Character Frequency</h3>";
for (const ch in freq) {
display += `${ch}: ${freq[ch]}<br>`;
}

output.innerHTML = display;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

This code has a critical Cross-Site Scripting (XSS) vulnerability. You are using innerHTML to render content that includes characters from user input (ch). If a user enters a string like <img src=x onerror=alert(1)>, the malicious code will be executed. You must always sanitize user input or use textContent to render it safely.

Suggested change
let display = "<h3>Character Frequency</h3>";
for (const ch in freq) {
display += `${ch}: ${freq[ch]}<br>`;
}
output.innerHTML = display;
output.innerHTML = "<h3>Character Frequency</h3>";
for (const ch in freq) {
const line = document.createElement("div");
line.textContent = `${ch}: ${freq[ch]}`;
output.appendChild(line);
}

Comment on lines +11 to +17
let content = "";

for (let i = 1; i <= 10; i++) {
content += `${num} x ${i} = ${num * i}<br>`;
}

output.innerHTML = content;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using innerHTML to build the table can be a security risk if the input were to contain malicious content. Although Number() conversion mitigates this here, it's a best practice to avoid innerHTML. You can create and append DOM elements instead, which is safer.

Suggested change
let content = "";
for (let i = 1; i <= 10; i++) {
content += `${num} x ${i} = ${num * i}<br>`;
}
output.innerHTML = content;
output.innerHTML = ""; // Clear previous results
for (let i = 1; i <= 10; i++) {
const line = document.createElement("div");
line.textContent = `${num} x ${i} = ${num * i}`;
output.appendChild(line);
}

const freq = {};


for (let index in text) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

You should not use a for...in loop to iterate over a string. for...in iterates over the enumerable properties of an object. For strings and other iterables, you should use a for...of loop to correctly iterate over each value (character in this case).

Suggested change
for (let index in text) {
for (const char of text) {

Comment on lines +4 to +6
const marks = Number(document.getElementById("marksInput").value);
let grade;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The code doesn't validate if the input is a valid number. If a user enters text, Number() will produce NaN. Your current logic will then incorrectly assign grade 'F'. You should add a check for isNaN and display an error message to the user. Also, an empty input is converted to 0, which might not be the desired behavior.

Suggested change
const marks = Number(document.getElementById("marksInput").value);
let grade;
const marksValue = document.getElementById("marksInput").value;
if (marksValue.trim() === "") {
gradeBox.textContent = "Please enter your marks.";
return;
}
const marks = Number(marksValue);
if (isNaN(marks)) {
gradeBox.textContent = "Please enter a valid number.";
return;
}
let grade;

Comment on lines +4 to +6
const year = Number(document.getElementById("yearInput").value);

let msg;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Input validation is missing. If the input is empty, year becomes 0, which is incorrectly reported as a leap year. If the input is non-numeric, year becomes NaN, which is reported as 'Not a Leap Year' without an error message. You should validate the input to provide clear feedback to the user.

    const yearValue = document.getElementById("yearInput").value;
    if (yearValue.trim() === "") {
        resultBox.textContent = "Please enter a year.";
        return;
    }

    const year = Number(yearValue);
    if (isNaN(year)) {
        resultBox.textContent = "Please enter a valid year.";
        return;
    }

    let msg;

Comment on lines +21 to +26
let sum = 0;


for (const num of parts) {
sum += num;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instead of a for...of loop to calculate the sum, you can use the Array.prototype.reduce() method for a more concise and functional approach.

Suggested change
let sum = 0;
for (const num of parts) {
sum += num;
}
const sum = parts.reduce((accumulator, current) => accumulator + current, 0);


<br><br>

<button onclick="findGrade()">Get Grade</button>
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using onclick attributes in HTML is an outdated practice that mixes presentation with behavior. A better approach is to use addEventListener in your JavaScript file to keep your concerns separated. This makes the code more maintainable and easier to debug.

For example, you could change this line to <button id="findGradeBtn">Get Grade</button> and then in your index.js add:
document.getElementById('findGradeBtn').addEventListener('click', findGrade);

This feedback applies to all other buttons with onclick handlers in this pull request.

Suggested change
<button onclick="findGrade()">Get Grade</button>
<button id="findGradeBtn">Get Grade</button>

<label>Enter Marks:</label>
<input type="number" id="marksInput" />

<br><br>
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using <br> tags to create vertical space is not a good practice for structuring your page layout. Spacing and layout should be handled by CSS, for example by applying margin-bottom to the elements. This keeps your HTML semantic and your styling separate.

This feedback applies to all other instances of <br> tags used for spacing in this pull request.

Comment on lines +32 to +34
resultBox.innerHTML = primes.length
? `Prime Numbers: ${primes.join(", ")}`
: "No prime numbers found in this range.";
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using innerHTML here is not necessary. Since you are not rendering any HTML tags, it's safer and better practice to use textContent. This prevents accidental rendering of HTML and is a good security habit.

Suggested change
resultBox.innerHTML = primes.length
? `Prime Numbers: ${primes.join(", ")}`
: "No prime numbers found in this range.";
resultBox.textContent = primes.length
? `Prime Numbers: ${primes.join(", ")}`
: "No prime numbers found in this range.";

Comment on lines +13 to +19
for (const row of letters) {
let line = "";
for (const col of row) {
line += col + " ";
}
console.log(line);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This loop logs the output to the console. While this can be useful for debugging, it's not needed for the final functionality of displaying the name in the browser and should be removed from production code, as per the best practices mentioned in the pull request description.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant