Junior — Middle
How do imperative and functional programming approaches differ?
sobes.tech AI
Answer from AI
The imperative programming style focuses on how exactly a task should be performed — it describes a sequence of steps and changes to the program's state. In this style, code often contains loops, assignments, and modifications of variables.
The functional programming style is oriented towards describing what should be done, not how. It uses pure functions without side effects, avoids changing state and data, and prefers immutability. Higher-order functions, recursion, and function composition are often used.
Example in Python:
# Imperative style
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
squares.append(n * n)
# Functional style
squares = list(map(lambda x: x * x, numbers))
In the functional style, code is more declarative and easier to test, as functions do not modify external state.