KAHIBARO
Discord Login Register

4.1. Variables and Data Types

Why Variables and Data Types Matter

Backend code constantly works with information. You receive data in requests, save it to databases, process it, and send it back in responses. To do this safely and predictably, you must:

If you ignore types, you get bugs that are painful to debug: wrong calculations, broken comparisons, and crashes.

In this chapter we will stay language agnostic, but examples will look somewhat like Python or JavaScript style pseudocode.

Variables: Names for Values in Memory

A variable is a named box that holds a value in your program's memory.

txt
x = 5

You can read that as: “Create a box called x and put the value 5 into it.”

Creating and Using Variables

Most languages follow this pattern:

text
# Pseudocode
# Declare and assign
count = 10
# Read the value
print(count)        # shows 10
# Change the value
count = count + 1   # now 11

In typed languages you often must specify the type:

text
int count = 10
count = count + 1

In more dynamic languages, the type is inferred from the value:

text
count = 10          # the language decides "this is an integer"

Naming Variables

Good variable names make code easier to understand. You will continually read and modify your own code and other people's code, so names matter.

Rules and Conventions

Most languages have similar rules:

Common naming styles:

StyleExampleWhere used
snake_caseuser_namePython, configuration, many backend scripts
camelCaseuserNameJavaScript, Java
PascalCaseUserNameClass names in many languages
SCREAMING_SNAKE_CASEMAX_RETRIESConstants

Good names describe what the variable represents, not how it is used:

text
# Bad
x = 7
# Better
max_login_attempts = 7

Variables vs Constants

A constant is like a variable, but its value should not change after it is set.

text
# Pseudocode
MAX_CONNECTIONS = 100    # We agree never to reassign this

Some languages let you enforce this:

text
const MAX_CONNECTIONS = 100  # cannot be changed later

Use constants for values such as:

This reduces accidental changes and makes your intent clear.

Data Types: Kinds of Values

A data type describes what kind of value is stored and what operations are allowed.

Common groups of data types:

Important rule
Every value has a type, and operations only make sense when types are compatible.
For example, 5 + 3 is fine, 5 + "hello" is usually an error or produces unexpected results.

Numeric Types

Backend systems use numbers for counts, prices, timestamps, IDs, and more.

Integers

An integer is a whole number, positive, negative, or zero.

text
user_count = 120
temperature = -5
zero = 0

Typical operations:

text
a = 5
b = 2
sum        = a + b    # 7
difference = a - b    # 3
product    = a * b    # 10
quotient   = a / b    # depends on language: 2 or 2.5
remainder  = a % b    # 1, "modulo"

Floating Point Numbers

A floating point number represents real numbers with decimals.

text
price = 9.99
rating = 4.5
pi = 3.14159

Use them for:

Precision Issues

Floating point numbers are stored in binary, so some decimals are not exact.

Examples in many languages:

text
0.1 + 0.2         # might give 0.30000000000000004
0.3 == 0.1 + 0.2  # often false

For money and financial calculations, you usually should not use plain floating point types. Many backend systems use:

Boolean Type

A boolean has only two values:

Examples:

text
is_admin = true
email_verified = false
has_paid = true

Booleans are crucial for conditions and control flow, which you will use in other chapters like Conditions and Loops.

Typical boolean operations:

text
has_account = true
has_paid    = false
can_login = has_account AND has_paid   # false

Some examples of boolean expressions:

text
age = 20
is_adult = age >= 18        # true
items_in_cart = 0
cart_is_empty = items_in_cart == 0  # true

Strings: Text Data

A string is a sequence of characters, used for text.

text
name = "Alice"
greeting = 'Hello'
message = "User not found"

You work with strings constantly in backends:

Common String Operations

Here are common operations and what they do conceptually:

text
first_name = "John"
last_name = "Doe"
# Concatenation (joining)
full_name = first_name + " " + last_name   # "John Doe"
# Length
len("Backend")  # 7 characters
# Access character by index (0 based)
"Backend"[0]    # 'B'
"Backend"[3]    # 'k'
# Substring
"Backend"[0:4]  # "Back"  (syntax varies by language)

String methods are very common:

text
"hello".upper()        # "HELLO"
"HELLO".lower()        # "hello"
"  spaced  ".strip()   # "spaced"
"admin@example.com".ends_with("@example.com")  # true

When building SQL queries or JSON, you must be very careful with string handling to avoid security issues like SQL injection. That is covered later in the Backend Security and SQL chapters.

Collections: Grouping Values

Backend applications often need to handle many items at once:

For that you use collection types.

Lists and Arrays

A list or array is an ordered collection of values, like an ordered row of boxes.

text
# A list of integers
scores = [10, 20, 30]
# A list of strings
usernames = ["alice", "bob", "charlie"]

Typical operations:

text
numbers = [1, 2, 3]
# Access by index (0 based)
numbers[0]   # 1
numbers[2]   # 3
# Change a value
numbers[1] = 20         # [1, 20, 3]
# Add an item
numbers.append(4)       # [1, 20, 3, 4]
# Length
len(numbers)            # 4

Lists are useful when:

Maps / Dictionaries / Hash Tables

A map is a collection of key value pairs. In various languages it may be called:

Example:

text
user = {
  "id": 123,
  "name": "Alice",
  "email": "alice@example.com"
}

Here:

To read values by key:

text
user_id = user["id"]        # 123
email  = user["email"]      # "alice@example.com"

To add or change:

text
user["is_admin"] = false    # add new key
user["email"] = "alice@newmail.com"  # update existing

Maps are critical in backend work:

Sets

A set is an unordered collection of unique items.

text
countries = {"US", "DE", "FR"}
# Adding duplicate has no effect
countries.add("US")   # still {"US", "DE", "FR"}

Sets are useful when:

Examples for backends:

Null, None, and Missing Values

Sometimes a variable has no value. Many languages use special values for this:

Use these to mean:

Example:

text
last_login_at = null    # user has never logged in

When working with null values, you must always be careful:

text
user = null
# user["name"]      # often causes an error, trying to access a property of null

Instead, you check first:

text
if user is not null:
    name = user["name"]
else:
    name = "Guest"

Static vs Dynamic Typing

Languages differ in how strictly they handle types. As a backend developer you will likely use both kinds over your career.

Statically Typed Languages

In statically typed languages, the type of each variable is known at compile time.

Examples: Java, C#, Go, TypeScript (for frontend but concept applies)

text
int    age = 30
string name = "Alice"
bool   is_admin = false

Characteristics:

Dynamically Typed Languages

In dynamically typed languages, variables do not have fixed types, values do.

Examples: Python, Ruby, JavaScript, PHP

text
age = 30         # now holds an integer
age = "thirty"   # now holds a string

Characteristics:

Both approaches are heavily used in backend development. Python and JavaScript are common dynamic choices, Go and Java are common static choices.

Type Conversion

Sometimes you must convert from one type to another. This is called type casting or type conversion.

Common Conversions

From string to number:

text
age_str = "25"
age = int(age_str)   # 25
price_str = "9.99"
price = float(price_str)  # 9.99

From number to string:

text
user_id = 123
user_id_str = str(user_id)   # "123"

From string to boolean, usually custom:

text
value = "true"
is_enabled = (value.lower() == "true")   # true

From list of pairs to map:

text
pairs = [["id", 1], ["name", "Alice"]]
user = dict(pairs)  # {"id": 1, "name": "Alice"}

Implicit vs Explicit Conversion

Implicit conversions can be convenient, but also dangerous, for example in some languages:

text
1 + "2"    # might become "12" by converting 1 to "1"

As a backend developer handling user data, API inputs, and database values, it is usually safer to perform explicit conversions so behavior is clear and predictable.

Practical Backend Examples of Types and Variables

To see how these concepts appear in real backend code, here are some typical patterns in pseudocode.

Storing Request Data

You receive JSON in an HTTP request:

json
{
  "email": "user@example.com",
  "age": 25,
  "is_admin": false,
  "tags": ["new", "beta"]
}

You might parse it into variables and proper types:

text
body = parse_json(request.body)
email    = body["email"]        # string
age      = int(body["age"])     # integer
is_admin = bool(body["is_admin"])  # boolean
tags     = body["tags"]         # list of strings

Building a Response

You collect values from variables and build a response dictionary or map:

text
user = {
  "id": 101,
  "email": email,
  "age": age,
  "is_admin": is_admin,
  "tags": tags
}
response_body = to_json(user)

Using Types for Validation

You may check types and values to validate an API request:

text
if type(age) is not int or age < 0:
    return error_response("age must be a non-negative integer")
if type(email) is not string or "@" not in email:
    return error_response("invalid email")

Common Beginner Mistakes with Types and Variables

These issues show up often in backend beginners' code.

ProblemExampleWhy it is bad
Reusing variable for different typesuser = 1, then user = "Alice"Makes code confusing and error prone
Confusing string and number"10" + 5May crash or give "105" instead of 15
Ignoring null / None checksuser["name"] when user might be nullCauses runtime errors in production
Using unclear namesx, y, data, temp for important variablesFuture you will not understand the code
Assuming type from appearance"00123" looks numeric but may be important as text, e.g. zip codesConverting may lose leading zeros

Summary

You have seen:

You will use these concepts in every other chapter, from Conditions and Loops to Databases and REST APIs. Understanding variables and data types now will make the rest of backend development much easier to learn.

Views: 9

Comments

Please login to add a comment.

Don't have an account? Register now!