
--- PDF page 18 ---
U N I T 1 · F R O N T- E N D D E V E L O P M E N T




       01
       HTML, CSS, JavaScript & Git
       How a browser talks to a server, how a page is built (HTML), dressed (CSS) and brought to
       life (JavaScript), how JavaScript waits for slow work (callbacks, Promises, async/await),
       and how a team saves and merges its code (Git and GitHub). Every past-paper question
       from this unit is answered in full, in the exact shape you should write it.

          103 marks asked in 3 papers          15 PYQs solved (11 answer blocks)         4 gaps filled       10 drills




   1.1 How the web works                                             1.13 JavaScript basics
   1.2 How a browser renders a page                                  1.14 ES6+, arrays, objects, modules
   1.3 HTML from zero                                                1.15 Every type of JS function
   1.4 Full page layout (PYQ)                                        1.16 Callbacks to Promises (PYQ)
   1.5 Three ways to add CSS (PYQ)                                   1.17 async/await, package delivery (PYQ)
   1.6 Selectors, cascade, specificity                               1.18 DOM, events, delegation
   1.7 Box model, units, colour                                      1.19 Form validation with JS (PYQ)
   1.8 Display and position                                          1.20 Git from zero (PYQ)
   1.9 Flexbox                                                       1.21 Branches, rebase, cherry-pick, tags (PYQ)
   1.10 Grid, and Grid vs Flexbox                                    1.22 GitHub: remotes and PRs (PYQ)
   1.11 Responsive and modern CSS                                    1.23 Likely questions for 2026
   1.12 Bootstrap and Tailwind                                       1.24 Last-minute recap



▸ Where the Unit 1 marks have been

                                                                    Re-Exam          Final 2024-
 Topic                                                                                                   Final 2025-26    Priority
                                                                    2023-24          25

 Git & GitHub (what/why, branches, tags, merge vs rebase,           —                —                   22 (Q1e, Q6 A-     🔥 HIGH
 cherry-pick, remote/clone)                                                                              B-C)

 Promises / callbacks / async-await                                 5 + part of 10   5 + 10 + part       —                  🔥 HIGH
                                                                                     of 10

 Types of JavaScript functions (+ callback / async)                 10               10                  —                  🔥 HIGH
 HTML form + JavaScript validation                                  10               10                  —                  🔥 HIGH
 Types of CSS (inline / internal / external)                        5                5                   —                  MEDIUM


 HTML page layout from a picture                                    10               —                   —                  MEDIUM

--- PDF page 19 ---
Re-Exam            Final 2024-
 Topic                                                                                                        Final 2025-26        Priority
                                                                         2023-24            25

 Frontend vs backend                                                     —                  —                 1                     LOW




  ✍️ WHAT THE TREND TELLS YOU
  The two older papers were code-heavy (write the form, convert the callbacks, write the CSS). The newest
  paper (Dec 2025) dropped HTML/CSS/JS code completely and spent 22 marks on Git concepts. Prepare
  both: memorise the four code templates in this chapter (layout page, validation form, Promise/async con‐
  version, three CSS types) and be able to write a page of clear theory on Git.




     1.1 How the web works: client and server
📚 Sources: Unit 1 Notes §2        LEC 1 (PDF) slides 7–11     One-Shot Revision · Unit 1    Complete Revision deck · U1 slide 4


  🧠 START FROM ZERO
  A web application is a conversation between two computers. The client (usually your browser) asks for
  something. The server (a computer that stores the application and its data) answers. The question is called
  a request, the answer a response, and the language they both speak is HTTP (HyperText Transfer
  Protocol), or its encrypted form HTTPS.


  💡 THINK OF IT LIKE
  A restaurant. You (client) give your order to the waiter, the order travels to the kitchen (server), the kitchen
  cooks and sends the dish back. You never walk into the kitchen; you only see what comes out. The road
  the waiter walks is the internet.




                                           Request                                         Reroute
                  Client                                          Internet                                          Server
                browser / app                                    DNS + routers                                    app + database
                                          Response                                         Response




The client–server model as drawn in LEC 1: the request is rerouted through the internet to the right server and the response comes back the same
                                                                     way.



▸ What happens when you hit a URL

 1        You type a URL such as https://www.server.com/api/orders.json and press Enter.

 2        DNS lookup. The browser asks DNS (the internet's phone book) for the IP address of
           www.server.com .

--- PDF page 20 ---
3        Connection. The browser opens a connection to that IP (for https , an encrypted TLS connection).

 4        HTTP request sent. Method + URL + headers (and a body for POST/PUT).

 5        Server works. It routes the request to the right code (in Unit 2 this is Django's urls.py → view), may
          query a database, and builds a response.

 6        HTTP response returned: a status code, headers and a body (HTML, JSON, an image…).

 7        Browser renders the HTML (section 1.2) and fires more requests for every CSS file, script and image
          the page needs.


▸ Anatomy of a request
This is the exact example from LEC 1. Learn to point at each part.

           HTTP request (LEC 1 example)


  GET https://www.server.com/api/orders.json?created_at=2022-01-18T19:08:48+00:00&limit=10 HTTP/1.1
  Host: www.server.com
  authorization: Basic Yjw2WU57IogGNiZzgxODhjZwBkOWIwZjdjZTY=



  Part                  In the example         What it means

  Method                GET                    The action: GET reads, POST creates, PUT/PATCH update, DELETE
                                               removes.

  Scheme                https                  The protocol; almost always https in production.

  Server (host)         www.server.com         Which machine is being contacted.

  Path                  /api/orders.json       Which resource on that server.

  Query string          ?                      Extra key=value pairs after ? , joined by & ; used for filtering, sorting,
                        created_at=...&lim‐    pagination.
                        it=10

  Headers               Host , authoriza‐      Metadata that travels outside the URL: who is asking, what format they
                        tion                   accept, tokens, cookies.

  Body (not in a        —                      Data sent to the server, e.g. JSON or form fields in a POST.
  GET)



  🔑 MEMORY HOOK
   Two requests to the exact same URL can behave completely differently , because authorization travels in
  the headers, not in the URL. (Unit 1 Notes §2.2.)


           A POST request carries a body

--- PDF page 21 ---
POST /api/orders HTTP/1.1
  Host: www.server.com
  Content-Type: application/json
  Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...


  {"sku": "A1-103/0", "qty": 2}




▸ Anatomy of a response
A response mirrors a request (headers + body) and adds the one thing a request never has: a status code and
description such as 200 OK . The body is very often JSON, a nested structure of keys and values that both
browser and server understand.

            HTTP response (LEC 1 example)


  HTTP/1.1 200 OK                                      <- status code + description
  Content-Type: application/json                       <- headers
  Date: Thu, 20 Jan 2022 14:13:05 GMT
  Server: Apache
  X-Correlation-Id: 0a491944-9e95-4ed9-85d9-d3f430ce5d59


  {                                                    <- body (JSON)
      "yourOrderReference": "PO16262999",
      "ourOrderNumber": "ORD000000031671",
      "lineItems": [
          { "sku": "A1-103/0", "description": "A desk lamp", "qty": 2 },
          { "sku": "A1-401/0", "description": "Some Bulbs",   "qty": 1 }
      ]
  }

--- PDF page 22 ---
▸ HTTP methods and status codes

  METHODS (VERBS)                                                        STATUS CODE FAMILIES

    Method         CRUD              Example                                Code             Meaning

    GET            Read              Load a product page                    1xx              Informational (rare)

    POST           Create            Submit a sign-up form                  200 / 201 /      OK / Created / No Content
                                                                            204
    PUT            Replace           Overwrite a whole profile
                                                                            301 / 302 /      Moved permanently / Found (redirect) /
    PATCH          Update part       Change only the email
                                                                            304              Not modified (use cache)
    DELETE         Delete            Remove an order
                                                                            400 / 401 /      Bad request / Not logged in / Forbidden /
                                                                            403 / 404        Not found
  An HTML <form> can only send GET or POST. GET puts
  data in the URL (visible, bookmarkable); POST puts it in the              500 / 502 /      Server crashed / Bad gateway / Service

  body (use it for passwords and anything that changes data).               503              unavailable


                                                                         Hook: 2xx "here you go", 3xx "go over there", 4xx "you
                                                                         made a mistake", 5xx "we made a mistake".



▸ Frontend vs backend

  Aspect                Frontend (client side)                                       Backend (server side)

  Runs where            In the user's browser                                        On the server

  Job                   What the user sees and touches: layout, styling, but‐        Business logic, database, authentication, secu‐
                        tons, forms, interactivity                                   rity, APIs that send data

  Technologies          HTML, CSS, JavaScript, Bootstrap/Tailwind, React             Python + Django / DRF, Node.js, PostgreSQL,
                                                                                     MongoDB

  In this course        Unit 1 and Unit 4 (React)                                    Unit 2 (Django), Unit 3 (databases)

  Main                  UI/UX, responsiveness, accessibility, speed of               Correctness, data integrity, scalability, security
  concerns              rendering


A full-stack developer works on both. The two halves meet at the HTTP request/response: the frontend sends
requests, the backend answers with HTML or JSON.


   PYQ       Final 2025-26 · Q1(f)   ★ LATEST                                                                                     1M


  What is the difference between frontend and backend in web development? Give one example tech‐
  nology for each.

   ✓    MODEL ANSWER — WRITE THIS

  Frontend is the client side of a web application: the part that runs in the user's browser and that the user
  sees and interacts with (layout, styling, forms, buttons). Example technology: React (or
  HTML/CSS/JavaScript).

--- PDF page 23 ---
Backend is the server side: it runs on the server, handles business logic, authentication and the database,
  and sends data (HTML/JSON) to the frontend. Example technology: Django (Python), with a database such
  as PostgreSQL.

  🎯 Marking scheme guess: 0.5 M correct distinction (client/browser vs server/logic+data) · 0.5 M one valid example each


     1.2 How a browser renders a page
📚 Sources: Unit 1 Notes §3       LEC 1 (PDF) slide 13    LEC 2 (CSS) slide 4    One-Shot Revision · Unit 1

 Complete Revision deck · U1 slide 5


The response for a page is just text. The browser turns that text into pixels through a fixed pipeline. Knowing this
pipeline explains several "rules" you will be asked about: why CSS goes in the <head> , why scripts go at the
end of <body> , and why you animate transform rather than width .

         1 Fetch              2 Parse HTML                3 Process CSS                4 Render tree                      5 Layout, Paint
        files arrive
                        →              DOM
                                                  →            CSSOM
                                                                               →          visible only
                                                                                                                 →          boxes, pixels




 1        Fetching. The browser sends the request; the server responds with the HTML, and the browser re‐
          quests the CSS, JS and images it finds inside.

 2        Parsing HTML → DOM. The HTML is read top to bottom and turned into the DOM (Document Object
          Model): a tree of objects that mirrors the nesting of the tags. JavaScript later reads and changes this
          tree.

 3        Processing CSS → CSSOM. Every stylesheet is parsed into the CSSOM (CSS Object Model): a sec‐
          ond tree recording which styles apply to which elements.

 4        Render tree. DOM + CSSOM are combined. Only visible elements are kept (no <head> , no
           display: none elements), each with its computed styles.


 5        Layout, then paint. Layout (also called reflow) calculates the exact position and size of every box;
          painting draws the pixels to the screen.


                                                                                                          html
         <html>
         <head><title>Shop</title></head>
         <body>
                                                                      →
                                                                                     head                                    body
         <h1>Sale</h1>
         <p>Up to <b>50%</b> off</p>
         </body>                                                                      title                          h1               p

         </html>
                                                                                                                                      b


              A tiny page and the DOM tree the browser builds from it: each tag becomes a node, nesting becomes parent → child.

--- PDF page 24 ---
▸ The practical rules this pipeline explains

  Rule                                     Why (pipeline reason)

  Link stylesheets in the <head>           CSS is render-blocking: nothing is painted until the CSSOM is ready, so load it first.

  Put <script> at the end of               A normal script stops HTML parsing while it downloads and runs, delaying first paint;
   <body> (or use defer )                  and a script that runs too early finds elements that are not in the DOM yet.

  Animate transform and                    Changing width , top , margin re-runs layout (reflow, expensive); changing
   opacity                                  color only repaints (cheaper); transform/opacity skip layout entirely.


 Script tag                                   Download          Runs when                           Use for

  <script src="a.js"> in head                 Blocks            Immediately                         Avoid
                                              parsing

  <script defer src="a.js">                   In parallel       After HTML is parsed, in order      Your own page scripts (LEC 3 slide
                                                                                                    27)

  <script async src="a.js">                   In parallel       As soon as downloaded, any          Independent scripts (analytics)
                                                                order

  <script src="a.js"> at end of               After content     After the content above it exists   The simple classroom way
 body



  ⚠️ COMMON MISTAKE
  The DOM is not the same as your HTML file. The browser repairs bad HTML while building it, and
  JavaScript can add or remove nodes later. DevTools → Elements shows the live DOM, not the source.


  ✍️ HOW TO WRITE THIS IN THE EXAM
  "Explain how a browser renders a web page" (5 M): draw the 5-box flow → one line per stage (DOM,
  CSSOM, render tree, layout, paint) → finish with the two consequences (CSS render-blocking, scripts at
  end / defer ) and reflow vs repaint.




    1.3 HTML from zero
📚 Sources: Unit 1 Notes §4       Lab 1 Manual (HTML) §1–8     LEC 1 (PDF) slides 14–15    One-Shot Revision · Unit 1

 Complete Revision deck · U1 slide 6


  🧠 START FROM ZERO
  HTML (HyperText Markup Language) is not a programming language; it is a markup language. You wrap
  pieces of content in tags to say what each piece is: a heading, a paragraph, a link, a form. HTML gives the
  page its structure and meaning; CSS will give it looks and JavaScript behaviour.

--- PDF page 25 ---
▸ Anatomy of an element

           one element


  <a href="https://example.com" target="_blank">Visit Example</a>
  <!-- ^ opening tag           ^ attributes (name="value")                  ^ content   ^ closing tag -->



Void (self-closing) elements have no content and no closing tag: <br> , <hr> , <img> , <input> , <meta> ,
 <link> . Comments are written <!-- like this --> .


▸ The skeleton of every page

           index.html — minimal HTML5 page


  <!DOCTYPE html>                                   <!-- use modern HTML5 rules -->
  <html lang="en">                                  <!-- the single root element -->
  <head>                                            <!-- invisible info for browser & search engines -->
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>My Portfolio</title>                    <!-- text in the browser tab -->
     <link rel="stylesheet" href="style.css">
  </head>
  <body>                                            <!-- everything the user sees -->
     <h1>Welcome to HTML!</h1>
     <p>This is a paragraph.</p>
     <img src="logo.png" alt="Logo">
     <script src="app.js"></script>                 <!-- scripts at the END of body -->
  </body>
  </html>



 Part                   Role

  <!DOCTYPE             Declares the document as HTML5 so the browser uses standards mode.
 html>

  <html>                Root element wrapping the whole page; lang="en" helps screen readers and search engines.

  <head>                Metadata: <meta charset> , viewport (needed for responsive design), <title> , <link> to CSS,
                         <style> , <script> .

  <body>                All visible content.



▸ Text, links and lists

 Tag              Purpose                                                   Tag          Purpose

  <h1> –          Headings (h1 = most important, one per page)               <p>         Paragraph
  <h6>

  <strong         Important text (bold, semantic)                            <b>         Bold, visual only
 >

--- PDF page 26 ---
Tag              Purpose                                           Tag         Purpose

  <em>            Emphasis (italic, semantic)                       <i>         Italic, visual only

  <br> /          Line break / horizontal rule                      <span>      Generic inline container
  <hr>

  <mark> ,        Highlight, fine print                             <blockquo   Long / short quotation
  <small>                                                           te> , <q>

  <code>          Inline code                                       <pre>       Preformatted text (keeps spaces)

  <a>             Hyperlink ( href , target="_blank" ,              <ul>        Bulleted / numbered list and its items ( ol
                   rel="noopener noreferrer" , download ,           <ol>        takes start , reversed , type )
                   title )                                          <li>

  <dl>            Description list: term + definition               <nav>       A block of navigation links
  <dt>
  <dd>


           links, lists, images and media


  <a href="https://example.com" target="_blank" rel="noopener noreferrer">Visit Example</a>
  <a href="about.html">About</a>                          <!-- relative path: same site -->
  <a href="#contact">Jump to contact</a>                  <!-- goes to the element with id="contact" -->
  <a href="mailto:hr@abc.com">Email HR</a>


  <ol type="1" start="3">
     <li>Third step</li>
     <li>Fourth step
        <ul><li>nested bullet</li></ul>
     </li>
  </ol>


  <!-- images and media -->
  <img src="cat.jpg" alt="A sleeping orange cat" width="400" loading="lazy">
  <figure>
     <img src="chart.png" alt="Sales by month">
     <figcaption>Fig 1. Monthly sales</figcaption>
  </figure>


  <video controls width="480" poster="thumb.jpg">
     <source src="intro.mp4" type="video/mp4">
     Your browser does not support video.
  </video>
  <audio controls src="song.mp3"></audio>



 alt text is always required: screen readers read it and it shows if the image fails. loading="lazy" delays off-
screen images. Video/audio attributes: controls , autoplay , loop , muted , poster .

--- PDF page 27 ---
▸ Tables

           table with header, body, footer and colspan


  <table border="1">
     <caption>Semester V marks</caption>
     <thead>
        <tr><th>Name</th><th>IMAP</th><th>ML</th></tr>
     </thead>
     <tbody>
        <tr><td>Asha</td><td>82</td><td>77</td></tr>
        <tr><td>Ravi</td><td>74</td><td>88</td></tr>
     </tbody>
     <tfoot>
        <tr><td colspan="3">Class average: 80.25</td></tr>                <!-- one cell spans 3 columns -->
     </tfoot>
  </table>



 <tr> = row, <th> = header cell (bold, centred), <td> = data cell. colspan merges cells across columns,
 rowspan down rows. Tables are for tabular data; for page layout use CSS Grid/Flexbox (section 1.4).


▸ Forms and inputs
A form collects input and sends it to a server. Two attributes on <form> matter most: action (the URL the
data goes to) and method ( get or post ). Each input needs a name : that is the key sent to the server
( name=Asha&email=... ). Each input should also have a <label for="id"> whose for matches the input's
 id , so clicking the label focuses the input and screen readers announce it.

 Input type         Gives you                           Input type          Gives you

  text              Single line of text                 password            Hidden characters

  email             Text that must look like an email   number              Numeric box with arrows; min , max , step

  tel , url         Phone / web address                 date                Date picker

  checkbox          Tick any number                     radio               Pick one of a group (same name )

  file              File chooser                        range , color       Slider, colour picker

  hidden            Value sent but not shown            submit / reset      Send / clear the form


           register.html — a complete form


  <form action="/register" method="post">
     <fieldset>
        <legend>Student details</legend>


        <label for="name">Name</label>
        <input type="text" id="name" name="name" placeholder="Asha Rao" required>

--- PDF page 28 ---
<label for="email">Email</label>
        <input type="email" id="email" name="email" required>


        <label for="age">Age</label>
        <input type="number" id="age" name="age" min="18" max="60">


        <p>Gender:
           <input type="radio" id="f" name="gender" value="F"><label for="f">F</label>
           <input type="radio" id="m" name="gender" value="M"><label for="m">M</label>
        </p>


        <label for="branch">Branch</label>
        <select id="branch" name="branch">
           <option value="ds">Data Science</option>
           <option value="ce">Computer Engg.</option>
        </select>


        <label for="msg">Message</label>
        <textarea id="msg" name="msg" rows="4"></textarea>


        <input type="checkbox" id="terms" name="terms" required>
        <label for="terms">I accept the terms</label>


        <button type="submit">Register</button>
        <button type="reset">Clear</button>
     </fieldset>
  </form>



                           GET                                                 POST

 Where data goes           In the URL query string ( ?name=Asha )              In the request body

 Visible / bookmarkable    Yes                                                 No

 Use for                   Searches, filters                                   Logins, sign-ups, anything that changes data



▸ HTML5 built-in validation: the first line of defence

 Attribute                                           Effect

  required                                           Field must be filled before the form submits.

  type="email" , type="url" , type="num‐             Browser checks the format.
 ber"

  min / max / step                                   Bounds for number and date inputs.

  minlength / maxlength                              Length limits for text.

  pattern="[A-Za-z ]+"                               Value must match this regular expression.

--- PDF page 29 ---
Attribute                                                         Effect

  novalidate (on <form> )                                          Turns the built-in checks off (used when JavaScript shows its own
                                                                   messages).


The browser blocks submission and shows a bubble message when a rule fails; CSS can style failures with
 input:invalid . For custom rules and inline messages you add JavaScript (section 1.19). Client-side checks
can be bypassed, so the server must always validate again.


▸ Semantic vs non-semantic HTML
A semantic tag says what its content means; a non-semantic tag ( <div> , <span> ) is a plain box used only
for grouping and styling.

 Semantic tag           Meaning                                              Semantic tag         Meaning

  <header>              Intro of the page or a section (logo, title)          <nav>               Navigation links

  <main>                The primary content (one per page)                    <section>           A thematic group with its own heading

  <article>             Self-contained content (blog post, card)              <aside>             Side content (sidebar, related links)

  <footer>              Closing info (copyright, contacts)                    <figure>            Media + caption



 Feature                         Semantic HTML                                               Non-semantic HTML

 Accessibility                   Clear: screen readers understand the structure              Varies: depends on added ARIA attributes

 SEO                             High: search engines read the structure directly            Low: no inherent meaning

 Clarity for developers          Easy: the tag name explains the role                        Needs class names to explain intent


Use a <div> only when no semantic tag fits, e.g. a purely decorative wrapper. Prefer <button> over a click‐
able <div> .


  BLOCK VS INLINE ELEMENTS                                                      CLASS VS ID

  Block ( div , p , h1 , section , ul ) start on a                                class can repeat on many elements (styling
  new line and take the full width. Inline ( span , a ,                         groups, .card ). id must be unique per page
   strong , em , img ) sit inside a line of text. CSS                           (one element, anchors #contact , JS getEle‐
   display can change either (1.8).                                             mentById ). Style with classes.



   ✏️ FILL IN THE BLANKS — HTML FORM
              complete the form


     <form ______="/contact" method="______">                                     <!-- 1, 2 -->
        <label ______="mail">Email</label>                                           <!-- 3 -->
        <input type="______" id="mail" ______="mail" ______>                             <!-- 4, 5, 6: must be filled -->
        <input type="number" id="age" name="age" ______="18" ______="60">                                  <!-- 7, 8 -->
        <button type="______">Send</button>                                          <!-- 9 -->
     </form>

--- PDF page 30 ---
10. The tag that wraps the primary content of a page, once per page:
   11. Attribute every <img> must have for accessibility:

   🔓 Answer key: 1 action · 2 post · 3 for · 4 email · 5 name · 6 required · 7 min · 8 max · 9 submit · 10 <main> · 11 alt


     1.4 Building a full page layout (PYQ)
📚 Sources: Lab 1 Manual (HTML) §6, §8         LEC 2 (CSS) slide 36 (named grid areas)     Unit 1 Notes §5.9

 Not in your files — added from standard references


     🚨 NOT IN YOUR STUDY MATERIAL · 10 MARKS · RE-EXAM 2023-24 Q3(B)
     What's missing: Lab 1 lists the semantic tags and table tags, and LEC 2 shows grid-template-areas ,
     but no file builds a complete header / navigation / content / footer page from a picture.

     Verdict: MUST LEARN. It is a 10-mark question you can answer with one memorised skeleton (about 40
     lines). The same skeleton is reused for any "make this page" question and for React layouts in Unit 4.



▸ The picture in the paper



                                          This is Web Page Main title
            Main Menu Navigation                             This is the main content of website
            HTML
            PHP
            PERL...




                                                           Copyright©2020 abc.com


             Redrawn from the 2023-24 paper: a title bar, a light-grey menu (≈40%), a darker grey content area (≈60%), a footer bar.



▸ How to attack any "make this layout" question

 1        Name the regions. Title → <header> , menu → <nav> , content → <main> , copyright → <footer> .

 2        Draw the grid. Two columns, three rows: "head head" / "menu main" / "foot foot" .

 3        Write the HTML with the exact texts from the picture.

 4        Write the CSS: display: grid + grid-template-areas , then colours, borders, alignment.

 5        Add one media query to stack the columns on phones (an easy extra mark).

--- PDF page 31 ---
PYQ         Re-Exam 2023-24 · Q3(b)                                                                        10 M


  Create a HTML Page to display a form given below as it is

    [Picture] Top box (centred, large bold): "This is Web Page Main title"
    Left column (light grey): "Main Menu Navigation" (bold), then HTML, PHP, PERL... on separate
    lines
    Right column (darker grey, wider): "This is the main content of website"
    Bottom bar (light grey, centred): "Copyright©2020 abc.com"



   ✓    MODEL ANSWER — WRITE THIS

  Approach. The page has four regions, so I use the HTML5 semantic tags <header> , <nav> , <main>
  and <footer> inside one wrapper, and lay them out with CSS Grid using named areas (two columns,
  three rows). Internal CSS keeps the answer in one file.

                layout.html


       <!DOCTYPE html>
       <html lang="en">
       <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>Web Page Layout</title>
         <style>
           * { box-sizing: border-box; }


           body {
               margin: 0;
               padding: 10px;
               font-family: "Times New Roman", serif;
           }


           /* the whole page is ONE grid with three rows and two columns */
           .page {
               display: grid;
               grid-template-columns: 2fr 3fr;              /* menu 40 %, content 60 % */
               grid-template-rows: auto 300px auto;         /* title, middle, footer    */
               grid-template-areas:
                 "head head"
                 "menu main"
                 "foot foot";
               gap: 3px;
               border: 1px solid #555;
               padding: 3px;
           }


           header, nav, main, footer {

--- PDF page 32 ---
border: 1px solid #888;
               padding: 4px 6px;
           }


           header { grid-area: head; text-align: center; padding: 22px; }
           header h1 { margin: 0; font-size: 2.2rem; }


           nav { grid-area: menu; background: #e8e8e8; }
           nav ul { list-style: none; margin: 0; padding: 0; }         /* no bullets, like the picture */
           nav a { color: inherit; text-decoration: none; }


           main { grid-area: main; background: #b0b0b0; }
           main p { margin: 0; }


           footer { grid-area: foot; background: #e8e8e8; text-align: center; }


           /* phones: stack everything in one column */
           @media (max-width: 600px) {
               .page {
                   grid-template-columns: 1fr;
                   grid-template-rows: auto auto 200px auto;
                   grid-template-areas: "head" "menu" "main" "foot";
               }
           }
        </style>
     </head>
     <body>
        <div class="page">
           <header>
               <h1>This is Web Page Main title</h1>
           </header>


           <nav>
               <b>Main Menu Navigation</b>
               <ul>
                   <li><a href="#">HTML</a></li>
                   <li><a href="#">PHP</a></li>
                   <li><a href="#">PERL...</a></li>
               </ul>
           </nav>


           <main>
               <p>This is the main content of website</p>
           </main>


           <footer>Copyright&copy;2020 abc.com</footer>

--- PDF page 33 ---
</div>
     </body>
     </html>



  HOW THE CODE PRODUCES THE PICTURE

        display: grid turns .page into a grid; its four children become grid items.

        grid-template-columns: 2fr 3fr splits the width 2 : 3 (menu ≈ 40%, content ≈ 60%).

        grid-template-areas "draws" the page: header and footer span both columns ( head head ,
        foot foot ); the middle row is menu main . Each child is placed with grid-area .

       Backgrounds #e8e8e8 (light grey) and #b0b0b0 (darker grey) and thin borders match the picture;
        text-align: center centres the title and the copyright line.

        list-style: none removes bullets so HTML / PHP / PERL... appear on plain separate lines; &copy;
       prints ©.
       The media query stacks the regions in one column below 600px (responsive).

  ALTERNATIVE 1 — THE CLASSIC TABLE LAYOUT (LOOKS IDENTICAL)

               table-layout.html (body only)


     <table width="100%" border="1" cellspacing="3" cellpadding="5">
        <tr>
           <td colspan="2" align="center" height="90">
             <h1>This is Web Page Main title</h1>
           </td>
        </tr>
        <tr valign="top">
           <td width="40%" height="300" bgcolor="#e8e8e8">
             <b>Main Menu Navigation</b><br>
             HTML<br>
             PHP<br>
             PERL...
           </td>
           <td width="60%" bgcolor="#b0b0b0">
             This is the main content of website
           </td>
        </tr>
        <tr>
           <td colspan="2" align="center" bgcolor="#e8e8e8">
             Copyright&copy;2020 abc.com
           </td>
        </tr>
     </table>

--- PDF page 34 ---
colspan="2" lets the title and footer cells stretch across both columns. This still renders in every browser,
  but bgcolor , align and valign are obsolete in HTML5 and layout tables are bad for accessibility and
  phones, which is why the semantic + Grid version is preferred.

  ALTERNATIVE 2 — FLEXBOX FOR THE MIDDLE ROW

               flex version of the middle row


     .middle { display: flex; gap: 3px; min-height: 300px; }                             /* wraps nav + main */
     nav         { flex: 2; }              /* 2 parts */
     main        { flex: 3; }              /* 3 parts */



  Conclusion. Semantic tags give the page meaning (accessibility, SEO); CSS Grid with named areas repro‐
  duces the layout in a few readable lines and adapts to small screens.

  🎯 Marking scheme guess: 2 M correct HTML5 skeleton + semantic regions · 2 M exact texts in the right places · 4 M CSS that repro‐
  duces the layout (grid/columns, colours, borders, centring) · 2 M explanation / responsiveness / alternative




  ⚠️ COMMON MISTAKE
  The paper says "display a form" but the picture contains no inputs. Do not write a <form> with text boxes;
  reproduce the layout exactly, with the texts word for word. If you are short of time, the table version is the
  fastest faithful answer.




    1.5 CSS basics and the three ways to add it (PYQ)
📚 Sources: Unit 1 Notes §5.1–5.2         LEC 2 (CSS) slides 3, 5, 6    LEC 1 (PDF) slide 16    One-Shot Revision · Unit 1


  🧠 START FROM ZERO
  CSS (Cascading Style Sheets) controls how HTML looks: colour, spacing, fonts, layout, motion. Keeping it
  separate from HTML is called separation of concerns: one stylesheet can style a thousand pages, so
  changing the brand colour in one file updates the whole site.



▸ Anatomy of a rule

                            declaration (property: value;)


              h1 { color: navy; margin-bottom: 1rem; }

            selector          property            value
                                                    everything between { and } = the declaration block

            Selector = which elements · property = what to change · value = what to change it to · a semicolon ends every declaration.


Beginner errors (LEC 2 slide 6): using = instead of : ; forgetting ; ; missing the closing } (the rest of the file breaks); writing
 10 px with a space (must be 10px ).

--- PDF page 35 ---
▸ Inline, internal and external CSS
Where you write the CSS decides its type. The code for all three is in the model answer just below; this table is
the comparison examiners look for.

                            Inline                           Internal                            External

  Written in                 style="..." attribute               <style> in <head>               Separate .css file +
                                                                                                  <link>

  Affects                   One element                      One page                            Every page that links it

  Reusable /                No / no                          Not across pages / no               Yes / yes (browser caches the
  cached                                                                                         file)

  Priority                  Highest (beats any selector)     Same weight; if they clash, the one that comes later in the <head>
                                                             wins

  Use for                   Quick test, JS-set styles;       Single-page demo, email             Every real project (default
                            avoid                            templates                           choice)



  ⚠️ COMMON MISTAKE
  Textbooks often say "inline > internal > external". Only the first part is a rule. Internal and external have the
  same priority; whichever is written later wins. The usual order ( <link> first, <style> after) makes internal
  win, which is where the textbook line comes from. !important beats all three.



   PYQ         Final 2024-25 · Q1(c)   Re-Exam 2023-24 · Q1(b)                                                                 5M


  2024-25: Explain with code inline, internal, and external CSS styles.
  2023-24: Explain the types of CSS with example.

   ✓    MODEL ANSWER — WRITE THIS

  CSS (Cascading Style Sheets) describes the presentation of HTML. Depending on where the CSS is writ‐
  ten, there are three types:

  1. Inline CSS — written in the style attribute of a single element; applies only to that element and has the
  highest priority. Not reusable, mixes content with style.

                inline


       <h1 style="color: blue; text-align: center;">Welcome</h1>



  2. Internal (embedded) CSS — written inside a <style> tag in the <head> ; applies to the whole page
  but cannot be shared with other pages.

                internal


       <head>
         <style>
             h1 { color: green; }

--- PDF page 36 ---
p   { font-size: 16px; }
          </style>
      </head>



  3. External CSS — written in a separate .css file and linked with <link> ; one file styles the entire web‐
  site, is cached by the browser, and keeps HTML clean. This is the recommended method.

                 index.html


      <head>
          <link rel="stylesheet" href="style.css">
      </head>



                 style.css


      h1 { color: red; }
      p   { font-family: Arial, sans-serif; }



  Priority (cascade): inline > internal/external (between these two the later one wins); !important overrides
  all. Conclusion: use external CSS for real projects, internal for single-page demos, inline only for one-off
  overrides.

  🎯 Marking scheme guess: 1 M definition of CSS · 3 M three types each with syntax/code (1 M each) · 1 M priority + when to use each


      1.6 Selectors, cascade, specificity, inheritance
📚 Sources: Unit 1 Notes §5.3–5.4       LEC 2 (CSS) slides 7–13     Lab 2 Manual (CSS) §1–2    One-Shot Revision · Unit 1


A selector answers one question: which elements does this rule apply to?

 Selector                     Syntax                         Matches                                 Use it for

 Type                         p                              Every <p>                               Base styles, resets

 Class                        .card                          Every element with                      Most styling (reusable, easy to
                                                                 class="card"                        override)

 ID                           #nav                           The one element with id="nav"           Anchors, JS hooks; rarely styling

 Universal                    *                              Every element                           Resets, box-sizing

 Grouping                     h1, h2, h3                     Any listed selector                     Sharing one declaration block

 Attribute                    input[type="email"             Elements with that attribute/value      Form controls
                              ]

 Chained                      a.btn                          An <a> that also has class btn          Being specific without a new class

 Descendant                   .menu li                       Any li inside .menu , any               Styling inside a component
                                                             depth

 Child                        .menu > li                     Only direct children                    Stopping styles leaking deeper

--- PDF page 37 ---
Selector                       Syntax                        Matches                                      Use it for

 Adjacent / general              h2 + p / h2 ~ p              The one p right after / every p              Spacing after headings
 sibling                                                      after



  ⚠️ THE .MENU > LI TRAP (LEC 2 SLIDE 8)
  With <div class="menu"><ul><li>Home</li><li>About</li></ul></div> : .menu li matches both
  items, .menu > li matches nothing (the ul sits in between), and li + li matches only "About".



  PSEUDO-CLASSES (STATE, ONE COLON)                                         PSEUDO-ELEMENTS (A PART, TWO
   :hover pointer over · :focus / :focus-visi‐
                                                                            COLONS)
  ble keyboard focus · :active being clicked ·                               ::before / ::after generated content (need
   :first-child , :last-child , :nth-child(2n)                               content ) · ::first-line · ::first-letter ·
  position · :not(.active) exclusion · :checked ,                            ::placeholder · ::selection .
   :disabled , :invalid form state.
                                                                             .required::after { content: "*"; color:
   tr:nth-child(odd) { background: #f4f4f4; }                               crimson; }



▸ The cascade: who wins when rules disagree?
Styles arrive from several places (browser defaults, a framework, your file). For each property separately, the
browser picks a winner in this strict order; each step matters only if the previous one tied:

                           1 Importance                         2 Specificity                       3 Source order
                        !important wins outright
                                                    →     more specific selector wins
                                                                                         →       still tied? later rule wins




▸ Specificity scoring
Count the selector into three buckets (IDs – classes/attributes/pseudo-classes – elements/pseudo-ele‐
ments) and compare left to right. A higher bucket always wins.

 Selector                                      Score              Notes

  p                                            0-0-1              Beats almost nothing

  .intro                                       0-1-0              Beats any number of element selectors

  p.intro                                      0-1-1              Beats a plain .intro

  ul li a:hover                                0-1-3                  :hover counts as a class

  #main p                                      1-0-1              Beats every rule made only of classes

  style="..."                                  inline             Beats all selectors in all stylesheets

  !important                                   override           Beats everything, including inline

--- PDF page 38 ---
🔑 MEMORY HOOK
   0-1-0 beats 0-0-11. Ten element selectors still lose to one class, and one ID beats any number of classes.
  Need to override? Use a better class, not !important (each !important makes the next bug harder; fair
  use is overriding a third-party widget you cannot edit).



▸ Inheritance

 Inherited automatically (mostly text)                                        Not inherited (box and layout)

  color , font-family , font-size , line-height ,                              margin , padding , border , background ,
  text-align , letter-spacing , visibility                                     width , height , display , position


That is why a font set on body reaches the whole page but a margin on body does not push every element.
Force it with color: inherit or reset with border: initial .


   ✏️ PREDICT THE RESULT — SPECIFICITY
              style.css + HTML


     /* HTML: <div id="box"><p class="msg note">Hello</p></div> */
     p                    { color: black; }            /* A */
     .msg                 { color: green; }            /* B */
     div p                { color: orange; }           /* C */
     #box .msg            { color: blue; }             /* D */
     .msg.note            { color: purple; }           /* E */
     p                    { color: red !important; }              /* F */



    1. Specificity of A, B, C, D, E:
    2. Colour of "Hello" with all six rules:
    3. Colour if rule F is deleted:
    4. Colour if F and D are deleted:

   🔓 Answer key: 1) A 0-0-1 · B 0-1-0 · C 0-0-2 · D 1-1-0 · E 0-2-0 — 2) red (!important wins) — 3) blue (D has an ID) — 4) purple (E 0-
   2-0 beats B 0-1-0 and C 0-0-2)




    1.7 The box model, units and colour
📚 Sources: Unit 1 Notes §5.5–5.6       LEC 2 (CSS) slides 15–22    Lab 2 Manual (CSS) §3–7, §11


Every element is a rectangle made of four nested layers, from the inside out: content → padding → border →
margin.

--- PDF page 39 ---
MARGIN — outside, transparent, pushes neighbours away

                              BORDER — the visible edge

                                PADDING — inside, takes the background colour


                                                               CONTENT
                                                              width × height




                            Open DevTools → Elements → box-model panel to see these four layers on any element.



▸ box-sizing: the one line every project needs

                                                                                width: 300px; padding: 10px; border:
  box-sizing                    What width means
                                                                               5px

  content-box                   Content only; padding + border added on        300 + 2×10 + 2×5 = 330px on screen
 (default)                      top

  border-box                    Whole box; padding + border fit inside         exactly 300px


             top of every stylesheet


  *, *::before, *::after { box-sizing: border-box; }


  .card {
      margin: 10px 20px;              /* 2 values: top-bottom            left-right                */
      padding: 10px 20px 5px 0;             /* 4 values: top right bottom left (clockwise) */
  }
  .container { width: 800px; margin: 0 auto; }                     /* centre a block that has a width */



Margin collapse: two vertical margins that touch do not add; the larger wins (30px + 20px gives 30px). Only
vertical margins collapse, and not inside flex/grid containers, which is one reason to prefer gap there.


▸ Units

 Unit            Relative to                                Best for                                Watch out

  px             Nothing (fixed)                            Thin borders                            Ignores the user's font-size setting

  %              Parent element                             Fluid widths                            % height needs a sized parent

  em             This element's font size                   Padding that scales with its text       Multiplies when nested

  rem            Root ( html ) font size                    Font sizes, spacing (default choice)    —

  vw / vh        1% of viewport width/height                Full-screen sections                    Mobile bars change vh; use dvh

  ch / fr        Width of "0" / share of free grid space    Line length (60–75ch) / grid tracks      fr works only in grid

--- PDF page 40 ---
Value functions: calc(100% - 40px) mixes units; clamp(1rem, 2.5vw, 2rem) = min, preferred, max;
 min(100%, 65ch) , max() .


▸ Colour, type, backgrounds, overflow — the essentials

 Topic                  Key facts

 Colour formats         Named tomato · hex #2E86AB · rgb(46 134 171) · hsl(197 58% 43%) (slide lightness for hover
                        shades) · alpha rgb(46 134 171 / 40%) . opacity fades the element and its children; an alpha colour
                        fades only that colour. Body text needs 4.5 : 1 contrast.

 Typography              font-family: "Inter", system-ui, sans-serif (end with a generic family) · font-weight
                        100–900 · unitless line-height: 1.5 · text-align , text-transform , text-decoration ,
                         letter-spacing .

 Backgrounds &           background: #eee url(bg.png) no-repeat center / cover; · gradients are images: linear-
 borders                gradient(135deg, #436768, #7fb0a8) · border: 2px solid #436768 (no style = no border) ·
                         border-radius: 50% = circle · box-shadow: 0 2px 8px rgb(0 0 0 / 15%) .

 Overflow                visible (default, spills) · hidden (clipped) · scroll (always a scrollbar) · auto (scrollbar only when
                        needed).




    1.8 Display and positioning
📚 Sources: Unit 1 Notes §5.7        LEC 2 (CSS) slides 24–26     Lab 2 Manual (CSS) §8


  display                     Behaviour                                                                       Default for

  block                       New line, full width; accepts width, height, all margins                         div p h1 section

  inline                      Sits in the text line; ignores width, height, top/bottom margin                  span a strong em

  inline-block                In the line, but accepts width/height                                           buttons, badges

  none                        Removed from the page, takes no space                                           hidden menus

  flex / grid                 Becomes a layout container (1.9, 1.10)                                          —


 display: none removes the box entirely; visibility: hidden hides it but keeps its space.

  position                 In normal flow?           Positioned against                         Typical use

  static (default)         Yes                       — (top/left/z-index ignored)               Everything

  relative                 Yes, keeps its space      Its own normal position                    Small nudges; parent of an absolute child

  absolute                 No                        Nearest positioned ancestor                Badges, tooltips, dropdowns

  fixed                    No                        The browser window (ignores scroll)        Chat button, fixed navbar

  sticky                   Yes until the offset      Acts relative, then fixed at top: 0        Sticky table headers, nav


            the absolute / relative pairing


  .card     { position: relative; }                                              /* the anchor */
  .badge { position: absolute; top: 8px; right: 8px; }                            /* sits in the card's corner */

--- PDF page 41 ---
/* forget position: relative on .card and the badge jumps to the page corner */



z-index works only on positioned elements (and flex/grid children); higher sits on top. A positioned parent with
its own z-index creates a stacking context its children cannot escape. float ( float: left ) was built for wrap‐
ping text around an image and was misused for whole layouts for years; read it in old code, but build rows with
Flexbox and pages with Grid.




    1.9 Flexbox: layout in one direction
📚 Sources: Unit 1 Notes §5.8                     LEC 2 (CSS) slides 27–32   Lab 2 Manual (CSS) §9   One-Shot Revision · Unit 1

 Complete Revision deck · U1 slide 7


  💡 THINK OF IT LIKE
  Beads on a string. Flexbox lines items up along one string (a row or a column) and decides how to share
  the leftover space between them.




                 CROSS → align-items
                                                  item               item                item



                                                         MAIN AXIS (flex-direction: row) → justify-content


                                                 display: flex on the parent; every direct child becomes a flex item.


  🔑 THE RULE
   justify-content moves items along the MAIN axis; align-items along the CROSS axis. Set
    flex-direction: column and the axes swap, so justify-content now moves things up and down.
  Centre anything: display: flex; justify-content: center; align-items: center;


 Container
                                       Values                                                                           Effect
 property

  flex-                                 row | row-reverse | column | column-reverse                                     Which way the main axis
 direction                                                                                                              points

  justify-                              flex-start | center | flex-end | space-between | space-                         Free space along the main
 content                               around | space-evenly                                                            axis

  align-items                           stretch (default) | flex-start | center | flex-end | base‐                      Alignment on the cross axis
                                       line

  flex-wrap                             nowrap | wrap                                                                   Allow a second line

  align-                               as justify-content                                                               Spaces the lines (only when
 content                                                                                                                wrapped)

--- PDF page 42 ---
Container
                          Values                                                                                Effect
 property

  gap                      1rem | 1rem 2rem                                                                     Space between items, no mar‐
                                                                                                                gin maths


 Item property                     Default           Meaning

  flex-grow                        0                 Share of leftover space this item takes

  flex-shrink                      1                 How much it shrinks when space is short (0 = never)

  flex-basis                       auto              Starting size before grow/shrink

  flex                              0 1 auto         Shorthand of the three; flex: 1 = "take an equal share"

  align-self / or‐                 auto / 0          Override align-items for one item / change visual order (screen readers still follow
 der                                                 HTML)


            three patterns that cover most layouts (LEC 2 slide 32)


  /* 1. navbar: logo left, links right */
  .nav { display: flex; justify-content: space-between; align-items: center; }
  .nav-links { display: flex; gap: 1rem; }


  /* 2. equal card row that wraps */
  .cards { display: flex; flex-wrap: wrap; gap: 1.5rem; }
  .card     { flex: 1 1 260px; }                             /* grow, shrink, start at 260px */


  /* 3. fixed sidebar + fluid content */
  .layout { display: flex; gap: 2rem; }
  .side      { flex: 0 0 240px; }                            /* never grow or shrink */
  .body      { flex: 1; }                                    /* take the rest */




    1.10 CSS Grid, and Grid vs Flexbox
📚 Sources: Unit 1 Notes §5.9           LEC 2 (CSS) slides 33–37    Lab 2 Manual (CSS) §10      One-Shot Revision · Unit 1

 Complete Revision deck · U1 slide 7


Grid lays items out in rows and columns at the same time. You define the tracks first; items drop into the cells.

 Term                   Meaning                                     Term          Meaning

 Grid container         The parent with display: grid               Grid item     Any direct child

 Track                  A whole row or column                       Line          Numbered borders between tracks, from 1; -1 = last

 Cell                   One row × one column                        Area          A block of cells, can be named


            defining tracks and placing items

--- PDF page 43 ---
.grid {
      display: grid;
      grid-template-columns: 200px 1fr 1fr;            /* fixed column + two equal shares of the rest */
      grid-template-rows: auto 300px;
      gap: 1.5rem;                                     /* gutters between rows and columns */
  }
  .three      { grid-template-columns: repeat(3, 1fr); }                         /* = 1fr 1fr 1fr */
  .gallery {                                                                     /* responsive, no media query */
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
      gap: 1rem;
  }
  .hero      { grid-column: 1 / 3; }          /* from line 1 to line 3 = two columns */
  .wide      { grid-column: span 2; }         /* stretch over two columns                       */
  .full      { grid-column: 1 / -1; }         /* first line to last line                        */
  .centre-all { place-items: center; }



 minmax(200px, 1fr) = never smaller than 200px, grows if there is room. auto-fit collapses empty columns
so items stretch; auto-fill keeps empty columns. Named areas are the most readable layout code: the
stylesheet draws a picture of the page (see the full example in 1.4).

             named areas (LEC 2 slide 36)


  .page {
      display: grid;
      grid-template-columns: 240px 1fr;
      grid-template-areas:
         "head head"
         "side main"
         "foot foot";
  }
  header { grid-area: head; }         aside { grid-area: side; }
  main       { grid-area: main; }     footer { grid-area: foot; }



                         Flexbox                                                     CSS Grid

  Dimensions             One axis: a row or a column                                 Two axes: rows and columns together

  Driven by              The content (items size themselves)                         The layout (tracks defined first)

  Best for               Navbars, toolbars, button groups, card rows, centring       Page skeletons, dashboards, galleries

  Overlapping items      Awkward                                                     Easy (two items in the same cell)

  Quick test             Can it be one row or one column?                            Must things line up in both directions?

--- PDF page 44 ---
🔑 MEMORY HOOK
   Grid the page, flex the parts. They are partners, not rivals: most real pages use Grid for the skeleton and
  Flexbox inside components.


   ✏️ FILL IN THE BLANKS — FLEXBOX AND GR I D
               complete the CSS


        /* centre a login box both ways inside .screen */
        .screen { display: ______; justify-content: ______; align-items: ______; height: 100vh; }


        /* 3 equal columns, featured item spans 2 (One-Shot example) */
        .gallery    { display: grid; grid-template-columns: ______(3, 1fr); gap: 16px; }
        .featured { grid-column: ______ 2; }


        /* page skeleton */
        .page { display: grid; grid-template-______:
                    "head head"
                    "side main"; }
        .side { grid-______: side; }



    8. In a flex container with flex-direction: column , which property moves items vertically?
    9. flex: 1 is short for flex: 1 1 ___

   🔓 Answer key: flex · center · center · repeat · span · areas · area · 8) justify-content (the main axis is now vertical) · 9) 0% (flex-basis
   0)




    1.11 Responsive design and modern CSS
📚 Sources: Unit 1 Notes §5.10–5.11         LEC 2 (CSS) slides 39–43      Lab 2 Manual (CSS) §12–15


Responsive design = one page that adapts to every screen width. Three ingredients: the viewport meta tag, flu‐
id units/layouts, and media queries.

            responsive basics


  <!-- in <head>: without this, phones zoom out and none of it works -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">



            mobile first (min-width): every rule ADDS


  .grid { display: grid; grid-template-columns: 1fr; }                                       /* phones: 1 column */
  @media (min-width: 600px) { .grid { grid-template-columns: repeat(2, 1fr); } }
  @media (min-width: 900px) { .grid { grid-template-columns: repeat(4, 1fr); } }

--- PDF page 45 ---
/* desktop first would start with 4 columns and UNDO them with max-width queries */
  @media (prefers-color-scheme: dark)          { :root { --bg: #111; } }
  @media (prefers-reduced-motion: reduce) { * { animation: none; transition: none; } }
  @media print { nav { display: none; } }



Why mobile first: the smallest screen is the hardest constraint, phones never download desktop-only rules, and
one narrow column forces you to decide what content matters. Common breakpoints 640 / 768 / 1024 / 1280px,
but the course advice is: widen the browser until the layout looks broken, and put the breakpoint there. Fluid
tools that need no media query: clamp() , min() , repeat(auto-fit, minmax(...)) .


▸ Custom properties (CSS variables) and theming

           variables on :root


  :root {
      --brand: #436768;
      --space: 1rem;
      --radius: 12px;
  }
  .btn {
      background: var(--brand);
      padding: var(--space);
      border-radius: var(--radius, 8px);      /* 8px is the fallback if --radius is not set */
  }
  @media (prefers-color-scheme: dark) {
      :root { --brand: #9fc4c6; }             /* that is the whole dark theme */
  }
  /* JavaScript can change them live: el.style.setProperty("--brand", "#c00"); */



Variables are inherited (set on :root , usable everywhere), have fallbacks, and turn theming into "override a
handful of variables". The Lab 2 Playground's day/night switch is one selector overriding five variables, with no
JavaScript.


▸ Transitions, transforms and animations

           motion


  /* transition: smooth change between TWO states; write it on the normal state */
  .btn           { transition: background 200ms ease, transform 200ms ease; }
  .btn:hover { background: #2e4b4d; transform: scale(1.05); }


  /* @keyframes: a named sequence that can play on its own */
  @keyframes fade-in {
      from { opacity: 0; transform: translateY(10px); }
      to    { opacity: 1; transform: translateY(0); }
  }

--- PDF page 46 ---
.card { animation: fade-in 0.4s ease-out; }
  @keyframes spin { to { transform: rotate(360deg); } }



Animate transform and opacity : they are the only properties the browser can animate without recalculating
layout, so they stay smooth (60 fps). Animating width , height , top , left re-runs layout every frame and
looks jerky. Respect prefers-reduced-motion .


▸ Organising a stylesheet
File order: reset + box-sizing → variables on :root → base elements → layout → components → utilities →
media queries. BEM naming keeps specificity flat at 0-1-0: .card (block), .card__title (element),
 .card--featured (modifier). Name by purpose ( .btn--danger ), never appearance ( .red-button ), and never
style by ID.

  ✍️ HOW TO WRITE THIS IN THE EXAM
  "What is responsive web design?" (5 M): definition → viewport meta → mobile-first + one
    @media (min-width) example → fluid units (%, rem, fr, clamp) → flexible layouts (Flexbox/Grid, auto-fit)
  → one line on frameworks (Bootstrap grid).




    1.12 CSS frameworks: Bootstrap and Tailwind
📚 Sources: Unit 1 Notes §6   LEC 3 (Git · Frameworks · JS) slides 19–24     Lab 3 Manual (JS · Git) §6


A CSS framework is pre-written, pre-tested CSS you pull in instead of styling everything by hand. You gain
consistent cross-browser styling, a responsive grid out of the box and fast prototyping; you trade some control
over fine details, a little file size, a learning curve, and (with Bootstrap) sites that can look "samey".


  BOOTSTRAP (2011, TWITTER)                                               TAILWIND (2017)

  Component-based. One class names a finished                             Utility-first. No ready-made button; you stack one
  look: btn btn-primary , card , navbar ,                                 small class per CSS property right in the HTML:
   alert , modal , badge . Also a 12-column grid                          bg-teal-600 text-white px-4 py-2 rounded-lg
  ( container , row , col-* ), utility classes and JS                     hover:bg-teal-700 . Responsive and state vari‐
  plugins (dropdowns, carousels, modals).                                 ants are prefixes: md:flex , hover:underline ,
                                                                          dark:bg-black .


           the same button, two ways (Lab 3 §6)


  <!-- Bootstrap: include once in <head> -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
  rel="stylesheet">
  <button class="btn btn-primary">Save</button>


  <!-- Tailwind: Play CDN for quick demos (real projects install it with a build step) -->

--- PDF page 47 ---
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
  <button class="bg-teal-600 text-white px-4 py-2 rounded-lg hover:bg-teal-700">Save</button>




▸ The Bootstrap grid
Each row is split into 12 units: col-6 = half, col-4 = a third. A breakpoint prefix applies from that width up
(mobile first): sm ≥576px, md ≥768px, lg ≥992px, xl ≥1200px. Here is the 1.4 layout in Bootstrap:

           layout with Bootstrap classes


  <div class="container border p-1">
     <header class="border text-center p-4"><h1>This is Web Page Main title</h1></header>
     <div class="row g-1 my-1">
         <nav    class="col-12 col-md-5 bg-light border">Main Menu Navigation ...</nav>                               <!-- full
  width on phone, 5/12 on desktop -->
         <main class="col-12 col-md-7 bg-secondary-subtle border" style="min-height:300px">
           This is the main content of website
         </main>
     </div>
     <footer class="border bg-light text-center">Copyright&copy;2020 abc.com</footer>
  </div>



                    Bootstrap                                    Tailwind

  Approach          Ready-made components                        Small single-property utility classes

  You think in      Finished pieces (a card, a navbar)           CSS properties (padding, colour)

  HTML reads        Clean, few classes                           Busy, many classes

  Custom            Harder; sites look similar                   Easy; you compose the design
  look

  Extras            JS plugins, 12-col grid                      Variants ( md: , hover: , dark: ); unused classes removed in
                                                                 production

  Best when         Speed and sensible defaults matter           A unique, tightly controlled design matters most
                    most


Neither is "better": Bootstrap for speed and consistency, Tailwind for control and a custom look (many new
projects choose Tailwind).




    1.13 JavaScript basics
📚 Sources: Unit 1 Notes §7.1–7.3       LEC 3 (Git · Frameworks · JS) slides 26–31   Lab 3 Manual (JS · Git) §1   One-Shot Revision · Unit 1

 Complete Revision deck · U1 slide 8

--- PDF page 48 ---
🧠 START FROM ZERO
  If HTML is the structure and CSS the presentation, JavaScript is the behaviour: it responds to clicks, typ‐
  ing and scrolling, changes the page after it has loaded, and fetches data from a server without a refresh. It
  runs inside the browser; press F12 → Console to try any line, and use console.log() to print.


           where the code goes (LEC 3 slide 27)


  <body>
     ...page...
     <script src="app.js"></script>                      <!-- best: external file at the END of body -->
     <script>console.log("hi");</script>                 <!-- inline, for tiny tests only -->
  </body>
  <!-- or in <head>: <script defer src="app.js"></script>                     runs after the HTML is parsed -->




▸ Variables: const, let, and why var is gone

 Keyword         Reassign?      Scope                                   Use

  const          No             Block { }                               Default choice

  let            Yes            Block { }                               Only when the value really changes (counters, totals)

  var            Yes            Function (leaks out of blocks)          Old code only; do not use


           scope and const, with the real outputs


  if (true) { var a = 1; let b = 2; }
  console.log(a);                   // 1      -> var leaked out of the if-block
  console.log(b);                   // ReferenceError: b is not defined


  const user = { name: "A" };
  user.name = "B";                  // allowed: const locks the NAME, not the contents
  user = {};                        // TypeError: Assignment to constant variable.


  for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);                           // 3 3 3
  for (let j = 0; j < 3; j++) setTimeout(() => console.log(j), 0);                           // 0 1 2 (new j per loop)




▸ Data types

 Primitives — copied by value                                                            Reference types — copied by reference

  string "hello" · number 42, 3.14 · boolean true/false · null deliber‐                   array [1, 2, 3] · object { name: "Aditi" }
 ate "nothing" · undefined not yet assigned · symbol , bigint                            · function

 Two variables are always independent                                                    Two variables can point at the same array:
                                                                                         change it through one, the other sees it

--- PDF page 49 ---
A variable has no fixed type; the value carries it (dynamic typing). typeof "hi" → "string" , typeof 42 →
 "number" , typeof [] → "object" (use Array.isArray ), and the famous quirk typeof null →
 "object" .


▸ Operators, equality and truthy values

  === NOT ==                                              FALSY VALUES (ONLY SIX)
   5 === "5" → false (number vs string)                     false , 0 , "" , null , undefined , NaN .
   5 == "5" → true ( == converts types!)
                                                          Everything else is truthy, including "0" , [] and
   0 == false → true · null == undefined →
                                                            {} .
  true
   NaN === NaN → false (use Number.isNaN )                  a || b falls back on any falsy value; a ?? b
                                                          only on null/undefined.
  Always use === and !== .


Arithmetic + - * / % ** · comparison === !== > < >= <= · logical && || ! · nullish ?? · optional chain‐
ing ?. . Note "5" + 2 → "52" (string join) but "5" - 2 → 3 .

           control flow


  let grade;
  if (score > 90) grade = "A";
  else if (score > 75) grade = "B";
  else grade = "C";


  const pass = score > 40 ? "yes" : "no";             // ternary


  switch (day) {
      case "Sat": case "Sun": console.log("weekend"); break;
      default: console.log("weekday");
  }


  for (let i = 0; i < 5; i++) console.log(i);         // classic loop (need the index)
  for (const item of cart) console.log(item);         // values of an array (cleanest)
  for (const key in user) console.log(key);           // keys of an object
  while (!done) { /* unknown number of repeats */ }




   ✏️ PREDICT THE OUTPUT
              what does each line print?


      console.log(5 == "5", 5 === "5");            // 1
      console.log(typeof null, typeof []);         // 2
      console.log("5" + 2, "5" - 2);               // 3
      console.log(Boolean("0"), Boolean([]), Boolean(""));         // 4
      console.log(0 || 10, 0 ?? 10);               // 5

--- PDF page 50 ---
const p = [1, 2]; const q = p; q.push(3);
      console.log(p);                                                    // 6



   🔓 Answer key: 1) true false · 2) object object · 3) 52 3 · 4) true true false · 5) 10 0 · 6) [1, 2, 3] (q and p are the same array). All verified
   in Node.




      1.14 ES6+, arrays, objects and modules
📚 Sources: Unit 1 Notes §7.5–7.6, §7.11          LEC 3 (Git · Frameworks · JS) slides 34–38      Lab 3 Manual (JS · Git) §1–2

 One-Shot Revision · Unit 1


ECMAScript is the official standard that JavaScript follows. ES6 (= ES2015) was the huge modernising update;
since then a smaller version ships every year, so "ES6+" means "modern JavaScript".

 Feature                                Version                      One-line example

  let / const , arrow                   ES2015                        const add = (a, b) => a + b;
 functions

 Template literals                      ES2015                        `Hi ${name}, score ${a + b}`

 Destructuring                          ES2015                        const { name, age } = user; · const [first, ,
                                                                     third] = arr;

 Default parameters                     ES2015                        function greet(n = "there") {}

 Spread / rest ...                      ES2015 (objects               [...a, ...b] · { ...user, age: 22 } · function
                                        ES2018)                      sum(...nums)

 Classes, modules, Promises             ES2015                        class Student {} · import { add } from './math.js'

  Array.includes , **                   ES2016                        [1, 2].includes(2) · 2 ** 3

  async / await                         ES2017                        const r = await fetch(url);

 Optional chaining, nullish ??          ES2020                        user?.address?.city · x ?? "default"


              ES6 essentials in action (outputs verified)


  const user = { name: "Asha", age: 21, address: { city: "Mumbai" } };


  const { name, age, phone = "N/A" } = user;                             // "Asha" 21 "N/A" (default used)
  const { name: fullName } = user;                                        // rename while destructuring
  const [first, , third] = [10, 20, 30];                                  // 10 30


  const all        = [...[1, 2], ...[3, 4]];                              // [1, 2, 3, 4]            spread
  const copy = { ...user, age: 22 };                                      // new object, user.age is still 21
  function sum(...nums) {                                                 // rest: gathers args into an array
      return nums.reduce((t, n) => t + n, 0);
  }
  sum(1, 2, 3, 4);                                                        // 10

--- PDF page 51 ---
console.log(`${name} lives in ${user?.address?.city}`);                  // Asha lives in Mumbai
  console.log(user?.contact?.email);                             // undefined (no crash)




▸ Arrays and the methods that replace loops
Basics: cart.length , cart[0] (zero-indexed), push / pop (end), shift / unshift (start), includes(x) ,
 indexOf(x) (−1 if absent), slice(a, b) (copy of part), join(", ") , sort() / reverse() (in place).

 Method                         Returns                                    Example

  forEach(fn)                   Nothing; just runs fn per item              cart.forEach(x => console.log(x))

  map(fn)                       New array, same length, transformed         nums.map(n => n * 2)

  filter(fn)                    New array of items that pass the test       nums.filter(n => n > 10)

  reduce(fn, start)             One value (sum, max, object)                nums.reduce((t, n) => t + n, 0)

  find(fn)                      First matching item or undefined            users.find(u => u.id === 3)

  some(fn) / every(fn)          true if any / all pass                      marks.every(m => m >= 40)


           Lab 3 §2 chain — read it as a sentence


  [1, 2, 3, 4, 5, 6, 7, 8]
       .filter(n => n % 2 === 0)          // keep the even ones           -> [2, 4, 6, 8]
       .map(n => n * n)                   // square each                  -> [4, 16, 36, 64]
       .reduce((a, b) => a + b, 0);       // add them up                  -> 120



  ⚠️ COMMON MISTAKE
    map / filter / reduce never change the original array (that is why they chain safely), but sort() does,
  and sorts as strings: [10, 1, 5].sort() → [1, 10, 5] . Use sort((a, b) => a - b) for numbers.



▸ Objects, classes and JSON

           objects and an ES6 class


  const student = {
       name: "Aditi",
       age: 21,
       greet() { return `Hi ${this.name}`; }             // method: `this` = the object it was called on
  };
  student.name;             // "Aditi"        dot access
  student["age"];           // 21             bracket access (key in a variable)


  class Student {                                        // blueprint (ES6 syntax over constructor functions)
       constructor(name, marks) { this.name = name; this.marks = marks; }
       isPass() { return this.marks >= 40; }
  }

--- PDF page 52 ---
class Topper extends Student {                           // inheritance
      constructor(name, marks, rank) { super(name, marks); this.rank = rank; }
  }
  new Topper("Asha", 95, 1).isPass();                      // true


  JSON.stringify({ name: "Asha", marks: [90, 85] });                        // '{"name":"Asha","marks":[90,85]}'                   object
  -> text
  JSON.parse('{"ok":true}').ok;                                             // true                                                text
  -> object



JSON is exactly this object shape written as text, and is how APIs send data (1.1). Arrays hold ordered items;
objects hold named ones; together they model almost any data.


▸ Modules: import and export

           math.js → app.js


  // math.js
  export function add(a, b) { return a + b; }                   // named export
  export const PI = 3.14;
  export default function square(n) { return n * n; }                       // one default export per file


  // app.js
  import square, { add, PI } from './math.js';
  console.log(add(2, 3), PI, square(4));                          // 5 3.14 16


  // index.html:        <script type="module" src="app.js"></script>



  ✍️ HOW TO WRITE THIS IN THE EXAM
  "Explain any five ES6 features with examples" (5 M): pick let/const, arrow functions, template literals, de‐
  structuring, spread/rest (or Promises/classes/modules); one-line definition + one-line code each. Mention
  that ES6 = ES2015 and that async/await (ES2017) and optional chaining (ES2020) are "ES6+".




      1.15 Every type of JavaScript function
📚 Sources: Unit 1 Notes §7.4   LEC 3 (Git · Frameworks · JS) slides 32–33     Not in your files — added from standard references



      🚨 NOT IN YOUR STUDY MATERIAL · 20 MARKS · RE-EXAM 2023-24 Q3(A) + FINAL 2024-25
        Q3(A)

      What's missing: your notes and LEC 3 teach only two kinds (the function declaration and the arrow func‐
      tion). Both older papers asked for "the different types of JavaScript functions" for 10 marks, together with
      callbacks (2024-25) and async/await (2023-24).

--- PDF page 53 ---
Verdict: MUST LEARN. Asked in two consecutive papers; the same knowledge (callbacks, async func‐
      tions) also powers the Promise and package-delivery questions. The table below plus six short snippets is
      the whole answer.



▸ Anatomy of a function

               parts of a function


  function greet(name = "there") {                 // name = parameter (with a default value)
       return `Hi ${name}`;                          // return sends a value back
  }
  greet("Aditi");                                    // "Aditi" = argument             ->   "Hi Aditi"
  greet();                                           // "Hi there"
  // no return statement         ->       the call evaluates to undefined



 #      Type                         What it is                                             Key point

 1      Function declaration          function add(a, b) { ... }                            Hoisted: callable before the line it is written on

 2      Function expression          A function stored in a variable                        Not usable before its line

 3      Anonymous function           A function with no name                                Usually passed straight to something

 4      Arrow function (ES6)          (a, b) => a + b                                       Short; no own this ; cannot be used with
                                                                                             new

 5      IIFE                         Immediately Invoked Function Expression                Runs once, creates a private scope

 6      Callback function            A function passed to another to be called later        Basis of events, timers, array methods

 7      Higher-order function        Takes and/or returns a function                         map , filter ; closures

 8      Constructor function         Called with new to build objects                       Capitalised name; this = new object

 9      Async function                async function f() {}                                 Always returns a Promise; may use await

 10     Generator function            function* gen() { yield 1; }                          Can pause ( yield ) and resume

 +      Method · recursive           Function stored on an object · function that calls      user.greet() · factorial(n)
        function                     itself


               functions.js — every type, outputs verified with Node


  // 1. Function declaration (hoisted: can be called before it is written)
  console.log(add(2, 3));                               // 5
  function add(a, b) {
       return a + b;
  }


  // 2. Function expression (NOT usable before this line)
  const multiply = function (a, b) {
       return a * b;
  };
  console.log(multiply(4, 5));                          // 20

--- PDF page 54 ---
// calling multiply() above its line -> ReferenceError: Cannot access 'multiply' before initial‐
  ization


  // 3. Anonymous function (no name) passed straight to setTimeout
  setTimeout(function () {
      console.log("anonymous ran");
  }, 0);


  // 4. Arrow function (ES6): short syntax, implicit return, no own `this`
  const square = n => n * n;
  const greet = (name = "there") => `Hi ${name}`;
  console.log(square(6), greet("Asha"));     // 36 Hi Asha


  // 5. IIFE: defined and run immediately; `secret` stays private
  (function () {
      const secret = "private";
      console.log("IIFE ran");
  })();


  // 6. Callback: a function passed in and called later by the receiver
  function processOrder(item, callback) {
      console.log("Processing", item);
      callback(item);
  }
  processOrder("laptop", function (x) {
      console.log("Callback: order for", x, "done");
  });


  // 7. Higher-order function: returns a function (closure remembers `factor`)
  function makeMultiplier(factor) {
      return function (n) {
        return n * factor;
      };
  }
  const double = makeMultiplier(2);
  console.log(double(10), [1, 2, 3].map(double));      // 20 [2, 4, 6]


  // 8. Constructor function: used with `new`
  function Student(name, roll) {
      this.name = name;
      this.roll = roll;
  }
  const s1 = new Student("Asha", 21);
  console.log(s1.name, s1.roll);          // Asha 21


  // 9. Async function: always returns a Promise

--- PDF page 55 ---
async function getMarks() {
      return 92;                                   // wrapped automatically in a resolved Promise
  }
  getMarks().then(m => console.log("marks =", m));                   // marks = 92


  // 10. Generator function: pauses at each yield
  function* idGenerator() {
      yield 1;
      yield 2;
  }
  const gen = idGenerator();
  console.log(gen.next().value, gen.next().value, gen.next().done);                         // 1 2 true


  // + recursive function
  function factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); }
  console.log(factorial(5));                       // 120




▸ Arrow function vs regular function

                        Regular function                                  Arrow function

 Syntax                  function f(a) { return a * 2; }                   const f = a => a * 2; (implicit return)

  this                  Its own; depends on how it is called              None of its own; uses the surrounding this (lexical)

  arguments object      Yes                                               No (use rest ...args )

 Use with new           Yes (constructor)                                 No → TypeError: ... is not a constructor

 Hoisting               Declarations are hoisted                          Stored in a variable, so not usable before its line

 Best for               Object methods, constructors                      Short callbacks: nums.map(n => n * 2)



▸ Callbacks in depth
A callback is a function passed as an argument to another function, which calls it back at the right moment.
Synchronous callbacks run immediately ( forEach , map ); asynchronous callbacks run later, when something
finishes or happens ( setTimeout , addEventListener , reading a file). Callbacks are how JavaScript handles
events and slow work without freezing, but nesting many of them leads to callback hell (1.16).

            sync and async callbacks


  [1, 2, 3].forEach(n => console.log(n));                          // sync: runs now, 3 times


  button.addEventListener("click", () => {                          // async: runs whenever a click happens
      console.log("clicked!");
  });


  setTimeout(() => console.log("2 s later"), 2000);                   // async: runs after the timer

--- PDF page 56 ---
🔑 MEMORY HOOK — TWO FAMILIES OF FIVE
  By how it is written: declaration, expression, anonymous, arrow, IIFE. By what it does: callback, higher-
  order, constructor, async, generator. Learn one 2–3 line snippet for each and you can answer "any three" or
  "all types in brief".


   ✏️ NAME THE TYPE / FILL THE BLANK
               identify each function


     (function () { console.log("hi"); })();                                         // A
     const total = prices.reduce((s, p) => s + p, 0);                                // B: the (s, p) => ... part
     function Car(model) { this.model = model; }                                     // C (used as new Car("i20"))
     async function load() { const r = await fetch(u); }                             // D
     function* counter() { ______ 1; ______ 2; }                                     // E: fill the keyword
     const twice = f => x => f(f(x));                                                // F



   🔓 Answer key: A IIFE · B arrow function used as a callback · C constructor function · D async function · E yield, yield (generator) · F
   higher-order function (takes and returns a function)




    1.16 Asynchronous JS: callbacks to Promises (PYQ)
📚 Sources: Unit 1 Notes §7.9        LEC 3 (Git · Frameworks · JS) slides 44–46, 50     Lab 3 Manual (JS · Git) §5   One-Shot Revision · Unit 1

 Complete Revision deck · U1 slide 9


  🧠 START FROM ZERO
  JavaScript runs on a single thread: it can do only one thing at a time. If it simply waited for a slow job (a
  network request, a 2-second timer), the whole page would freeze. So JavaScript starts the slow job, keeps
  going with other code, and handles the result when it arrives. Code written this way is asynchronous.


  💡 THINK OF IT LIKE
  Ordering at a food court. You order (start the job), get a buzzer (a Promise), and go find a table (keep run‐
  ning other code). When the buzzer goes off (the job finished), you collect the food (handle the result).
  Nobody stands frozen at the counter.

--- PDF page 57 ---
▸ The event loop: how "later" actually works


                 Call stack                                   Web APIs (browser)
                                           hand off
           runs ONE thing at a time                          timers · fetch · DOM events
                                                             do the slow work in parallel




                                                           Microtask queue — Promise .then / await continuations (run FIRST)

              console.log("A")
                                                           Task queue — setTimeout, click handlers (run after microtasks)

                              event loop: when the stack is empty,
                              move the next queued callback onto it


                   Synchronous code always finishes first; then all microtasks (Promises); then the next task (timers, events).


           event loop in 4 lines (verified output: A D C B)


  console.log("A");                                                          // sync
  setTimeout(() => console.log("B"), 0);                                     // task queue (even with 0 ms)
  Promise.resolve().then(() => console.log("C"));                            // microtask queue
  console.log("D");                                                          // sync
  // prints: A D C B




▸ Stage 1 — callbacks, and callback hell
The first solution: pass a function to be run "when done". It works, but when each step needs the previous one,
the callbacks nest deeper and deeper (LEC 3 slide 44):

           callback hell (the "pyramid of doom")


  getUser(id, user => {
     getPosts(user, posts => {
        getComments(posts, comments => {
           // ...and the next step goes even deeper
        });
     });
  });



Problems: hard to read (code drifts right), errors must be handled separately at every level, and you hand con‐
trol of your code to someone else's function ("inversion of control"). Promises were invented to fix this, and
async/await to make Promises read like normal code. Each row was invented to fix the one above it.


▸ Stage 2 — Promises
A Promise is an object that represents a value that is not ready yet: a placeholder for the future result of an
asynchronous operation.

--- PDF page 58 ---
PENDING          →                    FULFILLED
                                                                                     or
                                                                                                REJECTED
                        still waiting    resolve(value)   got a value → .then()           got an error → .catch()



Fulfilled and rejected are together called settled; once settled, a Promise never changes state again.

            promise-demo.js — create and consume (outputs verified)


  // CREATE: wrap slow work; call resolve on success, reject on failure
  function checkMarks(marks) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (marks >= 40) resolve(`Passed with ${marks}`);
            else reject(new Error(`Failed with ${marks}`));
        }, 1000);
      });
  }


  // CONSUME
  checkMarks(72)
      .then(result => console.log("then:", result))                        // then: Passed with 72
      .catch(err => console.log("catch:", err.message))                    // runs only on rejection
      .finally(() => console.log("finally: done"));                        // runs either way


  checkMarks(30)
      .then(result => console.log("then:", result))
      .catch(err => console.log("catch:", err.message))                    // catch: Failed with 30
      .finally(() => console.log("finally: done"));


  // CHAIN: whatever a .then returns is passed to the next .then
  Promise.resolve(2)
      .then(n => n * 10)                // 20
      .then(n => n + 5)                 // 25
      .then(n => console.log("chain:", n));                // chain: 25


  // Real use (LEC 3 slide 45): fetch returns a Promise
  fetch("/api/user")
      .then(res => res.json())                              // unwrap the response
      .then(user => console.log(user))                      // use the data
      .catch(err => console.log(err));                      // ONE catch handles a failure anywhere above



 Static method                                   Resolves when                        Rejects when             Use for

  Promise.all([p1, p2])                          ALL fulfil (array of values, same    ANY one rejects          Independent requests in
                                                 order)                                                        parallel

  Promise.race([...])                            The FIRST to settle fulfils          The first to settle      Timeouts
                                                                                      rejects

--- PDF page 59 ---
Static method                                     Resolves when                      Rejects when          Use for

  Promise.allSettled([...])                        All settle (list of {status,       Never                 "Tell me how each one
                                                   value/reason})                                           went"

  Promise.any([...])                               First to FULFIL                    All reject            Fastest mirror/server

  Promise.resolve(v) /                             Make an already-settled Promise
  Promise.reject(e)



  🔑 MEMORY HOOK (LEC 3 SLIDE 50)
      Concept                                     Easy meaning

      Callback                                    "Call me when you're done."

      Promise                                     "I'll give you the result later."

      async/await                                 "Wait here, then continue."

      Promise.all()                               "Start everything together."




▸ Turning a callback function into a Promise function
This pattern is exactly what the 10-mark package-delivery question (1.17) tests: delete the callback parame‐
ter, return a new Promise , and call resolve() where the callback used to be called.

            callback style → Promise style


  // before
  function wait(ms, callback) {
       setTimeout(callback, ms);
  }
  wait(1000, () => console.log("done"));


  // after
  function wait(ms) {
       return new Promise(resolve => setTimeout(resolve, ms));
  }
  wait(1000).then(() => console.log("done"));




   PYQ          Final 2024-25 · Q1(d)   Re-Exam 2023-24 · Q1(a)                                                                 5M


  2024-25: Write a short note on promises.
  2023-24: What are Promises in Javascript?

   ✓    MODEL ANSWER — WRITE THIS

  Definition. A Promise in JavaScript is an object that represents the eventual completion (or failure) of an
  asynchronous operation and its resulting value. It is a placeholder for a value that is not available yet, e.g.
  data from a server or the result of a timer.

--- PDF page 60 ---
States. A Promise is always in one of three states: pending (initial, operation still running) → fulfilled (com‐
  pleted successfully, has a value) or rejected (failed, has a reason/error). Once fulfilled or rejected it is set‐
  tled and cannot change.

  Creating — the executor function receives resolve and reject :

               create


     const orderPizza = new Promise((resolve, reject) => {
         setTimeout(() => {
           const ovenWorking = true;
           if (ovenWorking) resolve("Pizza is ready");
           else reject(new Error("Oven broke down"));
         }, 2000);
     });



  Consuming — .then() runs on success, .catch() on failure, .finally() always:

               consume


     orderPizza
         .then(msg => console.log(msg))                             // Pizza is ready (after 2 s)
         .catch(err => console.log(err.message))
         .finally(() => console.log("Order closed"));



  Chaining and combining. Each .then() returns a new Promise, so steps can be chained one after an‐
  other with a single .catch() at the end. Promise.all([p1, p2]) runs independent Promises in parallel
  and waits for all of them.

  Advantages over callbacks: no callback hell (flat chain instead of nesting), centralised error handling, easy
  composition ( all , race ), and they are the foundation of async/await .

  🎯 Marking scheme guess: 1 M definition · 1 M three states · 2 M syntax: create (resolve/reject) + consume (then/catch/finally) with exam‐
  ple · 1 M chaining / Promise.all / advantages




   ✏️ FILL IN THE BLANKS — PROMISES
               complete the code


     function getUser(id) {
         return new ______((______, ______) => {                        // 1, 2, 3
           setTimeout(() => {
               if (id > 0) ______({ id, name: "Asha" });                  // 4: success
               else ______(new Error("Invalid id"));                      // 5: failure
           }, 500);
         });
     }
     getUser(1)
         .______(user => console.log(user.name))                          // 6

--- PDF page 61 ---
.______(err => console.log(err.message))                             // 7
          .______(() => console.log("done"));                                  // 8: always runs


       const [a, b] = await Promise.______([getUser(1), getUser(2)]);                                  // 9: run both together



   10. The three states of a Promise:

   🔓 Answer key: 1 Promise · 2 resolve · 3 reject · 4 resolve · 5 reject · 6 then · 7 catch · 8 finally · 9 all · 10 pending, fulfilled, rejected


      1.17 async/await and the package-delivery PYQ
📚 Sources: Unit 1 Notes §7.9–7.10          LEC 3 (Git · Frameworks · JS) slides 47–49      Lab 3 Manual (JS · Git) §5     One-Shot Revision · Unit 1


async/await is not a new mechanism: it is nicer syntax layered directly over Promises, so asynchronous code
reads top to bottom like ordinary code, without freezing the page.

      async before a function makes it always return a Promise (a returned value is wrapped in a resolved
      Promise; a thrown error becomes a rejection).
      await (only inside an async function, or at the top level of a module) pauses that function until the
      Promise settles, then gives you its value. The rest of the page keeps running.
      A rejected await throws, so the familiar try / catch / finally handles errors.

            the same fetch, two ways (One-Shot / Complete Revision deck)


  // .then() version
  fetch(url).then(r => r.json()).then(d => console.log(d)).catch(e => console.log(e));


  // async / await version
  async function load() {
      try {
          const r = await fetch(url);                      // pause until the response arrives
          const d = await r.json();                        // pause until the body is parsed
          console.log(d);
      } catch (err) {
          console.log("Failed:", err);                     // any rejected await lands here
      }
  }




▸ Sequential vs parallel awaiting

            timings measured in Node


  const wait = (ms, v) => new Promise(res => setTimeout(() => res(v), ms));


  // SLOW: one after another -> total = 1000 + 1500 = ~2500 ms

--- PDF page 62 ---
const a = await wait(1000, "A");
  const b = await wait(1500, "B");                          // does not even start until a is done


  // FAST: start both, wait for both -> total = slower one = ~1500 ms
  const [c, d] = await Promise.all([wait(1000, "C"), wait(1500, "D")]);



Sequential is right when step 2 needs step 1's result (you need the user before you can load the user's posts).
For independent requests use Promise.all . The classic trap is await inside a loop:

             await-in-a-loop trap and its fix


  // serialises independent requests (slow)
  for (const id of ids) { await fetch(`/api/item/${id}`); }


  // build the promises first, await once (fast)
  const results = await Promise.all(ids.map(id => fetch(`/api/item/${id}`)));



 The four common async mistakes (LEC 3
                                                       Symptom                                       Fix
 slide 49)

 Forgetting await                                      Variable holds Promise { <pend‐               Add await (check this first!)
                                                       ing> }

 No error handling                                     Rejection fails silently / crashes far away   Wrap awaits in try/catch or add
                                                                                                       .catch

  await in a loop                                      Independent jobs run one by one                 Promise.all

 Awaiting a non-Promise                                Harmless, pointless ( await 5 gives           Only await things that return Promises
                                                       5)



   ✏️ PREDICT THE OUTPUT ORDER
               order.js


     console.log("1");
     setTimeout(() => console.log("2"), 0);
     Promise.resolve().then(() => console.log("3"));
     (async () => {
        console.log("4");
        await null;
        console.log("5");
     })();
     console.log("6");



   🔓 Answer key: 1 4 6 3 5 2 — sync lines first (1, 4 because an async function runs synchronously until its first await, then 6); then mi‐
   crotasks in queue order (3, then the code after await: 5); then the timer task (2). Verified in Node.

--- PDF page 63 ---
▸ The package-delivery question

  ✍️ HOW TO WRITE THIS IN THE EXAM
  Four parts score full marks: (1) say what the original prints and why "bye!" comes first; (2) Promise ver‐
  sion: each step returns new Promise and calls resolve() instead of callback() , chained with
    .then() and one .catch() ; (3) async/await version reusing those functions inside try/catch ; (4) the
  output with timings (2 s, 6 s, 9 s).



   PYQ       Final 2024-25 · Q2(a)                                                                            10 M


  Given a package delivery process which follows sequential execution with callbacks: Step 1: Placing
  the order for a package. Step 2: Processing the payment for the order. Step 3: Preparing the package
  in the warehouse. Final Step: Delivering the package to the customer.
  Problem 1: Convert the above package delivery process using Promises to handle the asynchronous
  flow.
  Problem 2: Using the solution from Problem 1 where Promises were used, now convert the package
  delivery scenario using Async/Await for better readability and easier handling of asynchronous tasks.

    function step1(callback) {
      setTimeout(function () {
        console.log("Step 1: Order placed for the package");
          callback();
        }, 2000);
    }
    function step2(callback) {
        setTimeout(function () {
          console.log("Step 2: Payment processed for the package");
          callback();
        }, 4000);
    }
    function step3(callback) {
      setTimeout(function () {
        console.log("Step 3: Package is being prepared in the warehouse");
        callback();
      }, 3000);
    }
    function finalStep() {
      console.log("Step 4: Package delivered to the customer! Enjoy your item.");
    }
    // Using callbacks to ensure steps are executed in sequence
    step1(() => {
      step2(() => {
        step3(() => {
          finalStep();
        });
      });
    });
    console.log("Other services are running in the background... bye!");



   ✓    MODEL ANSWER — WRITE THIS

--- PDF page 64 ---
WHAT THE GIVEN (CALLBACK) CODE PRINTS

    Time
    (cumula‐         Output                                  Why
    tive)

    ≈0s                 Other services are running in the     step1 only schedules a timer and returns at once; the last
                     background... bye!                       console.log is synchronous, so it runs first

    ≈2s                 Step 1: Order placed for the         2000 ms timer
                     package

    ≈6s                 Step 2: Payment processed for the    2 + 4 s (step 2 starts only after step 1)
                     package

    ≈9s                 Step 3: Package is being prepared    6+3s
                     in the warehouse

    ≈9s                 Step 4: Package delivered to the     runs immediately after step 3
                     customer! Enjoy your item.


  The steps are correct but nested three levels deep (callback hell): hard to read, and there is no single place
  to handle a failure.

  PROBLEM 1 — PROMISE VERSION

  Each step now returns a Promise and calls resolve() where it used to call callback() . Step 2 also
  shows the reject() path (a declined payment).

               delivery-promises.js


     function step1() {
         return new Promise((resolve, reject) => {
            setTimeout(() => {
               console.log("Step 1: Order placed for the package");
               resolve();                                     // step finished successfully
            }, 2000);
         });
     }


     function step2() {
         return new Promise((resolve, reject) => {
            setTimeout(() => {
               const paymentOk = true;                        // result from the payment gateway
               if (!paymentOk) {
                   reject(new Error("Payment declined"));    // failure path
                   return;
               }
               console.log("Step 2: Payment processed for the package");
               resolve();
            }, 4000);
         });

--- PDF page 65 ---
}


     function step3() {
         return new Promise((resolve, reject) => {
            setTimeout(() => {
               console.log("Step 3: Package is being prepared in the warehouse");
               resolve();
            }, 3000);
         });
     }


     function finalStep() {
         console.log("Step 4: Package delivered to the customer! Enjoy your item.");
     }


     // Each .then() waits for the previous Promise to resolve -> steps stay in order
     step1()
         .then(() => step2())          // returning the Promise makes the chain wait for it
         .then(() => step3())
         .then(() => finalStep())
         .catch((err) => console.error("Delivery failed:", err.message))        // one handler for every
     step
         .finally(() => console.log("Order process closed."));


     console.log("Other services are running in the background... bye!");



  How it works: step1() returns a pending Promise; when its timer fires it logs and resolves; the first
    .then calls step2() and returns its Promise, so the next .then waits for it, and so on. The chain is flat,
  and if any step calls reject() the remaining .then s are skipped and .catch runs. ( .then(step2) is a
  valid shorter form.)

  PROBLEM 2 — ASYNC/AWAIT VERSION (REUSES STEP1, STEP2, STEP3, FINALSTEP FROM
  PROBLEM 1)

               delivery-async.js


     // step1(), step2(), step3() and finalStep() exactly as in Problem 1


     async function deliverPackage() {
         try {
            await step1();           // pauses THIS function ~2 s; other code keeps running
            await step2();           // then ~4 s more
            await step3();           // then ~3 s more
            finalStep();             // runs only after all three have resolved
         } catch (err) {
            console.error("Delivery failed:", err.message);     // any reject() lands here
         } finally {

--- PDF page 66 ---
console.log("Order process closed.");
         }
     }


     deliverPackage();
     console.log("Other services are running in the background... bye!");



  OUTPUT OF BOTH CONVERTED VERSIONS (VERIFIED BY RUNNING THEM)

               console


     [0 s] Other services are running in the background... bye!
     [2 s] Step 1: Order placed for the package
     [6 s] Step 2: Payment processed for the package
     [9 s] Step 3: Package is being prepared in the warehouse
     [9 s] Step 4: Package delivered to the customer! Enjoy your item.
     [9 s] Order process closed.


     If paymentOk = false:
     [0 s] Other services are running in the background... bye!
     [2 s] Step 1: Order placed for the package
     [6 s] Delivery failed: Payment declined
     [6 s] Order process closed.



  "bye!" still prints first in both versions: a Promise chain and an await pause only the chain/async function,
  never the code after the call. (The [time] labels are added for explanation; the program itself prints only
  the messages.)

                          Callbacks                           Promises                         async/await

    Shape                 Nested pyramid                      Flat .then chain                 Top-to-bottom like sync code

    Errors                Handled at every level              One .catch()                      try/catch

    Readability           Poor                                Good                             Best


  Conclusion: Promises remove the nesting and centralise error handling; async/await is syntax over the
  same Promises that makes the sequence read like ordinary step-by-step code.

  🎯 Marking scheme guess: 1 M explain original output/order · 4 M Problem 1 (each step returns new Promise with resolve/reject + .then
  chain + .catch) · 4 M Problem 2 (async function, await each step, try/catch) · 1 M output and comparison




   PYQ        Final 2024-25 · Q3(a)   Re-Exam 2023-24 · Q3(a)                                                                      10 M


  2024-25: What is a Callback function? What are the different types of JavaScript functions explaining
  with sample code in brief?

--- PDF page 67 ---
2023-24: What is Async Await? What are the different types of JavaScript functions explaining explain
  any three with code?

   ✓       MODEL ANSWER — WRITE THIS

  Write part A for the 2024-25 wording, part B for the 2023-24 wording, and part C for both (for "any three", expand three of the
  types with code).


  A. CALLBACK FUNCTION

  A callback function is a function passed as an argument to another function, which calls it ("calls it back")
  later, usually when a task completes or an event happens. Callbacks let JavaScript run code after asyn‐
  chronous work (timers, events, server responses) without blocking. They can be synchronous
  ( arr.forEach(cb) ) or asynchronous ( setTimeout(cb, 1000) ). Too many nested callbacks cause call‐
  back hell, which Promises and async/await solve.

                 callback


       function downloadFile(name, callback) {
           console.log("Downloading", name);
           setTimeout(() => callback(name), 1000);              // call back after 1 s
       }
       downloadFile("notes.pdf", function (file) {
           console.log(file, "downloaded");                     // the callback
       });



  B. ASYNC / AWAIT

  async/await (ES2017) is syntax built on Promises for writing asynchronous code that reads like syn‐
  chronous code. The async keyword makes a function always return a Promise; inside it, await pauses
  that function until a Promise settles and returns its value, without blocking the rest of the program. Errors
  from rejected Promises are caught with try/catch .

                 async/await


       const wait = ms => new Promise(resolve => setTimeout(resolve, ms));


       async function placeOrder() {
           try {
               console.log("Order placed");
               await wait(2000);                                 // pause 2 s (page not frozen)
               console.log("Order shipped");
           } catch (err) {
               console.log("Error:", err.message);
           }
       }
       placeOrder();

--- PDF page 68 ---
C. TYPES OF JAVASCRIPT FUNCTIONS

    Type                                              Sample code

    1. Function declaration (named, hoisted)           function add(a, b) { return a + b; }

    2. Function expression                             const mul = function (a, b) { return a * b; };

    3. Anonymous function                              setTimeout(function () { console.log("hi"); }, 1000);

    4. Arrow function (ES6)                            const square = n => n * n;

    5. IIFE                                            (function () { console.log("runs at once"); })();

    6. Callback function                               [1, 2, 3].forEach(n => console.log(n));

    7. Higher-order function                           const twice = f => x => f(f(x));

    8. Constructor function                            function Car(m) { this.model = m; } new Car("i20");

    9. Async function                                  async function load() { const r = await fetch(url); }

    10. Generator function                             function* ids() { yield 1; yield 2; }


  Three explained with code:

              declaration · arrow · IIFE


     // 1. Function declaration: named, reusable, hoisted (callable before its definition)
     console.log(area(5, 4));                                   // 20
     function area(l, b) {
         return l * b;
     }


     // 2. Arrow function: short ES6 syntax, implicit return, no own `this`
     const isEven = n => n % 2 === 0;
     console.log([1, 2, 3, 4].filter(isEven)); // [2, 4]


     // 3. IIFE: defined and executed immediately; its variables stay private
     (function () {
         const appName = "IMAP";
         console.log(appName, "started");                       // IMAP started
     })();



  Conclusion: declarations and expressions define reusable logic; arrow functions give concise callbacks;
  IIFEs isolate scope; callbacks, Promises and async functions handle asynchronous work, with async/await
  being the most readable.

  🎯 Marking scheme guess: 2 M definition + example of callback (2024-25) or async/await (2023-24) · 2 M list of function types · 6 M code
  + explanation (3 types × 2 M for 2023-24; ~1 M each for 6+ types "in brief" for 2024-25)

--- PDF page 69 ---
1.18 The DOM, events and event delegation
📚 Sources: Unit 1 Notes §7.7–7.8   LEC 3 (Git · Frameworks · JS) slides 39–43   Lab 3 Manual (JS · Git) §3–4


The DOM (1.2) is the live tree of objects the browser builds from your HTML. Once JavaScript holds a reference
to an element, it can read and change it instantly, with no page reload.

 Task                   Code                                                                    Notes

 Select one             document.querySelector(".btn") · document.get‐                          Any CSS selector; first match or
                        ElementById("nav")                                                       null

 Select many            document.querySelectorAll("li")                                         A list you can loop with
                                                                                                 for...of / forEach

 Change text            el.textContent = "Hi"                                                   Safest way to read/write words

 Change HTML            el.innerHTML = "<b>Hi</b>"                                              Never with user input: it can inject a
                                                                                                working script (XSS)

 Change style           el.classList.add/remove/toggle("active") ·                              Prefer classes; style is inline and
                        el.style.color = "teal"                                                 camelCased

 Attributes / form      img.setAttribute("src", url) · input.value                               value is always a string
 values

 Create / add /         document.createElement("li") · list.append(li) /                        How dynamic lists and chat messages
 remove                 appendChild · li.remove()                                               appear

 Listen                 el.addEventListener("click", handler)                                   Handler receives an event object e



 Event                              Fires when                             Event object                  Use

  click                             Button/link pressed                     e.target                     The element the event hap‐
                                                                                                         pened on

  input / change                    Field changes (every key / on           e.target.value               The current text
                                    commit)

  submit                            A form is sent                          e.preventDefault(            Stop the browser's default
                                                                           )                             action

  keydown                           A key goes down                         e.key                        Which key

  blur / focus                      Field loses / gains focus               e.stopPropagation            Stop bubbling to parents
                                                                           ()

  mouseover ,                       Pointer enters / HTML fully             e.type                       The event's name
  DOMContentLoaded                  parsed


           counter.html — select, listen, update state, render (LEC 3 slide 43)


  <button id="inc">+1</button>
  <span id="out">0</span>
  <script>
     let count = 0;                                                  // 3. state lives in a variable
     const out = document.querySelector("#out");                     // 1. select
     document.querySelector("#inc")

--- PDF page 70 ---
.addEventListener("click", () => {                                // 2. listen
           count++;                                                       // 3. update state
           out.textContent = count;                                       // 4. reflect it in the DOM
        });
  </script>



  🧠 WHY THIS MATTERS LATER
  "State lives in a variable; the DOM just displays it." This update state → render loop is exactly what React
  automates in Unit 4.



▸ Bubbling and event delegation
An event on a child bubbles up through every ancestor. So instead of one listener per <li> , attach one listen‐
er to the parent and use event.target (with closest() ) to find which child was clicked. It also works for
children added later, because the listener lives on the parent.

           todo.js — creating items + one delegated listener (Lab 3 §3–4)


  const list       = document.querySelector("#todo");
  const input = document.querySelector("#task");


  document.querySelector("#add").addEventListener("click", () => {
     const li = document.createElement("li");                           // create
     li.textContent = input.value;                                      // fill (textContent: safe)
     li.classList.add("item");                                          // style
     list.append(li);                                                   // add to the page
     input.value = "";
  });


  list.addEventListener("click", (event) => {                           // ONE listener for all items, even future ones
     const item = event.target.closest("li");                           // walk up to the nearest <li>
     if (!item) return;                                                 // clicked the gap between items
     item.classList.toggle("done");                                     // strike it through
  });




    1.19 Form validation with JavaScript (PYQ)
📚 Sources: Lab 1 Manual (HTML) §7          LEC 3 (Git · Frameworks · JS) slides 39–42   Lab 3 Manual (JS · Git) §3

 Not in your files — added from standard references



    🚨 NOT IN YOUR STUDY MATERIAL · 20 MARKS · RE-EXAM 2023-24 Q2(A) + FINAL 2024-25
      Q2(B)

--- PDF page 71 ---
What's missing: Lab 1 shows form tags and the HTML5 attributes ( required , pattern , min / max ),
      and LEC 3 lists the submit event, but no file contains a JavaScript validation script or an index.html +
      test.js pair.

      Verdict: MUST LEARN. The same 10-mark question appeared in both older papers (fields
      name/age/email, then name/salary/email). One memorised template below answers any field combination.



▸ Three layers of validation

                          1 HTML5 attributes                     2 JavaScript (test.js)                 3 Server (Django)
                      required, type, min/max, pattern
                                                         →     custom rules, inline messages
                                                                                                →          final authority



HTML5 attributes are the first line of defence (free, no code). JavaScript adds rules HTML cannot express (let‐
ters only, a salary greater than zero, custom wording) and shows messages next to each field before anything is
sent. But anyone can switch JavaScript off or send a request with DevTools/curl, so the server must always vali‐
date again (Django forms/serializers, Unit 2).


▸ The recipe

 1         index.html: a <form> where every input has an id , plus an empty <span> for its error message; link
            test.js at the end of <body> .


 2         One small function per field that returns "" if valid or the error text if not.

 3         Listen for submit on the form; run every check and show each message.

 4         If anything failed, call event.preventDefault() so the form is not sent.

 5         If all passed, show a success message (or let the form submit to the server).


▸ Regular expressions you need

 Piece                   Means                           Piece                           Means

  / ... /                A regex literal                     ^ / $                       Start / end of the text (match the whole value)

  [A-Za-z ]              One letter or a space               [^\s@]                      Any char except whitespace and @

  +                      One or more of the previous         {2,}                        Two or more

  \.                     A literal dot                       regex.test(str)             Returns true / false


Email pattern used below: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ = "some name charac‐
ters, an @, a domain, a dot, and an ending of 2+ letters". Tested in Node: asha.rao@mail.co.in ✓,
 asha@example.com            ✓, asha@mail ✗, @mail.com ✗, asha@@mail.com ✗, asha rao@mail.com ✗, a@b.c ✗
(ending too short).

--- PDF page 72 ---
PYQ        Final 2024-25 · Q2(b)   Re-Exam 2023-24 · Q2(a)                                                   10 M


  2024-25: How do you create an HTML form with JavaScript validation for the fields: name, salary, and
  email? Please provide the code for both index.html (HTML form) and test.js (JavaScript validation
  logic) that checks the validity of each field (name, salary, email) and handles user input validation.
  2023-24: Create an HTML form with JavaScript validation for name, age and email fields? Please pro‐
  vide both the HTML code (index.html) and the JavaScript code (test.js) for the form validation, and
  write the code for validation of each field.

   ✓    MODEL ANSWER — WRITE THIS

  Idea. index.html holds the form (with HTML5 attributes as a first check and an error <span> under each
  field); test.js listens for the form's submit event, validates every field, shows inline error messages, blocks
  submission with preventDefault() if any field is invalid, and shows a success message otherwise. The
  answer covers name, age, salary and email: in the exam, keep age for the 2023-24 wording or salary for
  the 2024-25 wording and delete the other field's three parts (its HTML block, its function, its line in
    validators ).

                index.html


       <!DOCTYPE html>
       <html lang="en">
       <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>Employee Registration</title>
         <style>
             body     { font-family: Arial, sans-serif; max-width: 420px; margin: 30px auto; }
             .field { margin-bottom: 14px; }
             label    { display: block; font-weight: bold; margin-bottom: 4px; }
             input    { width: 100%; padding: 8px; box-sizing: border-box; }
             input.invalid { border: 2px solid crimson; }
             .error     { color: crimson; font-size: 0.85rem; }
             .success { color: green; font-weight: bold; }
         </style>
       </head>
       <body>
         <h2>Employee Registration</h2>


         <!-- novalidate: switch off the browser's pop-up bubbles so test.js shows its own messages
       -->
         <form id="regForm" action="#" method="post" novalidate>
             <div class="field">
              <label for="name">Name</label>
              <input type="text" id="name" name="name" required>
              <span class="error" id="nameError"></span>
             </div>

--- PDF page 73 ---
<div class="field">
             <label for="age">Age</label>
             <input type="number" id="age" name="age" min="18" max="60" required>
             <span class="error" id="ageError"></span>
           </div>


           <div class="field">
             <label for="salary">Salary (₹)</label>
             <input type="number" id="salary" name="salary" min="1" step="0.01" required>
             <span class="error" id="salaryError"></span>
           </div>


           <div class="field">
             <label for="email">Email</label>
             <input type="email" id="email" name="email" required>
             <span class="error" id="emailError"></span>
           </div>


           <button type="submit">Submit</button>
           <p id="formMsg" class="success"></p>
         </form>


         <script src="test.js"></script>
     </body>
     </html>



              test.js


     // test.js : client-side validation for index.html


     // ---- 1. one small function per field: return "" if valid, else the error text ----
     function validateName(value) {
         if (value === "") return "Name is required.";
         if (!/^[A-Za-z ]+$/.test(value)) return "Name can contain only letters and spaces.";
         if (value.length < 2) return "Name must be at least 2 characters.";
         return "";
     }


     function validateAge(value) {
         if (value === "") return "Age is required.";
         const age = Number(value);
         if (!Number.isInteger(age)) return "Age must be a whole number.";
         if (age < 18 || age > 60) return "Age must be between 18 and 60.";
         return "";
     }

--- PDF page 74 ---
function validateSalary(value) {
          if (value === "") return "Salary is required.";
          const salary = Number(value);
          if (Number.isNaN(salary)) return "Salary must be a number.";
          if (salary <= 0) return "Salary must be greater than 0.";
          return "";
     }


     function validateEmail(value) {
          const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
          if (value === "") return "Email is required.";
          if (!emailPattern.test(value)) return "Enter a valid email, e.g. asha@example.com";
          return "";
     }


     // ---- 2. map each input id to its checker ----
     const validators = {
          name: validateName,
          age: validateAge,
          salary: validateSalary,
          email: validateEmail
     };


     // ---- 3. run one field's check and show / clear its inline message ----
     function checkField(id) {
          const input = document.getElementById(id);
          const message = validators[id](input.value.trim());
          document.getElementById(id + "Error").textContent = message;
          input.classList.toggle("invalid", message !== "");
          return message === "";
     }


     // ---- 4. live feedback: check a field as soon as the user leaves it ----
     for (const id in validators) {
          document.getElementById(id).addEventListener("blur", () => checkField(id));
     }


     // ---- 5. final check on submit ----
     const form = document.getElementById("regForm");
     const formMsg = document.getElementById("formMsg");


     form.addEventListener("submit", (event) => {
          let allValid = true;
          for (const id in validators) {
           if (!checkField(id)) allValid = false;      // check EVERY field, so all errors show

--- PDF page 75 ---
}


        if (!allValid) {
            event.preventDefault();                                // stop the form from being sent
            formMsg.textContent = "";
            return;
        }


        event.preventDefault();                                    // demo only (no server): stay on this page
        formMsg.textContent = "Form submitted successfully!";
        form.reset();
     });



  WHAT EACH CHECK DOES

    Field     Rules (in order)                                    Code that enforces it

    Name      Required → letters and spaces only → at least 2      value === "" · /^[A-Za-z ]+$/.test(value) ·
              characters                                           value.length < 2

    Age       Required → whole number → between 18 and             Number.isInteger(Number(value)) · age < 18 ||
              60                                                  age > 60

    Salary    Required → a number → greater than 0                 Number.isNaN(salary) · salary <= 0

    Email     Required → matches name@domain.ext                   emailPattern.test(value)


  HOW IT WORKS

    1. novalidate turns off the browser's pop-up bubbles so test.js shows its own messages; the HTML5
       attributes ( required , type="email" , min / max ) stay as documentation and as the first line of de‐
       fence if novalidate is removed.
    2. .trim() removes spaces at both ends, so a field of only spaces counts as empty.
    3. checkField(id) runs the right validator, writes the message into id + "Error" (e.g. nameError )
       with textContent , and adds a red border via classList.toggle("invalid", ...) .
    4. The blur listeners give instant feedback when the user leaves a field.
    5. On submit , every field is checked (so all errors show at once). If any fails, event.preventDefault()
       stops the submission. If all pass, a success message is shown; with a real backend, delete the second
        preventDefault() and the browser sends the data to the form's action URL, where the server vali‐
       dates again.

  TEST CASES (RUN IN CHROME)

    Input (name / age / salary /
                                       Messages shown
    email)

    all empty                          Name is required · Age is required · Salary is required · Email is required (not submitted)

    Asha123 / 17 / -5 / asha@          Name can contain only letters and spaces · Age must be between 18 and 60 · Salary must be
                                       greater than 0 · Enter a valid email

--- PDF page 76 ---
Input (name / age / salary /
                                         Messages shown
    email)

    A / 25.5 / abc / asha                Name must be at least 2 characters · Age must be a whole number · Salary is required (a
    example.com                           type="number" box refuses "abc", so the value arrives empty) · Enter a valid email

    Asha Rao / 61 / 0 / a@b.c            (name OK) · Age must be between 18 and 60 · Salary must be greater than 0 · Enter a valid
                                         email

    Asha Rao / 25 / 45000 /              No errors → "Form submitted successfully!" and the form is reset
    asha.rao@example.com



  🎯 Marking scheme guess: 3 M index.html (form, labels, ids, error spans, script link) · 5 M test.js (one check per field with correct logic,
  submit listener, preventDefault, messages) · 2 M explanation / HTML5 attributes / server-side note




  ⚠️ COMMON MISTAKES
       Linking test.js in the <head> without defer : getElementById returns null because the form
       does not exist yet.
       Forgetting event.preventDefault() : the page submits/reloads and your messages vanish.
       Comparing numbers as strings: input.value is always a string; convert with Number() first
       ( "100" < "20" is true as strings).
       Regex without ^ and $ : /[A-Za-z ]+/ also matches "Asha123" because it finds letters somewhere.
       Writing only HTML5 attributes when the question says "JavaScript validation": the examiner wants
       test.js.


  ✍️ SHORT VERSION IF TIME IS TIGHT (THE CLASSIC TEXTBOOK STYLE)
  Some students write <form name="myForm" onsubmit="return validateForm()"> and a
    validateForm() that uses alert("Name must be filled out"); return false; per field and
    return true; at the end. It is accepted, but the version above (addEventListener, inline messages, one
  function per field) is the modern answer and scores better.


   ✏️ FILL IN THE BLANKS — VALIDATION
              complete test.js


     const form = document.______("regForm");                                            // 1
     form.______("submit", (event) => {                                                  // 2
        const email = document.getElementById("email").value.______();                                 // 3: strip spaces
        const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!pattern.______(email)) {                                                   // 4
            document.getElementById("emailError").______ = "Invalid email";                              // 5
            event.______();                                                              // 6: stop submission
        }
        const salary = ______(document.getElementById("salary").value);                                // 7: string -> number
        if (Number.isNaN(salary) || salary ______ 0) { /* error */ }                                    // 8
     });

--- PDF page 77 ---
🔓 Answer key: 1 getElementById · 2 addEventListener · 3 trim · 4 test · 5 textContent · 6 preventDefault · 7 Number · 8 <=


    1.20 Git from zero (PYQ)
📚 Sources: Unit 1 Notes §8.1–8.4, §8.7, §8.9       LEC 3 (Git · Frameworks · JS) slides 3–11        Lab 3 Manual (JS · Git) §7

 One-Shot Revision · Unit 1 + Appendix      Complete Revision deck · U1 slide 10


  🧠 START FROM ZERO
  Without version control a project becomes a folder of guesses: app.js , app_final.js ,
    app_final_v2.js , app_final_REAL.js … Which one works? Who changed what? Version control re‐
  places that with one folder that remembers its entire history: every version kept, every change labelled with
  why, any earlier point restorable in seconds, and a whole team working in parallel without overwriting each
  other.


Git is a free, open-source, distributed version control system created by Linus Torvalds in 2005 (for Linux ker‐
nel development). "Distributed" means every developer's copy (clone) contains the full history, so Git works fully
offline and every clone is a backup.

                             Centralised VCS (e.g. SVN)                              Distributed VCS (Git)

 History lives               Only on the central server                              On every developer's machine

 Offline work                No commits without the server                           Commit, branch, view history offline

 Server dies                 History lost (unless backed up)                         Any clone can restore it



▸ Git's mental model: snapshots, not differences

                                                                                                                                 HEAD

                     c1                     c2                        c3                    c4                       c5


                   initial               add nav                   style hero             fix bug                add footer



        Each commit is a full snapshot ("photo") of the project; each points back to its parent. HEAD = where you are now (LEC 3 slide 5).


Every commit stores: an ID (a SHA hash such as a1b2c3d ; 7 characters are enough to refer to it), author, time‐
stamp, message, and a pointer to its parent commit.

 Git                                                      GitHub

 A program installed on your computer                     A website that hosts Git repositories online

 Works offline; tracks versions and history               Needs internet; holds the shared team copy (the remote)

 By Linus Torvalds, 2005; free and open                   Adds pull requests, code review, issues, Actions (CI/CD); alternatives GitLab,
 source                                                   Bitbucket

--- PDF page 78 ---
💡 THINK OF IT LIKE
  Git is the camera that takes the snapshots; GitHub is the shared album you upload them to.



▸ The four places a change lives

   Working directory    →            Staging area           →                Local repository        →           Remote (GitHub)
       files you edit   git add   picked for next commit    git commit     commits on your machine   git push    shared copy online



Going back the other way: git pull (or fetch ) brings remote commits down; git restore throws away
working-directory edits. The staging area exists so each commit is one clean, logical change rather than a
dump of every edit. Running git commit before git add commits nothing.

           first session (Lab 3 §7)


  # once per machine: sign your commits
  git config --global user.name          "Asha Rao"
  git config --global user.email "asha@example.com"


  git init                                        # start tracking this folder (creates hidden .git)
  git status                                      # what changed? what is staged? (run it constantly)
  git add profile-card.html                       # stage one file                (git add .     = stage everything)
  git commit -m "Add profile card HTML skeleton"
  git log --oneline                               # history, one line per commit (--graph for a tree)



 Command                          Does                                   Command                          Does

  git diff                        Unstaged edits vs last commit          git diff --staged                What you are about to
                                                                                                          commit

  git show <id>                   Everything one commit changed          git blame file                   Who last changed each
                                                                                                          line

  git restore file                Discard uncommitted edits              git reset file                   Unstage, keep the edits

  git stash / git stash           Shelve unfinished work / bring it      git log --oneline --             Compact history tree
 pop                              back                                   graph



▸ .gitignore

           .gitignore (LEC 3 slide 11)


  # dependencies
  node_modules/
  # secrets and environment
  .env
  *.key
  # build output and logs
  dist/
  *.log

--- PDF page 79 ---
# exception: DO track this one file
  !keep.log
  # OS / editor cruft
  .DS_Store
  .vscode/



Add it before the first commit: it only stops untracked files from being picked up; a file already committed
stays in history. Never commit passwords, API keys or node_modules .


▸ Undoing things: restore vs reset vs revert

  Command                   Undoes                                                                  Use it for

   git restore              Throws away uncommitted edits (back to the last commit)                 A bad edit never committed
  <file>

   git reset                Moves HEAD back; --soft keeps changes staged, --hard                    A local commit nobody else
                            deletes them. Rewrites history.                                         has seen

   git revert               Creates a new commit that undoes an old one. History preserved.         A commit already pushed
  <id>                                                                                              and shared



  🔑 GOLDEN RULE
   Never rewrite history that others have already pulled. Once pushed and shared, undo with revert (adds a
  commit), never reset or a force-push (erases commits and breaks teammates' copies).



   PYQ       Final 2025-26 · Q6(A)   ★ LATEST                                                                              8M


  Explain in detail what Git is and why developers use it. Describe at least four key advantages of using
  Git in software projects — for example, collaboration, version history, branching, and backup/recov‐
  ery. Support each point with a short, practical example.

   ✓   MODEL ANSWER — WRITE THIS

  What Git is. Git is a free, open-source distributed version control system, created by Linus Torvalds in
  2005, that records the history of a project as a series of commits. Each commit is a complete snapshot of
  all files plus an ID (SHA hash), author, timestamp, message and a link to its parent. Changes move from the
  working directory → staging area ( git add ) → local repository ( git commit ) → remote such as GitHub
  ( git push ). Because it is distributed, every developer has the full history locally.

  Why developers use it: instead of copies like app_final_v2.js , one repository keeps every version,
  records who changed what and why, lets a team work in parallel safely, and allows any earlier state to be
  restored in seconds.

  KEY ADVANTAGES WITH EXAMPLES

    1. Collaboration. Many developers work on the same codebase at once; Git merges their work and flags
       conflicts instead of silently overwriting. Example: in our Django project, Asha builds the login page and

--- PDF page 80 ---
Ravi the cart on separate branches; both push to GitHub and open pull requests, which teammates re‐
       view before merging into main .
    2. Version history and accountability. Every change is a commit with a message, author and time.
       Example: the checkout page broke yesterday; git log --oneline and git diff show the commit
       "Change tax calculation", and git blame shows who changed that line, so the bug is found in
       minutes.
    3. Branching. A branch is a lightweight pointer that lets you build a feature in isolation while main stays
       stable and deployable. Example: git switch -c feature/dark-mode ; experiment freely; if it fails,
       delete the branch; if it works, git merge it.
    4. Backup and recovery. Every clone is a full copy of the repository, and the remote on GitHub is another
       copy. Example: a laptop is stolen; git clone https://github.com/team/shop.git on a new machine
       restores everything. A bad commit that was already pushed is undone safely with git revert <id> ;
       an unwanted local edit with git restore .
    5. Offline speed and safe experimentation (extra). Commits, diffs and history work without internet; tags
       mark releases ( v1.0.0 ) so you can always rebuild or roll back to exactly what was shipped.

  Conclusion. Git makes software development traceable, parallel and recoverable; combined with GitHub it
  is the standard foundation for team workflows, code review and CI/CD.

  🎯 Marking scheme guess: 2 M what Git is (distributed VCS, commits/snapshots, working dir → staging → repo → remote) + why · 6 M
  four advantages × (1 M point + 0.5 M practical example)




   ✏️ COMMAND COMPLETION — EVERYDAY GIT
    1. Turn the current folder into a repository: git
    2. Stage every changed file: git add
    3. Save the staged snapshot with a message: git commit                                            "Add navbar"

    4. Show history, one line per commit: git log
    5. See what you are about to commit: git diff
    6. Undo a commit that is already on GitHub, safely: git                                        a1b2c3d

    7. Throw away uncommitted changes to style.css: git                                           style.css

    8. Set your name once per machine: git config                                         user.name "Asha"


   🔓 Answer key: 1 init · 2 . (dot) · 3 -m · 4 --oneline · 5 --staged · 6 revert · 7 restore · 8 --global


    1.21 Branches, merge vs rebase, cherry-pick, tags (PYQ)
📚 Sources: Unit 1 Notes §8.5–8.6, §8.8         LEC 3 (Git · Frameworks · JS) slides 12–15, 18      Lab 3 Manual (JS · Git) §8–9

 Tags & cherry-pick: not in your files — added from standard references


    🚨 NOT IN YOUR STUDY MATERIAL · PART OF 12 MARKS · FINAL 2025-26 Q6(B) + Q6(C)
    What's missing: branching, merge conflicts and merge vs rebase are covered (Unit 1 Notes §8.5–8.8,
    LEC 3). But git tag and git cherry-pick appear in none of your 22 study files, and the newest pa‐
    per asked for both ("describe what a tag is…", "explain what git cherry-pick does and give one use

--- PDF page 81 ---
case").

    Verdict: MUST LEARN. Each is a 2–3 mark chunk inside the latest paper's Git question and takes 15
    minutes to learn. Without them you cap Q6(B) and Q6(C) at about two-thirds.



▸ What a branch is
A branch is simply a movable pointer to a commit, not a copy of the project. When you commit on a branch,
its pointer moves forward. Creating a branch is therefore instant and cheap, and lets several features be built in
parallel while main stays untouched and deployable.

                        git switch -c feature/login                                                      merge commit

                                                                                                                          main




                                               feature/login commits

                          Branch off main, commit on the branch, merge back when finished (LEC 3 slide 12).


 Command                                                                          Does

  git branch / git branch -a                                                      List local / all branches (current one marked *)

  git branch fix-footer                                                           Create a branch without switching

  git switch -c add-nav (older: git checkout -b add-nav )                         Create a branch and move onto it

  git switch main (older: git checkout main )                                     Move to an existing branch

  git merge add-nav                                                               Bring add-nav's commits into the current branch

  git branch -d add-nav                                                           Delete a merged branch


Fast-forward vs three-way merge. If main has not moved since you branched, Git just slides the main
pointer forward (fast-forward, no new commit). If both moved, Git creates a merge commit with two parents
( --no-ff forces a merge commit even when a fast-forward was possible).


▸ Merge conflicts: Git asking a question
Git merges automatically when the branches changed different lines. A conflict happens only when both
changed the same lines differently. Real output from a test repository:

           terminal + style.css during a conflict


  $ git merge feature/navy
  Auto-merging style.css
  CONFLICT (content): Merge conflict in style.css
  Automatic merge failed; fix conflicts and then commit the result.


  body {
  <<<<<<< HEAD
     color: crimson;                 <- your version (current branch, main)

--- PDF page 82 ---
=======
      color: navy;                     <- their version (branch being merged)
  >>>>>>> feature/navy
  }



 1          See where: git status lists conflicted files ("both modified").

 2          Open and choose: keep the right lines (one side, the other, or a mix) and delete all three marker lines.
            VS Code offers Accept Current / Incoming / Both buttons.

 3          Stage it: git add style.css tells Git this file is resolved.

 4          Finish: git commit completes the merge (or git merge --abort to cancel it all).


▸ Merge vs rebase

         git merge — combines histories with a new merge commit


              A            B              C                      M      main

                                  D                E

                                      D, E keep their IDs; M has two parents


         git rebase main — replays the feature commits on top of main


              A            B              C                 D'                  E'       main (linear)

                                  D                E                                     D', E' = NEW commits (new IDs)


                                                        Redrawn from LEC 3 slide 15.


                   git merge                                               git rebase

  What it         Joins the two histories with a new merge                Re-applies the branch's commits one by one on top of the
  does            commit                                                  target's tip

  History         True, branched history; extra merge commits             Straight, linear history; no merge commit
  shape

  Commit          Unchanged (non-destructive)                             Replayed commits get new IDs (history rewritten)
  IDs

  Pros            Safe on shared branches; preserves exactly              Clean, readable log; easier git log /bisect; can tidy com‐
                  what happened and when                                  mits ( git rebase -i to squash)

  Cons            Log becomes cluttered with merge commits                Dangerous on pushed/shared commits; conflicts may be re‐
                                                                          solved once per replayed commit

  Use when        Bringing a finished feature into main ; any             Updating your own local feature branch with the latest
                  shared branch                                            main before opening a PR

--- PDF page 83 ---
the two ways to bring main's new work into your branch


  git switch feature/login
  git merge main                  # adds a merge commit to feature/login
  # --- or ---
  git rebase main                 # replays feature/login's commits after main's tip
  # conflict during rebase: fix the file, git add it, then
  git rebase --continue           # (or git rebase --abort to go back)




▸ git cherry-pick
 git cherry-pick <commit-id> takes the changes introduced by one specific commit from another branch
and applies them to the current branch as a new commit (new ID, same change and message). You get one
commit, not the whole branch.

           hotfix example (verified in a test repo)


  git switch dev
  git log --oneline               # f5c1bf9 Fix footer overlap         <- needed in main now
                                  # 2d4e8a1 WIP feature                 <- NOT ready for main
  git switch main
  git cherry-pick -x f5c1bf9           # -x adds "(cherry picked from commit f5c1bf9...)" to the message
  git log --oneline -1                  # 8f2fa35 Fix footer overlap          (same change, NEW id)
  # on conflict: fix, git add, git cherry-pick --continue               (or --abort)



Use cases: (1) a bug fix made on a development branch must go to main /a release now, without the unfin‐
ished work around it; (2) you committed to the wrong branch, so cherry-pick it onto the right one; (3) back-port‐
ing a fix to an older release branch. Use sparingly: the same change now exists as two commits.


▸ git tag: naming a release
A tag is a fixed, human-readable name for one specific commit, typically a release version such as v1.0.0 .
Unlike a branch, a tag never moves when new commits are made.

               Lightweight tag             Annotated tag (use for releases)

 Create         git tag v1.0.0              git tag -a v1.0.0 -m "First stable release"

 Stores        Just a name → commit        Tagger name, email, date, message (can be signed)


           working with tags


  git tag                                # list tags
  git tag -a v1.0.0 -m "First stable release"
  git tag -a v0.9.0 9fceb02 -m "Beta"         # tag an older commit
  git show v1.0.0                        # tag details + the commit
  git push origin v1.0.0                 # tags are NOT pushed by default
  git push origin --tags                 # push all tags

--- PDF page 84 ---
git switch --detach v1.0.0                    # look at the code exactly as released (or: git checkout v1.0.0)
  git tag -d v1.0.0                             # delete locally



Why tags for releases: they mark exactly which code was shipped, so you can rebuild it, compare versions
( git diff v1.0.0 v1.1.0 ), roll back, and write release notes. Versions usually follow semantic versioning
 MAJOR.MINOR.PATCH (breaking change . new feature . bug fix). GitHub "Releases" are built on tags, and CI/CD
pipelines often build and tag the Docker image with the same version (Unit 5).

                 Branch                                                       Tag

 Moves?          Yes, forward with every commit                               No, fixed forever

 Purpose         Ongoing work (a feature, a line of development)              Bookmark a point in history (a release)



   PYQ       Final 2025-26 · Q6(B)   ★ LATEST                                                                             6M


  Explain what a branch represents in Git and how it helps developers work on multiple features at
  once. Describe the typical workflow for: - Creating a feature branch - Making changes and commits -
  Merging back to main branch - Handling merge conflicts. In contrast, describe what a tag is and why
  it's often used when marking software releases.

   ✓    MODEL ANSWER — WRITE THIS

  Branch. A branch in Git is a lightweight, movable pointer to a commit; each new commit on the branch
  moves the pointer forward. It represents an independent line of development. Because branches isolate
  work, several developers can build several features at once ( feature/login , feature/cart ) while
    main stays stable and deployable; finished work is merged back, abandoned work is simply deleted.

              typical feature-branch workflow


       # 1. Create a feature branch from an up-to-date main
       git switch main
       git pull origin main
       git switch -c feature/login                     # (or: git checkout -b feature/login)


       # 2. Make changes and commit in small steps
       git add login.html login.js
       git commit -m "Add login form"
       git push -u origin feature/login                # share / back up the branch


       # 3. Merge back into main (directly, or via a Pull Request on GitHub)
       git switch main
       git pull origin main
       git merge feature/login
       git push origin main
       git branch -d feature/login                     # clean up


       # 4. Handling a merge conflict

--- PDF page 85 ---
#      Git stops: "CONFLICT (content): Merge conflict in login.js"
       #      open the file, choose between <<<<<<< HEAD / ======= / >>>>>>> feature/login,
       #      delete the marker lines, then:
       git add login.js
       git commit -m "Merge feature/login, resolve conflict"



  Tag. In contrast, a tag is a permanent, named pointer to one specific commit that never moves.
  Annotated tags ( git tag -a v1.0.0 -m "Release 1.0.0" , then git push origin v1.0.0 ) also store
  the tagger, date and message. Tags are used to mark releases because they record exactly which code was
  shipped as v1.0.0 , making it easy to rebuild, compare ( git diff v1.0.0 v1.1.0 ), roll back, and publish
  GitHub Releases, usually with semantic versioning (MAJOR.MINOR.PATCH).

  🎯 Marking scheme guess: 1.5 M branch definition + parallel features · 3 M workflow (create, commit, merge, conflict resolution) with
  commands · 1.5 M tag definition + why used for releases (vs branch)




   PYQ        Final 2025-26 · Q6(C)   ★ LATEST                                                                                       6M


  Explain the difference between git merge and git rebase. When would you use each? What are the
  pros and cons of each approach? Also explain what git cherry-pick does and give one use case for it.

   ✓       MODEL ANSWER — WRITE THIS

  git merge integrates another branch by creating a new merge commit that has two parents; the original
  commits of both branches stay unchanged, so the history shows exactly how work branched and joined.
  git rebase moves the base of the current branch: it replays the branch's commits one by one on top of
  the tip of the target branch, producing a straight, linear history with no merge commit, but the replayed
  commits are new commits with new IDs (history is rewritten).

  Diagram: merge — A–B–C on main, D–E on feature → new commit M joins C and E. Rebase — feature becomes A–B–C–D′–E′
  (D′, E′ are copies).

                Merge                                              Rebase

    Pros        Non-destructive, safe on shared branches,          Clean linear history, easier to read and debug, no noise from merge
                preserves true history and context                 commits

    Cons        Many merge commits clutter the log                 Rewrites commit IDs: dangerous on pushed/shared branches; may
                                                                   need conflict fixes per commit

    Use         Integrating a finished feature into main , or      Updating your own local, unpushed feature branch with the latest
    when        on any branch others use                            main ( git rebase main ) before a PR


  Rule: never rebase commits that others have already pulled (same golden rule as git reset ).

  git cherry-pick copies the changes of one chosen commit from another branch and applies them to the
  current branch as a new commit: git cherry-pick <commit-id> . Use case: a critical bug fix was com‐
  mitted on the dev branch, which also contains unfinished features; switching to main and running
    git cherry-pick a1b2c3d ships only the fix to production without merging the incomplete work.


  🎯 Marking scheme guess: 2 M merge vs rebase difference (merge commit vs replay/linear, IDs) · 2 M when to use + pros/cons · 2 M cher‐
  ry-pick definition + one use case

--- PDF page 86 ---
✏️ FILL IN THE BLANKS — BRANCHES, CO NFL ICTS , TAGS
    1. Create and switch to feature/cart in one command: git                                          -c feature/cart (older
       form: git checkout                         feature/cart )

    2. The three conflict marker lines are                       ,                    and
    3. After editing a conflicted file you must run git                               file then git

    4. Create an annotated release tag: git tag                                v2.0.0 -m "Release 2.0.0" and upload it:
        git push origin

    5. Copy only commit 7d3e2f1 onto the current branch: git                                        7d3e2f1

    6. Replay your local feature branch on top of main: git                                  main


   🔓 Answer key: 1 switch · -b · 2 <<<<<<< HEAD, =======, >>>>>>> branch-name · 3 add · commit · 4 -a · v2.0.0 (or --tags) · 5
   cherry-pick · 6 rebase




    1.22 GitHub: remotes, clone, push, pull, PRs (PYQ)
📚 Sources: Unit 1 Notes §8.3, §8.10      LEC 3 (Git · Frameworks · JS) slides 16–18     Lab 3 Manual (JS · Git) §10–11

 One-Shot Revision · Unit 1 + Appendix


A remote is a copy of the repository hosted elsewhere (usually GitHub). origin is just the conventional nick‐
name for the main remote's URL.

 Command                                           Does

  git clone <url>                                  Download a full copy of a remote repo (history included), already linked as origin

  git remote add origin <url>                      Link an existing local repo to a GitHub repo

  git remote -v                                    Show the remotes and their URLs

  git remote set-url origin <url>                  Change the URL of an existing origin

  git push -u origin main                          Upload commits; -u remembers the pairing so later just git push

  git pull (= fetch + merge )                      Download new commits and merge them into the current branch

  git fetch                                        Download changes to inspect, without merging yet


           two ways to start


  # A. project started on your laptop -> put it on GitHub (Lab 3 §10)
  git init
  git add .
  git commit -m "Initial commit"
  git branch -M main                                          # make sure the branch is called main
  git remote add origin https://github.com/YOUR-USERNAME/profile-card.git
  git push -u origin main


  # B. project already on GitHub -> get it

--- PDF page 87 ---
git clone https://github.com/PARTNER-USERNAME/profile-card.git partner-card
  cd partner-card



 Clone                                      Fork                                        Pull request (PR)

 Git command: a local copy of a             GitHub feature: your own server-side copy   GitHub feature: a proposal to merge one
 repo on your machine                       of someone else's repo                      branch into another, with review



▸ The pull-request workflow (Lab 3 §11)

 1          Clone the repository (or fork it first if you have no write access).

 2          Branch off main : git switch -c add-guest-note .

 3          Make one small, honest change and commit it with a clear message.

 4          Push the branch, not main: git push -u origin add-guest-note (you usually cannot push to
            someone else's main).

 5          Open a pull request on GitHub comparing your branch with main .

 6          Review and merge: teammates comment line by line, CI (GitHub Actions) runs tests, the owner
            merges.


Good commit habits: small and focused (one idea per commit); present tense ("Add login form", not "added
stuff"); pull before you start, push when you pause; the message explains why, the diff already shows what; nev‐
er force-push to a shared branch. GitHub also gives Issues (bug/to-do tracker), Actions (CI/CD on every push)
and README.md (the repo's front page).


     PYQ      Final 2025-26 · Q1(e)   ★ LATEST                                                                                    2M


  Write the CLI to set a Git remote named origin to https://github.com/user/repo.git, and the CLI to
  clone a repo from that URL. (Commands only.)

     ✓    MODEL ANSWER — WRITE THIS

               commands


         git remote add origin https://github.com/user/repo.git
         git clone https://github.com/user/repo.git


  (Optional extras if space allows: git remote -v to verify; if origin already exists,
     git remote set-url origin https://github.com/user/repo.git .)

  🎯 Marking scheme guess: 1 M git remote add origin <url> · 1 M git clone <url>

--- PDF page 88 ---
⚠️ COMMON MISTAKES
    git remote origin add (wrong order), git add remote , or git clone origin all lose the marks. The
  pattern is git + noun + verb: git remote add <name> <url> . Pushing before any commit gives "src ref‐
  spec main does not match any".




    1.23 Likely questions for 2026
📚 Sources: All three past papers         Unit 1 Notes     LEC 2 (CSS)      LEC 3 (Git · Frameworks · JS)


The newest paper asked Unit 1 only through Git (conceptual, scenario-style). Expect the same style, with the
older code questions as the fallback.

  Likely question                                                                             Marks        Answer pointer

  Explain the Git workflow: working directory, staging area, local repo,                      5–6          1.20 four-places flow + "one clean
  remote. Why does the staging area exist?                                                                 logical commit"

  git restore vs reset vs revert; which is safe after pushing and why?                        4–6          1.20 undo table + golden rule

  A teammate force-pushed / rebased a shared branch. What breaks                              6            1.21 rebase cons + golden rule; use
  and how should it have been done?                                                                        merge/revert

  Fork vs clone vs pull request; describe the PR workflow                                     4–6          1.22 table + 6 steps

  Explain how a browser renders a page (DOM, CSSOM, render tree, lay‐                         5            1.2
  out, paint); why CSS in head, scripts at end

  Anatomy of an HTTP request and response; GET vs POST; status                                4–5          1.1
  codes

  Flexbox vs Grid with examples; when to use each                                             5–6          1.9–1.10 comparison table + 3 pat‐
                                                                                                           terns + named areas

  CSS cascade and specificity; compute which rule wins                                        4–5          1.6 + specificity drill

  Sequential vs parallel await; Promise.all; common async mistakes                            5–6          1.17

  Bootstrap vs Tailwind; semantic vs non-semantic HTML                                        4–5          1.12 table · 1.3 table




    1.24 Last-minute recap
📚 Sources: Every Unit 1 file
 Topic                  Must-remember facts

 Client–server          Request = method + scheme + server + path + query + headers (+ body). Response = status + headers + body (of‐
                        ten JSON). Auth travels in headers. 2xx ok · 3xx redirect · 4xx client error · 5xx server error.

 Frontend /             Frontend = browser, UI (HTML/CSS/JS, React). Backend = server, logic + DB (Django, PostgreSQL).
 backend

--- PDF page 89 ---
Topic                  Must-remember facts

 Rendering              Fetch → DOM → CSSOM → render tree → layout → paint. CSS render-blocking → head. Scripts → end of body /
                         defer . Animate transform + opacity.

 HTML                   DOCTYPE, html, head (charset, viewport, title, link), body. Semantic: header, nav, main, section, article, aside, footer.
                        Form: action, method, name, label for=id; HTML5: required, type, min/max, pattern.

 CSS types              Inline (style attr, highest) · internal (<style> in head) · external (.css + <link>, cached, best). Internal vs external: later
                        wins.

 Cascade                !important → specificity (ID-class-element) → source order. 0-1-0 beats 0-0-11. Text properties inherit; box proper‐
                        ties do not.

 Box model              content → padding → border → margin; *{box-sizing:border-box} ; 300 + 20 + 10 = 330 under content-
                        box. rem for sizes, px for borders.

 Layout                 position: static/relative/absolute (nearest positioned ancestor)/fixed/sticky. Flex = 1 axis (justify = main, align-items =
                        cross). Grid = 2 axes (fr, repeat, minmax, auto-fit, areas). Grid the page, flex the parts. Mobile first = min-width.

 Frameworks             Bootstrap = components + 12-col grid (sm 576, md 768, lg 992, xl 1200). Tailwind = utility classes, variants
                        md:/hover:/dark:.

 JS core                const default, let if reassigned, never var. === always. Falsy: false 0 "" null undefined NaN. typeof null = "object".
                        map/filter/reduce return new arrays.

 Functions              Declaration (hoisted), expression, anonymous, arrow (no own this, no new), IIFE, callback, higher-order, constructor
                        (new), async (returns Promise), generator (function*, yield).

 Async                  Callbacks → callback hell → Promises (pending/fulfilled/rejected; then/catch/finally; all/race/allSettled/any) →
                        async/await (syntax over Promises, try/catch). Sync first, then microtasks (Promises), then tasks (setTimeout).

 Git                    Distributed VCS, snapshots, Linus Torvalds 2005. init · status · add · commit -m · log --oneline · switch -c · merge ·
                        rebase · cherry-pick · tag -a · remote add origin · clone · push -u · pull = fetch + merge. Revert shared mistakes;
                        never rewrite shared history.



▸ Code skeletons to write from memory

             the five templates


  // 1. callback -> Promise
  function step(ms, msg) {
       return new Promise((resolve, reject) => {
         setTimeout(() => { console.log(msg); resolve(); }, ms);
       });
  }
  // 2. Promise chain
  step(2000, "A").then(() => step(4000, "B")).then(() => console.log("done")).catch(e => con‐
  sole.error(e));
  // 3. async/await
  async function run() {
       try { await step(2000, "A"); await step(4000, "B"); }
       catch (err) { console.error(err.message); }
  }
  // 4. validation on submit
  form.addEventListener("submit", (event) => {

--- PDF page 90 ---
if (!/^[A-Za-z ]+$/.test(nameInput.value.trim())) {
           nameError.textContent = "Letters only";
           event.preventDefault();
       }
  });
  // 5. page layout (CSS)
  // .page { display: grid; grid-template-columns: 2fr 3fr;
  //                   grid-template-areas: "head head" "menu main" "foot foot"; }



  🔑 FIVE LINES TO SAY IN THE EXAM HALL
           "bye!" prints first because setTimeout only schedules work; Promises and await never block code after
           the call.
           Validate in three layers: HTML5 attributes, JavaScript, and again on the server.
           Merge preserves history; rebase rewrites it; never rebase what others have pulled.
           A branch moves with every commit; a tag is fixed and marks a release.
           Cherry-pick copies one commit onto the current branch as a new commit.