1. Courses
  2. Developer Foundations
  3. JavaScript Deep Dive
  4. Stop 1

30 minBeginner

JavaScript in one sitting

Welcome to JavaScript Deep Dive. This first lesson is a fast tour of the parts of JavaScript you use every day: values and types, variables, comparisons, conditions and loops. Each part comes with the trap that catches people, so the deeper lessons that follow have solid ground to stand on.

By the end you can

  • Name the eight kinds of value in JavaScript and check one with typeof
  • Choose between let and const, and say why var is out
  • Predict what ==, ===, || and ?? return, including the surprising cases
  • Write and run a Node script in VS Code's terminal that summarises a store's daily sales

The everyday picture

On a new cashier's first day, the store manager does not hand over the whole operations manual. She gives a fifteen-minute briefing at the counter: this is the till, this is the scanner, this is how a card or mobile-wallet payment looks on screen. Then she adds the five mistakes every new cashier makes in the first week, such as scanning a multipack as one item, or giving change before the payment is confirmed.

This lesson is that briefing for JavaScript. If you have written some JavaScript before, most of it will be a reminder. If you are new, it gives you just enough to follow the rest of the course. Either way, the valuable part is the list of traps next to each topic, because those are what show up later as bugs in a sales report. All you need is Node installed and VS Code open (VS Code essentials covers the setup), and every example is a small grocery-store script you can run yourself.

Values and types: seven primitives and objects

Every value in JavaScript is one of eight types. Seven are : single, unchangeable values. The eighth is object, which covers everything that holds other values: plain objects, arrays, functions, dates, Maps.

  • number: one type for all numbers, whole or fractional (1250, 0.15). It is a 64-bit floating-point number, which is why 0.1 + 0.2 prints 0.30000000000000004. Working with data explains why and what to do about money.
  • bigint: whole numbers of any size, written with an n: 9007199254740993n. Plain numbers stay exact only up to 9,007,199,254,740,991.
  • string: text, in single quotes, double quotes or backticks.
  • boolean: true or false.
  • undefined: "no value was ever given". A variable you declared but never set, or a property that does not exist.
  • null: "deliberately empty". Your code or your API sets it on purpose.
  • symbol: a unique id, mostly used inside libraries. You will rarely write one.

The typeof operator tells you the type as a string. It has one famous bug that can never be fixed, because fixing it would break old websites: typeof null is 'object'. Arrays also say 'object', so use Array.isArray(x) to check for an array.

JavaScript
console.log(typeof 10n, typeof Symbol('x'), typeof function () {}, typeof []);
console.log(typeof undefined, typeof 'a', typeof NaN, Array.isArray([]));
console.log(typeof null);   // the old bug
Output
bigint symbol function object
undefined string number true
object

Notice typeof NaN is 'number'. is the number you get when a conversion fails, for example Number('2 pcs').

Quick check

An API returns a list of order lines. What does typeof lines give you?

Every value a single value a container Primitives (7) number string boolean bigint null undefined symbol typeof null says 'object' Objects { } object [ ] array function Date Map Set copied on assign shared on assign
The type family. Seven primitives hold one value each and are copied when you assign them. Everything else is an object, and assigning an object shares it (Objects, arrays and references). typeof null wrongly says 'object'.

Variables, operators and the two kinds of equal

Declare with const by default and with let when you will reassign the name, such as a running total. Both are . Do not use var: it ignores blocks and has hoisting surprises that Functions, scope and closures shows in full. One more thing about const: it stops you from pointing the name at a new value, and it does not stop changes inside an object. const cart = [] followed by cart.push(item) is allowed. Objects, arrays and references is about exactly that.

Arithmetic operators are the usual + - * / % plus ** for powers. The trap is +: if either side is a string, it joins text instead of adding. Everything a user types into a form arrives as a string, so this bites often:

JavaScript
const qtyFromForm = '2';                 // every form input value is a string
console.log(qtyFromForm + 1);            // + with a string joins text
console.log(Number(qtyFromForm) + 1);    // convert first, then add
console.log(Number(''), Number('2 pcs'));
Output
21
3
0 NaN

Note that Number('') is 0, not an error. An empty quantity box becomes zero silently, so validate input before converting it.

For comparison, JavaScript has two equals. === (strict equality) is true only when both sides have the same type and the same value. == (loose equality) first converts the two sides towards a common type, a process called , and the rules are long and odd: 0 == '' is true, [] == false is true, null == 0 is false. Always use === and !==. The one idiom some teams allow is x == null, which is true for both null and undefined. ESLint's eqeqeq rule enforces this (VS Code for teams).

Quick check

A scanner reads barcode '0420019' and the database stores it as the string '0420019'. Which line should your code use to compare them?

Truthy, falsy, and safe defaults

An if, a while, &&, || and ! all accept any value, not only booleans. They treat a value as true or false by a fixed rule. Exactly eight values are : false, 0, -0, 0n, "", null, undefined and NaN. Every other value is , including the string '0', the string 'false', an empty array and an empty object.

Quick check

A form sends a stock count. Which of these values makes if (count) run its body?

if (value) goes to else runs the if Falsy: only 8 false 0 -0 0n "" NaN null undefined Truthy: all else these surprise people '0' 'false' [ ] { } ' ' -1 and every other value
Exactly eight values are falsy; everything else is truthy, including '0', [] and {}. The two highlighted values, null and undefined, are the only ones that ?? and ?. treat as missing.

This matters most for defaults. a || b returns b whenever a is falsy, so a real zero gets replaced. The operator a ?? b returns b only when a is null or undefined. For numbers such as a discount, a quantity or a stock level, where 0 is a real answer, use ??.

, a?.b, reads b only if a is not null or undefined, and gives undefined otherwise instead of crashing. The two work well together:

JavaScript
const discountCents = 0;                  // a real "no discount"
console.log(discountCents || 50, discountCents ?? 50);

const sale = { customer: null };          // a walk-in customer
console.log(sale.customer?.phone, sale.customer?.phone ?? 'walk-in');
console.log(sale.customer.phone);         // no ?. here
Output
50 0
undefined walk-in
TypeError: Cannot read properties of null (reading 'phone')

The last line stops the script; Node prints a stack trace, and the line above is the important part of it. Do not sprinkle ?. everywhere, though. If a sale must always have a store, sale.store?.siteId hides a real data bug behind a quiet undefined. Use ?. where "missing" is a normal, expected case.

Strings, conditions, loops and the console

use backticks and ${…} to put values inside text: `Store ${siteId}: ${lineCount} lines`. They can also span several lines. Prefer them to joining strings with +.

if / else if / else works as in any C-style language. switch compares with === and has one trap: without break or return, execution falls through into the next case. Sometimes that is what you want, so that several cases share one answer, such as the many mobile wallets a store accepts (M-Pesa, UPI, GCash and so on):

JavaScript
function channel(paidBy) {
  switch (paidBy) {
    case 'cash': return 'cash';
    case 'mpesa':                 // no return: falls through on purpose
    case 'upi':
    case 'gcash': return 'mobile wallet';
    case 'card': return 'card';
    default: return 'other';
  }
}
console.log(channel('upi'), channel('cheque'));
Output
mobile wallet other

For loops, you need three forms. The classic for (let i = 0; i < n; i++) when you need the index. for (const sale of sales) to walk the values of an array, a string, a Map or a Set; this is the one to use most. And for (const key in obj), which walks the keys of an object. Do not use for…in on arrays: it gives you the indexes as strings ('0', '1') and can include extra properties. Inside any loop, continue skips to the next item and break stops. Working with data covers the array methods (map, filter, reduce) that replace many loops.

The console is your first debugging tool. console.log prints values (objects are shown with their contents), console.table prints an array or object as a table, and console.error writes to the error stream, which the terminal and log collectors treat separately. Errors, debugging and testing goes from here to real breakpoints.

Build it

Write a small Node script that summarises one store's day, run it in VS Code's terminal, then test your instincts with eight one-liners. If you want to practise before installing anything, the Practice section below runs two exercises in your browser.

  1. Open a folder and a terminal

    Make a folder, open it in VS Code with code . (VS Code essentials), and open the integrated terminal with Ctrl+` on both Windows and macOS, or the Command Palette command "View: Toggle Terminal". These commands are the same in PowerShell, Git Bash and zsh. Any Node 22 or 24 version is fine.

    Terminal
    mkdir js-basics
    cd js-basics
    code .
    node -v
    Output
    v22.22.0
  2. Write the script

    Create daily-sales.js. It skips voided lines, totals in cents, groups the money by payment method and remembers the biggest line. Every idea from this lesson is in it: const and let, a truthiness check on voided, ?? for a missing key, ?. for a possibly empty result, template literals and for…of. The last few lines format cents as US dollars with Intl.NumberFormat, which Working with data explains.

    JavaScript
    // daily-sales.js: summarise one store's sales for one day
    const siteId = 'S014';
    const sales = [                       // prices in cents: 1250 cents = $12.50
      { id: 1, articleCode: '100234', qty: 2, unitPrice: 1250, paidBy: 'cash' },
      { id: 2, articleCode: '200871', qty: 1, unitPrice: 3999, paidBy: 'wallet' },
      { id: 3, articleCode: '100234', qty: 3, unitPrice: 1250, paidBy: 'card' },
      { id: 4, articleCode: '310045', qty: 1, unitPrice: 450, paidBy: 'cash', voided: true },
      { id: 5, articleCode: '420019', qty: 6, unitPrice: 199, paidBy: 'wallet' },
    ];
    
    let totalCents = 0;
    let lineCount = 0;
    let biggest = null;                   // the largest sale line so far
    const byMethod = {};                  // e.g. { cash: 2500, wallet: 3999 }
    
    for (const sale of sales) {
      if (sale.voided) continue;          // skip cancelled lines (undefined is falsy)
      const lineTotal = sale.qty * sale.unitPrice;
      totalCents += lineTotal;
      lineCount += 1;
      byMethod[sale.paidBy] = (byMethod[sale.paidBy] ?? 0) + lineTotal;
      if (biggest === null || lineTotal > biggest.lineTotal) {
        biggest = { articleCode: sale.articleCode, lineTotal };
      }
    }
    
    const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
    const dollars = (cents) => usd.format(cents / 100);   // for display only
    
    console.log(`Store ${siteId}: ${lineCount} lines, total ${dollars(totalCents)}`);
    for (const [method, cents] of Object.entries(byMethod)) {
      console.log(`  ${method.padEnd(6)} ${dollars(cents).padStart(8)}`);
    }
    console.log(`Biggest line: article ${biggest?.articleCode ?? 'none'}`);
  3. Run it, then run it on every save

    Run it once. Then try node --watch, which re-runs the script each time you save (stable since Node 22). Change a quantity, press Ctrl+S (Cmd+S on macOS) and watch the total change. Stop it with Ctrl+C.

    Terminal
    node daily-sales.js
    node --watch daily-sales.js
    Output
    Store S014: 4 lines, total $114.43
      cash     $25.00
      wallet   $51.93
      card     $37.50
    Biggest line: article 200871

    The voided $4.50 line is not in the cash total, and byMethod created each key the first time it saw it, thanks to ?? 0.

  4. Predict the output: eight one-liners

    Save this as predict.js. Before you run it, write down what you expect each line to print. Then run node predict.js and compare.

    JavaScript
    const order = { store: null };                                   // setup
    console.log(typeof null);                                        // 1
    console.log('5' + 3, '5' - 3);                                   // 2
    console.log(0 == '', 0 === '');                                  // 3
    console.log(null == undefined, null === undefined);              // 4
    console.log(0 || 50, 0 ?? 50);                                   // 5
    console.log(Boolean('0'), Boolean(''), Boolean([]));             // 6
    console.log(NaN === NaN, Number.isNaN(Number('12a')));           // 7
    console.log(order.store?.siteId, order.items?.length ?? 0);      // 8
    Show the real output and why
    Output
    object
    53 2
    true false
    true false
    50 0
    true false true
    false true
    undefined 0
    1. The old typeof null bug.
    2. + with a string joins text; - only works on numbers, so it converts '5' to 5.
    3. == converts '' to 0, so they are "equal"; === sees two types.
    4. null and undefined are loosely equal to each other and to nothing else.
    5. || replaces any falsy value; ?? keeps the real zero.
    6. A non-empty string is truthy even if it says '0'; an empty array is truthy too.
    7. NaN is not equal to itself. Use Number.isNaN to test for it.
    8. order.store is null, so ?. stops and gives undefined; items does not exist, so ?? 0 supplies the default.

Bring it to your team

These small rules show up as real bugs in money and stock code. Ask about them early.

  • "Do we keep every price and total as integer cents, and where exactly do we turn it into currency text?"
  • "Is ESLint's eqeqeq rule on, along with no-var and prefer-const?"
  • "For this default value, can zero be a real answer? If yes, are we using ?? instead of ||?"
  • "When a field is missing in this API response, is it null, absent, or an empty string? Which one does the app check for?"
  • "Where do we convert form input to numbers, and what happens with an empty box or '2 pcs'?"

Red flags

  • == comparisons in pricing, stock or payment code.
  • qty || 1, discount || DEFAULT or stock || 0 on values where 0 is valid.
  • Prices stored as 12.5 in some places and 1250 in others.
  • typeof x === 'object' used as an "is this an object" check without also ruling out null.

Practice

Fix two input bugs from the Partner app

Both functions below have a bug from this lesson. addQty receives the quantity exactly as the form sends it, as text. It must return a number, and it must throw an Error for input that is not a whole number of at least 1, such as an empty box or '2 pcs'. discountFor must keep the line's own discount, including a real 0, and use the 50-cent default only when the discount is missing (null or undefined). Press Run to check your answer.

JavaScript exerciseRuns in your browser with tests
// 1. The form sends qty as text, such as '2'. Return the new quantity as a number.
function addQty(currentQty, qtyFromForm) {
  return currentQty + qtyFromForm;
}

// 2. Keep the line's own discount. Use the default only when it is missing.
const DEFAULT_DISCOUNT_CENTS = 50;
function discountFor(line) {
  return line.discountCents || DEFAULT_DISCOUNT_CENTS;
}
Ctrl + Enter runs
Show a solution
JavaScript
function addQty(currentQty, qtyFromForm) {
  const qty = Number(qtyFromForm);
  // Number('') is 0 and Number('2 pcs') is NaN, so check before using it
  if (qtyFromForm.trim() === '' || !Number.isInteger(qty) || qty < 1) {
    throw new Error(`bad quantity: '${qtyFromForm}'`);
  }
  return currentQty + qty;
}

const DEFAULT_DISCOUNT_CENTS = 50;
function discountFor(line) {
  return line.discountCents ?? DEFAULT_DISCOUNT_CENTS;   // only null or undefined
}
Pass the exercise to finish this task.

Total a day's sales by payment method

Write totalsByMethod(sales). Each sale looks like { qty: 2, unitPrice: 1250, paidBy: 'cash', voided: true }, and voided may be missing. Return an object with the total in cents per payment method, skipping voided sales, such as { cash: 2500, card: 3750 }. The starter has three bugs from this lesson.

JavaScript exerciseRuns in your browser with tests
function totalsByMethod(sales) {
  const byMethod = {};
  for (const sale in sales) {
    byMethod[sale.paidBy] += sale.qty * sale.unitPrice;
  }
  return byMethod;
}
Ctrl + Enter runs
Show a solution
JavaScript
function totalsByMethod(sales) {
  const byMethod = {};
  for (const sale of sales) {                 // of: the values, not the indexes
    if (sale.voided) continue;                // a missing voided is undefined, so falsy
    const line = sale.qty * sale.unitPrice;
    byMethod[sale.paidBy] = (byMethod[sale.paidBy] ?? 0) + line;
  }
  return byMethod;
}
Pass the exercise to finish this task.

Check yourself

A partner shop sets an article's discount to 0 on purpose. The code reads const d = line.discountCents || 50;. What is d, and what should the code use?

A quantity comes from a form as '2'. The code computes qty + 1. What does it give?

What does const cart = []; cart.push('100234'); do?

Flashcards

Open my review

Key takeaways

  • Seven primitive types plus objects. typeof null is 'object'; check arrays with Array.isArray.
  • Use const by default, let when you reassign, never var. const does not freeze objects.
  • Always compare with ===. Watch + with strings, and convert form input with Number() after validating it.
  • Only eight values are falsy. Use ?? for defaults when 0 or '' is a real value, and ?. where "missing" is normal.
  • Keep money in integer cents and format it only for display.

Sources

Episode transcriptEight falsy values and a free discount · about 13 minutes · tap any line to play from there
  1. NadiaImran, picture this. Ravi's partner shop sets the discount on a bag of rice to zero. No discount, on purpose. And for two weeks the Partner app keeps giving every customer fifty cents off anyway.
  2. ImranThat sounds like a pricing bug I would spend a week chasing. Where does it come from?
  3. NadiaFrom one tiny piece of JavaScript basics. That's what today is about: a fast tour of the language, with the traps that cause bugs like that one.
  4. ImranSo this is the first lesson of the course, before the deep ones. I read JavaScript in code reviews all the time, so I'm hoping most of it is a reminder.
  5. NadiaFor you it will be. And if someone listening has never written JavaScript, this is the lesson that gets them ready for the rest.
  6. NadiaThink of a new cashier's first day. The store manager doesn't hand over the whole manual. She gives a fifteen minute briefing at the counter. This is the till, this is the scanner, this is how a mobile wallet payment looks.
  7. NadiaAnd then she adds the five mistakes every new cashier makes in week one. Scanning a multipack as one item. Giving change before the payment is confirmed.
  8. ImranSo the briefing is short, but the list of mistakes is the valuable part.
  9. NadiaExactly. Let's start with values. Every value in JavaScript is one of eight types. Seven are called primitives. A primitive is a single, simple value that can't be changed in place.
  10. ImranNumber, string, boolean. Then null and undefined. What are the other two?
  11. NadiaBigInt, for whole numbers of any size, and symbol, which is a unique ID you'll mostly see inside libraries. The eighth type is object, and it covers everything that holds other values. Plain objects, arrays, functions, dates, maps.
  12. NadiaIf you can see your screen, the first diagram shows this as a family tree. On the left, a dashed frame with the seven primitives. On the right, a frame with objects. Under the left side it says copied on assign, and under the right side, shared on assign.
  13. ImranThat copied versus shared part sounds important.
  14. NadiaIt's so important it gets its own lesson later in the course, on objects and references. For now, just remember there are two families and they behave differently when you hand them around.
  15. ImranWhat's the difference between null and undefined? I've always used them as if they were the same.
  16. NadiaUndefined means no value was ever given. A variable you declared but never set, or a property that doesn't exist. Null means deliberately empty. Your code or your API puts it there on purpose, like a sale with no registered customer.
  17. ImranAnd the typeof operator tells you which type you have.
  18. NadiaMostly. It has one famous bug. Typeof null says object. It's been wrong since the first version, and it can never be fixed because old websites depend on it. Arrays also say object, so to check for an array you use Array dot isArray.
  19. ImranAnd numbers? I remember all numbers being one type.
  20. NadiaRight. Whole or fractional, it's one number type, stored as a sixty-four bit floating point value. That's why zero point one plus zero point two prints zero point three, followed by a long tail of zeros and a four. The lesson on working with data explains why.
  21. ImranWhich is why our team keeps prices in cents.
  22. NadiaYes. Twelve dollars fifty is stored as one thousand two hundred fifty cents, a whole number. Whole numbers are exact up to about nine thousand trillion. You turn them into dollar text, or your local currency, only when you show them on screen.
  23. ImranOkay. Variables next. Let and const, and never var?
  24. NadiaNever var. Use const by default, and let when you'll reassign the name, like a running total. Both only live inside the nearest pair of curly braces. Var ignores those blocks and has some surprises we'll see in the next lesson.
  25. ImranSo const means the value can't change.
  26. NadiaThat's the common guess, and it's not quite right. Const means the name can't be pointed at something new. If the name holds an array, you can still push items into that array. Const doesn't freeze anything.
  27. ImranSo a const cart can still get new lines added. Good to know before I read a code review.
  28. NadiaNow the plus sign. If either side is a string, plus joins text instead of adding. And every value a user types into a form arrives as a string.
  29. ImranSo a quantity of two from the form, plus one, gives me twenty-one.
  30. NadiaThe string twenty-one, yes. The fix is to convert with the Number function first. But watch out: an empty box converts to zero without any error, and two pieces written as text converts to NaN, which means not a number. So validate before you convert.
  31. ImranThen equality. I know there are two kinds.
  32. NadiaTriple equals is strict. It's true only when the type and the value are both the same. Double equals is loose. It first converts both sides towards a common type, which is called type coercion, and the rules are strange.
  33. NadiaWith double equals, zero equals an empty string. An empty array equals false. But null does not equal zero. Nobody remembers all of it.
  34. ImranSo the rule is simple. Always triple equals.
  35. NadiaAlways, and the ESLint rule called eqeqeq enforces it for the whole team. Some teams allow one exception: comparing with null using double equals, because that catches both null and undefined in one check.
  36. ImranNow tell me about Ravi's rice discount.
  37. NadiaFirst, truthy and falsy. An if statement doesn't need a real true or false. It accepts any value and decides by a fixed rule. Exactly eight values count as false. They're called falsy.
  38. NadiaFalse itself. Zero, and negative zero. The BigInt zero. The empty string. Null. Undefined. And NaN. That's the whole list. Everything else is truthy.
  39. ImranEven an empty array?
  40. NadiaEven an empty array, an empty object, and the string containing the character zero. If you can see the screen, the second diagram sorts them. On the left, a grey box with only eight values. On the right, everything else, with the surprising ones highlighted in amber.
  41. ImranSo the discount code was something like: discount, or fifty cents as a default.
  42. NadiaExactly that. The or operator returns the right side whenever the left side is falsy. Zero is falsy. So Ravi's real zero discount got replaced with the default fifty cents.
  43. ImranAnd the fix?
  44. NadiaTwo characters. The double question mark operator, called nullish coalescing. It uses the right side only when the left side is null or undefined. A real zero stays zero.
  45. ImranSo for any number where zero is a real answer, like a discount, a quantity or a stock level, I want the double question mark, not or.
  46. NadiaThat's the review question in one sentence. Ravi's shop is the At Mangrove Market example in the lesson, and it adds up to roughly sixty dollars a week he never agreed to give away.
  47. ImranAnd its cousin, the question mark followed by a dot?
  48. NadiaOptional chaining. It reads a property only if the thing before it isn't null or undefined. Otherwise you get undefined instead of a crash. For a walk-in customer with no record, reading the phone number with optional chaining gives undefined, and you can default it to the words walk-in.
  49. ImranSo I should use it everywhere to stop crashes?
  50. NadiaNo, and that's a reasonable guess that causes quiet bugs. If a sale must always have a store, optional chaining hides a real data problem behind an undefined. Use it only where missing is a normal case.
  51. ImranQuick round on the rest. Strings?
  52. NadiaTemplate literals. You write the text in backticks and drop values straight into it, like store, then the site ID, then the number of lines. Much cleaner than joining pieces with plus.
  53. ImranSwitch statements?
  54. NadiaThey compare strictly. The trap is that without a break or a return, execution falls through into the next case. Sometimes that's useful, so M-Pesa, UPI and GCash can share one answer, mobile wallet. But forget it by accident and two branches run.
  55. ImranAnd loops. I usually just write the classic for loop with an index.
  56. NadiaThat's fine when you need the index. For walking values, use for of. It works on arrays, strings, maps and sets. There's also for in, which walks the keys of an object. Don't use for in on an array. It gives you the positions as strings.
  57. NadiaNow the Build it. You make a folder, open it in VS Code with code dot, and open the terminal. Then you write a short script for one store's day: five sale lines, one of them voided.
  58. ImranAnd the script loops through them?
  59. NadiaIt skips the voided line, adds up the rest in cents, groups the money by payment method, cash, card and wallet, and remembers the biggest line. The total comes to one hundred fourteen dollars and forty-three cents.
  60. ImranAnd the grouping uses the double question mark to start each payment method at zero.
  61. NadiaRight. Then you run it with node watch, which re-runs the script every time you save. Change a quantity, save, and the total updates.
  62. NadiaThe last step is a predict the output game. Eight one-line puzzles. You write your answer down before running them. The typeof null bug, the plus with a string, the two equals, and the zero versus default case all appear.
  63. ImranI'll admit I'd probably get the NaN one wrong.
  64. NadiaMost people do. NaN is not equal to itself. To test for it you use Number dot isNaN.
  65. ImranAnd the practice section has two exercises that run right in the browser, so nobody needs to install anything to try them.
  66. NadiaYes. One fixes the form quantity and Ravi's discount. The other totals a day by payment method, and its starter code has three bugs from today: for in on an array, adding to a missing key, and forgetting the voided lines. The test names tell you which one you still have.
  67. ImranSo what do I take to my next design review?
  68. NadiaThree questions. Do we keep every price as whole cents, and where exactly do we turn it into currency text? Is the strict equality lint rule on? And for every default on a number, can zero be a real answer here?
  69. ImranI'd add one about API responses. When a field is missing, is it null, absent, or an empty string? Because the app has to check for the right one.
  70. NadiaGood addition, Imran. Those three cases behave differently with or, with the double question mark, and with optional chaining.
  71. NadiaHere's one to think about. A quantity arrives from a form as the string two. The code adds one. What do you get? Take a second.
  72. ImranThe string twenty-one, because plus with a string joins text.
  73. NadiaRight. And here's the twist: minus would have converted it, so the string five minus three gives the number two. Only plus has the text rule.
  74. ImranLet me sum it up. One: seven primitives and objects, and typeof null lies. Two: const by default, let when I reassign, never var, and const doesn't freeze anything. Three: triple equals always, and the double question mark for defaults.
  75. NadiaOne nuance on the third. The double question mark is for defaults where zero or an empty string is a real value. And keep the money in cents, always.
  76. ImranNext time?
  77. NadiaFunctions and closures. A cashier's drawer that remembers its own float even after the shift manager has gone home.
Finished reading?Mark it complete to fill in its stop on your course line.

Use it at work

Utility script

A small script with its options at the top, input checks, a summary line and tests.

Open in the Code Lab
Next stopFunctions, scope and closures
Was this lesson helpful?
Questions and discussion

Loading the discussion…