Exams > JavaScript

Exams > Exam 2: JavaScript

This exam will take place Wed, 04/08 during class.

Introduction

This is a paper-based 75-minute JavaScript exam. It focuses on reading code, reasoning about what code will do, and writing short JavaScript snippets by hand.

Name: ______________________________________

Guidelines

  • Read each prompt carefully.
  • For multiple-choice questions, clearly circle or mark your answer(s).
  • For short-answer questions, explain your reasoning clearly.
  • For code-writing questions, keep your solution short and focused.
  • Unless a prompt says otherwise, assume all selectors match real elements and the code runs in a browser without syntax errors.
Answer Key
1. Value: 4
   Data type: number

2. Value: 21
   Data type: number

3. Value: true
   Data type: boolean

4. tulip

5. x = 3
   y = 4
   z = 3

6. B -  true then false

7. Sample answer:
   `let` can be reassigned; `const` cannot be reassigned after it is created.
   For objects and arrays, a `const` variable cannot be reassigned to a new object/array,
   but the contents of that object or array can still change.

8. A - Hello, Guest then Hello, Alice

9. Correct definitions: A, B, C, and E

10. True statements: A, B, and D

11. D - { theme: 'light', compact: true, fontSize: 'large' }

12. Sample answer:
   GET = retrieve data
   POST = create/send new data
   PATCH = update part of a resource
   DELETE = remove a resource

13. Sample answer:
   A bearer token is a token that proves the user is authenticated.
   We put it in the Authorization header because that is the standard place to send
   authentication credentials with an HTTP request.

14. Sample answer:
   `fetch()` sends an HTTP request to a server or API.
   We usually use it with `async` / `await` because the request takes time and
   `fetch()` returns a Promise, so we need to wait for the response.

15.
   async function loadStudents() {
     const response = await fetch('/api/students');
     const students = await response.json();
     const html = students.map(student => `<p>${student.name}</p>`).join('');
     document.querySelector('#results').innerHTML = html;
   }

16.
   function courseToHTML(course) {
     return `
       <article class="course">
         <h3>${course.title}</h3>
         <p>Room: ${course.room}</p>
         <p>Credits: ${course.credits}</p>
         <p>Instructor: ${course.instructors[0].fullName}</p>
       </article>
     `;
   }

17.
   const csStudents = students.filter(student => student.major === "Computer Science");

18.
   function showMascot() {
     const mascot = document.querySelector('#mascot');
     const caption = document.querySelector('#caption');
     mascot.src = 'bulldog.png';
     mascot.alt = 'Bulldog mascot';
     caption.textContent = 'UNCA Bulldogs';
   }

   // You can either attach the event handler using JavaScript....
   document.querySelector('#show-mascot').addEventListener('click', showMascot);

   // ...or you can attach the event handler via HTML:
   <button id="show-mascot" onclick="showMascot()">Show Mascot</button>
  1. [4 pts] Consider the following:

    let myList = [[1, 8], [6, 9], [0, 7], [3, 2]];
    let result = myList.length;
    1. What is the VALUE stored in result? ______________________________
    2. What is the DATA TYPE of result? ______________________________
  1. [4 pts] Consider the following:

    let myList = [[1, 8], [6, 9], [0, 7], [3, 2]];
    let result = myList[2][1] * myList[3][0];
    1. What is the VALUE stored in result? ______________________________
    2. What is the DATA TYPE of result? ______________________________
  2. [4 pts] Consider the following:

    let a = 4;
    let b = 6;
    let c = false;
    let result = c || !(b <= a);
    1. What is the VALUE stored in result? ______________________________
    2. What is the DATA TYPE of result? ______________________________
  3. [4 pts] After the following code block runs, what prints to the screen?

    let a = false;
    let b = true;
    let c = true;
    let result = null;
    
    if (a || !c) {
        result = 'rose';
    } else if (!b || !a) {
        result = 'tulip';
    } else if (b) {
        result = 'daisy';
    } else {
        result = 'buttercup';
    }
    console.log(result);

  1. [8 pts] Consider the following code:

    function f1(a, b) {
        return b / a + 1;
    }
    
    function f2(a, b) {
        return (a - b) * 2;
    }
    
    let x = f1(2, 4);
    let y = f2(5, x);
    let z = f1(f2(2, 1), y);
    console.log(x, y, z);
    1. What is the value stored in x? ______________________________
    2. What is the value stored in y? ______________________________
    3. What is the value stored in z? ______________________________
  2. [4 pts] What will this code output? Circle the correct answer below:

    console.log(5 == '5');
    console.log(5 === '5');
    • true then true
    • true then false
    • false then true
    • false then false
  1. [4 pts] In your own words, explain the difference between let and const.

  2. [4 pts] What will this code output? Circle the correct answer below:

    function greet(name = 'Guest') {
      console.log('Hello, ' + name);
    }
    greet();
    greet('Alice');
    • Hello, Guest then Hello, Alice
    • Hello, undefined then Hello, Alice
    • Hello, Guest then Hello, Guest
    • Error
  3. [4 pts] Which of the following function definitions are written correctly? Circle all that apply.

    • function double(x) { return x * 2; }
    • const double = (x) => x * 2;
    • const double = x => x * 2;
    • const double = (x) => { x * 2; }
    • const double = (x) => { return x * 2; }
    • function = double(x) { return x * 2; }
  1. [4 pts] Circle the true statements:

    • myArray.map(...) returns a new transformed array.
    • myArray.filter(...) accepts a callback function as an argument that should return true or false.
    • myArray.forEach(...) returns a new transformed array.
    • myArray.toSorted(...) returns a sorted copy.
    • myArray.forEach(...) is most useful when you want a return value to store in a new variable.
  2. [4 pts] What will this code output? Circle the correct answer below:

    const settings = { theme: 'light', compact: false };
    const updated = { ...settings, compact: true, fontSize: 'large' };
    console.log(updated);
    • { theme: 'light' }
    • { compact: true, fontSize: 'large' }
    • { theme: 'light', compact: false, fontSize: 'large' }
    • { theme: 'light', compact: true, fontSize: 'large' }
    • Error
  3. [6 pts] Name 3 HTTP methods and describe their purpose.

  1. [6 pts] What is the purpose of a bearer token? Why do we put the bearer token in the Authorization header?

  2. [6 pts] In your own words, what does fetch() do, and why do we usually use it with async / await?

  1. [8 pts] Put these lines in the correct order to complete a function that fetches data from /api/students and renders each student’s name inside #results.

    • const html = students.map(student => `<p>${student.name}</p>`).join('');
    • async function loadStudents() {
    • document.querySelector('#results').innerHTML = html;
    • const response = await fetch('/api/students');
    • }
    • const students = await response.json();

    Assume this element already exists:

    <section id="results"></section>

    Write the correct function in the area below:

  1. [10 pts] Write a function named courseToHTML(course) that takes a course object (like the one shown below) and returns the following string.

    <article class="course">
      <h3>JavaScript</h3>
      <p>Room: RB 244</p>
      <p>Credits: 3</p>
      <p>Instructor: Walter Jones</p>
    </article>
    • Use a template literal.
    • Your function should work for any course object (not just a course on JavaScript)
    const course = {
      title: "JavaScript",
      room: "RB 244",
      credits: 3, 
      instructors: [{ fullName: 'Walter Jones' }]
    };

  1. [8 pts] Use filter(...) to create a new array containing only the students whose major is "Computer Science".

    const students = [
      { name: "Alice", age: 20, grade: 85, major: "Computer Science" },
      { name: "Bob", age: 21, grade: 92, major: "Mathematics" },
      { name: "Charlie", age: 19, grade: 78, major: "Computer Science" },
      { name: "Diana", age: 22, grade: 95, major: "Physics" },
      { name: "Eve", age: 20, grade: 88, major: "Computer Science" }
    ];

  1. [12 pts] Write a function and event handler so that when the user clicks a button labeled Show Mascot, your code updates the image and caption in the DOM.

    You may assume these elements already exist:

    <button id="show-mascot">Show Mascot</button>
    <img id="mascot" src="" alt="">
    <p id="caption"></p>

    When the button is clicked:

    1. set the image src to "bulldog.png"
    2. set the image alt to "Bulldog mascot"
    3. set the paragraph text to UNCA Bulldogs

    Expected result after the button is clicked:

    <button id="show-mascot">Show Mascot</button>
    <img id="mascot" src="bulldog.png" alt="Bulldog mascot">
    <p id="caption">UNCA Bulldogs</p>

    In the section below, write the JavaScript (and if necessary, also rewrite the HTML button code).

UNC Asheville Department of Computer Science