Basic Types & Annotations

JavaScript has several fundamental data types. Understanding these basic types and how to annotate them in code helps prevent errors and makes your code easier to read and maintain.

Illustration of Basic Types & Annotations
Illustration of Basic Types & Annotations

Primitive Types

  • Number: Represents both integer and floating-point numbers.
  • String: Textual data wrapped in quotes.
  • Boolean: Logical true or false values.
  • Undefined: Variable declared but not assigned a value.
  • Null: Represents an intentional absence of value.
  • Symbol: Unique and immutable value, often used as object keys.
  • BigInt: For integers larger than the Number type can safely represent.
JavaScript Basic Types Overview
TypeExample
Number42, 3.14
String'Hello', "World"
Booleantrue, false
Undefinedlet x;
Nullnull
SymbolSymbol('id')
BigInt9007199254740991n

Type Annotations (with JSDoc)

JavaScript itself is dynamically typed, but you can add type annotations via JSDoc comments to help tools like editors and linters understand your intended types.

📌 Deep Dive: Annotating Variables with JSDoc

JAVASCRIPT
/**
 * @type {number}
 */
let age = 30;

/**
 * @type {string}
 */
let name = "Alice";

/**
 * @type {boolean}
 */
let isActive = true;

💡 Why Use Type Annotations?

They improve code readability, enable better editor autocomplete, and help catch type-related bugs before runtime.

Dynamic Typing Notes

JavaScript variables can hold any type, and their type can change at runtime.

📌 Deep Dive: Dynamic Typing Example

JAVASCRIPT
let data = 42;      // data is a Number
data = "Hello";      // now data is a String
data = false;        // now data is a Boolean

⚠️ Watch Out for Type Confusion

Changing types can lead to unexpected behavior, especially in comparisons and arithmetic operations.

Summary Table: Type vs. Annotation

Type vs. Annotation
ConceptDescription
TypeThe actual data kind stored in a variable at runtime (e.g., number, string)
AnnotationA developer-added comment that states the intended type, used for tooling support

💡 Remember:

Type annotations do not enforce types at runtime in JavaScript but help developers and tools catch issues early.