← React / TypeScript

React / TypeScript · 02 / 18

Variables and data types in JavaScript

Use const and let and identify text, numbers, booleans and missing values.

  • Small
  • Basics
  • 15 min

Prerequisites: JavaScript: your first program

A variable name makes a value reusable. const prevents later reassignment. let permits it. JavaScript normally stores numbers as number and text as string. true and false are booleans. null is an intentionally missing value. undefined often means no value has been supplied or assigned yet.

Example files

01Associate names and values

const name = "House" assigns text to name. costCents uses let because we increase its value later. Names are case-sensitive. house and House would be different variables.

values.mjs · javascriptOpen file
const name = 'House';
let costCents = 12990;
costCents += 100;
const reminder = true;
const contractor = null;
console.log(`${name}: ${costCents / 100} EUR`);
console.log(typeof costCents, typeof reminder);
console.log(contractor ?? 'unknown');

Run / check

node values.mjs

02Compose text

A template string uses backticks. ${...} inserts a calculated value. The example divides integer cents by 100. The stored amount still remains an integer.

03Observe types

typeof returns a type description. The historical oddity typeof null === "object" does not make null a usable object. Check missing values explicitly. ?? selects a fallback only for null or undefined.

Expected result

House: 130.9 EUR. Then number, boolean and unknown.

Your exercise

Set contractor to an empty string. What does ?? print now?

Show the solution and explanation

An empty string is an existing value. ?? preserves it. If empty names are invalid in the domain, you need a separate check such as contractor.trim().length > 0 after checking the type.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.