Data Types and Values

Numbers, text, booleans, null and collections, and how languages convert between them.

What is it?

Every value has a type that decides what it is and what you can do with it. You can multiply two numbers, but multiplying two names makes no sense.

The common building blocks, in nearly every language:

- Integers: whole numbers (42, -7). - Floating-point numbers: numbers with a fractional part (3.14). They're approximations, so 0.1 + 0.2 is not exactly 0.3. - Booleans: true/false (True/False in Python). Results of comparisons. - Strings: text ("hello"), a sequence of characters. - "Nothing": None in Python; null and undefined in JavaScript. Means "no value here". - Collections: lists/arrays, dictionaries/objects/maps, sets, which group many values together.

Language differences worth knowing:

- Python has separate int and float. JavaScript has one number type (a 64-bit float) plus bigint for huge integers. - Changing a value from one type to another is type conversion. Doing it explicitly (int("42")) is casting. Doing it automatically is coercion. JavaScript coerces a lot ("5" * 2 is 10); Python mostly refuses ("5" + 1 is a TypeError).

Explain like I'm 10

Types are like containers in a kitchen: a measuring jug for liquids, a carton for eggs, a jar for spices. You can pour from one to another, but you need to know what's inside, and pouring eggs into the jug doesn't go well.

Examples

Checking types

print(type(42))        # <class 'int'>
print(type(3.14))      # <class 'float'>
print(type(True))      # <class 'bool'>
print(type("hi"))      # <class 'str'>
print(type(None))      # <class 'NoneType'>
print(type([1, 2]))    # <class 'list'>
print(type({"a": 1}))  # <class 'dict'>

print(7 / 2)   # 3.5  (true division always gives a float)
print(7 // 2)  # 3    (floor division)

type() reveals a value's type. Note that / always produces a float in Python 3.

Checking types in JavaScript

console.log(typeof 42);         // "number"
console.log(typeof 3.14);       // "number"  (same type!)
console.log(typeof 10n);        // "bigint"
console.log(typeof true);       // "boolean"
console.log(typeof "hi");       // "string"
console.log(typeof undefined);  // "undefined"
console.log(typeof null);       // "object"  (historic bug, kept forever)
console.log(Array.isArray([1, 2])); // true  (typeof [] is "object")

typeof works for most primitives, but null and arrays report "object". Use value === null and Array.isArray(value) to check them.

Conversion vs coercion

// Explicit conversion: you ask for it
Number("42");      // 42
String(42);        // "42"
Number("abc");     // NaN  ("Not a Number")
parseInt("42px");  // 42  (stops at the first non-digit)

// Implicit coercion: the language does it for you
"5" + 1;    // "51"  (+ with a string concatenates)
"5" - 1;    // 4     (- only works on numbers)
1 == "1";   // true  (loose equality coerces)
1 === "1";  // false (strict equality does not)

// Python, for comparison:
//   int("42")   -> 42
//   "5" + 1     -> TypeError: can only concatenate str (not "int") to str
//   str(5) + "1" -> "51"

Prefer explicit conversion. Implicit coercion makes code shorter but hides bugs, which is why JavaScript developers use ===.

How it works

Under the hood, every value is bits in memory. The type tells the program how to interpret those bits and which operations are allowed. The same 32 bits could be an integer, a float or four characters.

Primitive vs compound: numbers, booleans and (in most languages) strings are simple values. Collections and objects hold or point to other values.

Static vs dynamic typing: in C or Java, variables have declared types checked before the program runs. In Python and JavaScript, values carry their types and checks happen at runtime.

Strong vs weak typing (informal terms): Python is fairly strict about mixing types and raises errors. JavaScript is weakly typed: many operators coerce operands, following fixed rules (for example, + concatenates if either side is a string; -, * and / convert to numbers).

Strings are immutable in both Python and JavaScript: "changing" a string creates a new one.

Common types
  ├── Numbers ........ int / float (Python)   number / bigint (JS)
  ├── Boolean ........ True / False           true / false
  ├── Text ........... str                    string
  ├── Nothing ........ None                   null, undefined
  └── Collections .... list, tuple,           Array, Object,
                       dict, set              Map, Set

Why does it exist?

Types let the computer store values efficiently and apply the right operations: adding two numbers is different hardware work from joining two strings. They also catch mistakes. An error like "can't add a string to an int" points at a bug before it silently corrupts data.

When to use it

Think about types whenever data crosses a boundary:

- Input is almost always text (form fields, command-line args, files, query strings). Convert it to the type you need right away and validate it. - Output often needs text: format numbers and dates for display. - Calculations need numbers; make sure you're not adding strings. - Choose a collection type based on how you'll use the data.

When not to use it

Don't lean on implicit coercion to save a few characters (+"42", if (x == null) tricks) in code others must read; write the explicit conversion. Don't use floats for money or anything that needs exact decimals; use integer cents or a decimal type.

Common mistakes

  • Forgetting that input is text: input() in Python and form values in JavaScript return strings, so "2" + "3" gives "23".

  • Expecting exact decimal math from floats: 0.1 + 0.2 === 0.3 is false.

  • Checking for NaN with x === NaN, which is always false. Use Number.isNaN(x).

  • Using typeof x === "object" to detect objects in JavaScript; it's also true for null and arrays.

  • Using == in JavaScript and getting surprised by coercion (0 == "" is true). Use ===.

Practice exercises

  1. Easy:

    Ask the user for two numbers (with input() in Python or prompt() in a browser), convert them properly, and print their sum. Then remove the conversion and observe what happens.

  2. Medium:

    Write describe(value) in Python and in JavaScript that returns a string naming the value's type, correctly distinguishing integers, floats, booleans, strings, None/null, lists/arrays and dictionaries/objects.

  3. Hard:

    Write parseAge(text) that returns an integer age or raises a clear error for empty strings, non-numbers, decimals like "12.5", negatives and absurd values like 500. Write tests for each case.

Interview questions

What's the difference between type conversion and type coercion?

Conversion (casting) is explicit: the programmer calls int("5") or Number("5"). Coercion is implicit: the language converts automatically, as in "5" * 2 → 10 in JavaScript.

Why does `0.1 + 0.2` not equal `0.3`?

Floats are stored in binary, and 0.1 and 0.2 have no exact binary representation, much like 1/3 in decimal. The tiny rounding errors add up to 0.30000000000000004. Compare with a tolerance or use a decimal type when exactness matters.

What's the difference between `null` and `undefined` in JavaScript?

undefined means a value was never assigned (missing variables, properties, arguments or return values). null is an explicit "no value" that a programmer sets on purpose.

Why does `typeof null` return `"object"`?

It's a bug from JavaScript's first implementation, where null used the same type tag as objects. Fixing it would break existing websites, so it stays. Check with value === null instead.

Output-prediction (JavaScript): `"3" + 4 + 5` and `3 + 4 + "5"`?

"345" and "75". Evaluation is left to right: once a string is involved, + concatenates; before that, 3 + 4 is numeric addition.

What happens with `"5" + 1` in Python?

TypeError: can only concatenate str (not "int") to str. Python doesn't coerce between strings and numbers; you must convert explicitly with int() or str().

What is NaN, and how do you test for it?

"Not a Number", a special float value from invalid math like 0/0 or Number("abc"). NaN isn't equal to anything, including itself, so use Number.isNaN(x) in JavaScript or math.isnan(x) in Python.

What's the difference between static and dynamic typing?

Static typing checks types before running (C, Java, TypeScript), attaching them to variables. Dynamic typing checks at runtime (Python, JavaScript), attaching types to values, so one name can hold different types over time.

What's the difference between a primitive and a compound (reference) type?

A primitive is a single simple value like a number or boolean. A compound type (list, object, dict) groups other values. In Python and JavaScript, compound values are mutable objects accessed by reference, so two names can share one.

Scenario: an API returns a 19-digit order ID and your JavaScript code shows a slightly different number. Why?

JSON.parse turns it into a number, which is exact only up to 2⁵³−1 (about 16 digits), so it's rounded. Have the API send IDs as strings, or parse with a BigInt-aware parser.