Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3 · LANGUAGES

How to Code in JavaScript/TypeScript Using AI

Use an AI assistant to write a small JavaScript function, run it with Node.js, and prove it works with Node's built-in test runner. No extra packages needed.

In short: say the Node version and “no npm packages”, give one example, ask for node:test tests, run node --test.

Why JavaScript with AI

WHY

JavaScript runs websites, servers (Node.js) and apps. There are many ways to do one thing, and old examples are everywhere. A clear prompt keeps the AI on modern, simple code.

What you need

WHAT
  • Node.js 20 or newer: includes node --test, the built-in test runner.
  • An editor + assistant: VS Code with GitHub Copilot or Claude Code, or WebStorm with Copilot.
  • TypeScript (optional): npm i -D typescript and run npx tsc --noEmit to type-check.

How it flows

1 · Describe the function Node 20, no packages, example 2 · AI writes code read every line 3 · Run it node slugify.js 4 · Ask for tests node:test + assert 5 · Run tests node --test = green

Install and check

HOW
  1. Install Node.js LTS from nodejs.org (or nvm install --lts).
  2. Check it: node -v should show v20 or newer.
  3. Make a folder: mkdir slug-demo && cd slug-demo.
  4. Optional: npm init -y to create package.json. Set "test": "node --test" under scripts.

Step 1 — the prompt

COPY THIS PROMPT

Write a Node.js 20 CommonJS module with slugify(title). No npm packages. Lowercase, remove accents, turn anything that is not a-z or 0-9 into one dash, trim dashes at the ends. Throw TypeError if title is not a string. Example: slugify("Hello, World! 2026") returns "hello-world-2026". Only return the code.

Step 2 — the code (tested here)

slugify.js
// Turn a title into a URL slug. Built with an AI assistant, then tested.
function slugify(title) {
  if (typeof title !== "string") throw new TypeError("title must be a string");
  return title
    .normalize("NFKD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}
module.exports = { slugify };
if (require.main === module) console.log(slugify(process.argv[2] || "Hello, World! 2026"));

Step 3 — run it

node slugify.js "Hello, World! 2026"
# -> hello-world-2026

Step 4 — ask for tests, then run them

FOLLOW-UP PROMPT

Write tests with node:test and node:assert for slugify: a normal title, accents with extra spaces, and a non-string input.

slugify.test.js
const test = require("node:test");
const assert = require("node:assert");
const { slugify } = require("./slugify");

test("basic title", () => {
  assert.strictEqual(slugify("Hello, World! 2026"), "hello-world-2026");
});
test("accents and extra spaces", () => {
  assert.strictEqual(slugify("  Café   Menu  "), "cafe-menu");
});
test("rejects non-string", () => {
  assert.throws(() => slugify(42), TypeError);
});
node --test
# -> tests 3, pass 3, fail 0

TypeScript version (same idea)

Ask: “Convert slugify.js to TypeScript with strict types.” The function signature becomes:

export function slugify(title: string): string { ... }

Then run npx tsc --noEmit to check types before you run it.

Settings and config

  1. Tell the AI your module style: CommonJS (require) or ES modules (import, "type": "module" in package.json). Mixing them is a common AI mistake.
  2. Project rules file: add “Node 20, node:test, no new npm packages without asking” to .github/copilot-instructions.md or CLAUDE.md.
  3. Lint: npm init @eslint/config@latest then npx eslint ..

Watch out (common AI mistakes in JS)

  • Fake or unneeded npm packages — check on npmjs.com before installing. Typo-named packages can be malware.
  • Old patterns — var, callbacks instead of async/await.
  • Browser vs Node — document does not exist in Node; require does not exist in the browser.
  • == vs === — ask for strict equality.

Try this yourself: normalise Indian mobile numbers with AI (no npm packages)

Hello friends. Beyond the slugify demo on this page, build a new fictional helper called normalizePhoneIn for Mira Quill's peplin moss contacts list. It must accept common Indian mobile strings, return a +91 E.164-style value, and throw clear errors for bad input. Use CommonJS, node:test and node:assert only. TypeScript remains an optional tip; you do not need to install the TypeScript compiler to pass this practice.

Ravindra Bagale's Tip

Tell the AI your Node version, CommonJS module style, and “no new npm packages.” Run node --test yourself. Optionally convert the same function to TypeScript later with npx tsc --noEmit, but that step is not required for this gate.

Practice label: every name, number and time in this exercise is fictional teaching data. It is not about a real person, account or company. Passing these tests proves only the cases listed in the tests, not every possible input.
Environment (tested): this exercise was run on 6 November 2026 with Node.js v20.19.2 using the built-in node:test and node:assert modules. No npm packages are required. Use Node 18 or newer.

Your task: implement normalizePhoneIn(phone) so that "98765 43210", "+91-9876543210" and "09876543210" all become "+919876543210". Non-strings raise TypeError. Invalid numbers raise an Error whose message mentions invalid Indian mobile number. No npm packages.

Setup

HOW
  1. Create a project folder and open a terminal inside it.
  2. Confirm Node: run node -v. Use Node 18 or newer (this page was tested on v20.19.2).
  3. No virtualenv and no npm install are required for the gate. Stay on CommonJS (require / module.exports).

Starter phone.js (intentionally incomplete):

phone.js
'use strict';

/** Fictional Indian mobile normaliser for Mira Quill's peplin moss contacts list. */
function normalizePhoneIn(phone) {
  // Intentionally incomplete starter: students ask AI to finish it.
  if (typeof phone !== 'string') {
    throw new TypeError('phone must be a string');
  }
  throw new Error('not implemented');
}

module.exports = { normalizePhoneIn };

Tests test_phone.js:

test_phone.js
'use strict';
const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { normalizePhoneIn } = require('./phone.js');

describe('normalizePhoneIn', () => {
  it('accepts spaced ten-digit mobile', () => {
    assert.equal(normalizePhoneIn('98765 43210'), '+919876543210');
  });
  it('accepts +91- prefix', () => {
    assert.equal(normalizePhoneIn('+91-9876543210'), '+919876543210');
  });
  it('accepts leading zero', () => {
    assert.equal(normalizePhoneIn('09876543210'), '+919876543210');
  });
  it('rejects non-string with TypeError', () => {
    assert.throws(() => normalizePhoneIn(9876543210), TypeError);
  });
  it('rejects invalid length', () => {
    assert.throws(() => normalizePhoneIn('12345'), /invalid Indian mobile number/);
  });
  it('rejects landline-looking start digit', () => {
    assert.throws(() => normalizePhoneIn('5876543210'), /invalid Indian mobile number/);
  });
});

Suggested AI ask:

js-prompt.txt
Implement normalizePhoneIn(phone) in CommonJS phone.js for fictional Indian mobiles. Accept '98765 43210', '+91-9876543210', and '09876543210' and return '+919876543210'. Throw TypeError for non-strings and Error('invalid Indian mobile number') for bad values. No npm packages. Keep node:test tests unchanged.

HOW to finish

HOW
  1. Save phone.js and test_phone.js in the same folder.
  2. Run node --test test_phone.js on the starter. Expect about 1 pass and 5 fail while the function is not implemented.
  3. Ask your AI assistant for a CommonJS implementation with no new packages.
  4. Replace the body of normalizePhoneIn and save. Do not edit the test file.
  5. Run node --test test_phone.js again. Expect 6 passed (tests 6 / pass 6 / fail 0).
  6. Optional TypeScript tip only: you may later ask the AI to add types and run npx tsc --noEmit. That is not required to pass this practice gate.

Real output before the implementation (summary lines):

node-test-before.txt
# tests 6
# pass 1
# fail 5

Real output after a good implementation:

node-test-after.txt
# tests 6
# suites 1
# pass 6
# fail 0
Optional working phone.js (try it yourself first)

Your AI assistant may strip digits with a different helper name. Any version is fine if all 6 tests pass and you added no npm packages.

phone.js
'use strict';

/** Fictional Indian mobile normaliser for Mira Quill's peplin moss contacts list. */
function normalizePhoneIn(phone) {
  if (typeof phone !== 'string') {
    throw new TypeError('phone must be a string');
  }
  const digits = phone.replace(/\D/g, '');
  let national = digits;
  if (national.startsWith('91') && national.length === 12) {
    national = national.slice(2);
  } else if (national.startsWith('0') && national.length === 11) {
    national = national.slice(1);
  }
  if (!/^[6-9]\d{9}$/.test(national)) {
    throw new Error('invalid Indian mobile number');
  }
  return '+91' + national;
}

module.exports = { normalizePhoneIn };

Troubleshooting

HOW
  1. Error: Cannot find module './phone.js'. Fix: keep phone.js and test_phone.js in the same folder.
  2. Problem: spaced numbers still fail. Fix: remove every non-digit first, then handle a leading 91 country code or a leading 0 trunk prefix before checking for ten digits starting with 6-9.
  3. Problem: the AI added an npm package. Fix: delete that dependency and ask again with “no npm packages; use only node:test and node:assert.”
  4. Problem: you installed TypeScript only to pass. Fix: TypeScript is optional here; the gate is node --test on the JavaScript files.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Prove JS with node --test

Ask the AI for one CommonJS function and keep dependencies at zero for this gate.
When node --test reports 6 passed, the phone normaliser matches the listed Indian mobile cases.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

TypeScript stays optional here

You can convert the same helper to TypeScript later and run npx tsc --noEmit.
This practice gate does not require installing the TypeScript compiler.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

JS node --test ने सिद्ध करा

AI कडून एक CommonJS function मागा आणि या गेटसाठी dependencies शून्य ठेवा.
जेव्हा node --test 6 passed दाखवते, तेव्हा phone normaliser नमूद Indian mobile cases शी जुळतो.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

TypeScript इथे optional आहे

नंतर तोच helper TypeScript मध्ये रूपांतरित करून npx tsc --noEmit चालवू शकता.
या सराव गेटसाठी TypeScript compiler install करण्याची गरज नाही.
Ravindra Bagale · ravindrabagale.com/ai-coding

Quick quiz

1. Which command runs Node's built-in tests?

node --test.

2. Why say “no npm packages”?

Fewer dependencies, and no risk of fake or harmful packages.

3. What does slugify("Hello, World! 2026") return?

hello-world-2026.

4. How do you type-check TypeScript without building?

npx tsc --noEmit.

Save tokens and money

SMART AI USE

Paste only the function, not node_modules or a lock file. Never let the AI read package-lock.json unless needed, it is huge. Ask for one function plus tests, then the next.

Save these cards

INTERVIEW CARDAI Coding

How do you prove AI JS code works?

Run it with node.
Write node:test tests and run node --test.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

JavaScript vs TypeScript with AI

JS: fast to start, errors show at run time.
TS: types catch AI mistakes early with tsc --noEmit.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

JS with AI in 3

Say Node version + module style + no packages.
One example in the prompt.
node --test = proof.
Ravindra Bagale · ravindrabagale.com/ai-coding