How does a programming language work?
🇪🇸Puedes leer la versión en Español aquí
If you think about it, programming languages aren’t so different from any human language: each language has its own set of rules, what we know as grammar, so that what we say makes sense.
Although each language has its nuances, in most Romance languages (English, Spanish, French, Italian, and Portuguese) the basic sentence follows the pattern subject + verb + complement.
In code something very similar happens: we use sequences of expressions and statements that organize the program flow and make instructions clear and easy to follow sequentially. This organization not only facilitates reading and understanding, but also helps keep code understandable and easier to improve over time. 🤖
Expressions
An expression is a combination of certain elements that are evaluated to produce a result.
Let’s see some examples of expressions:
- The expression
5 + 3uses the addition operator to operate the numeric values5and3. This operation returns as result the numeric value8. - The expression
x * yuses the multiplication operator to operate the variablesxandy, whose values are unknown. Once concrete values are assigned to these variables, we can determine the resulting value of the operation. - The expression
"Hello " + namemakes use of the concatenation operator to join the string value"Hello "with the variablename. The result of this operation is unknown until a specific value is assigned to the variablename. - The expression
f(x) = x^2uses the power operator to square the variablex. Although the result of this expression is a numeric value, it remains unknown until a specific value is provided forx. It’s important to mention that this expression is actually a function that can evaluate various values forx. For example, ifx = 3, thenf(3) = 9.
🚜 A function is a process that takes certain values and transforms them into outputs of other values according to specific rules.
Let’s look in detail at each of the possible elements that an expression can contain: values, variables, operators, and functions.
Values and types
In programming, information is represented through values, and each value belongs to a specific type. These types determine how values are manipulated and stored in memory.
Let’s see some examples of the most commonly used values:
- When performing mathematical operations, numeric type values are used, similar to those we use daily:
6,32,0,-13,π(the value of Pi),9.99, and even∞(infinity). - To print a value on screen, string type values are used, which are written in quotes. For example
"A","Hello","10"(which is different from the number10),"🥸"(emojis), and special characters like the letter"ñ"or symbols"©"(copyright). - When making decisions within a program, boolean type values are used. These can only have two states:
trueorfalse.
📫 Boolean values are usually called flags (flags) where a flag up indicates
true, (activated) while a flag down indicatesfalse(deactivated).
ℹ️ Each programming language handles a variety of values and types. Later we’ll delve into the specific types that JavaScript supports.
Variables
Variables in programming help us manage and organize information. Imagine they’re like folders on a desk. Each folder has a label with a unique name to identify what it contains. These folders, in turn, can house one or several documents, which would represent our values.
📁 Think of a variable as a folder labeled with a unique name, ready to store a value.
Variables have multiple functions, but for now, we’ll focus on two main aspects:
- Data storage: As we mentioned before, variables are like folders where you can save and access essential data, such as total sales or inventory summary. This way, you’ll always have that information at hand when you need it.
- Dynamic data handling: Imagine you have a document that’s constantly updated, it could be a report of events from the last seven days. Variables allow you to “capture” that changing data and adapt to different circumstances.
Let’s see some examples:
- The variable
agestores numeric values that represent a person’sage. For example, if we assignage = 25, the variable age contains the value25. - The variable
namecould store string type values. By settingname = "Lucía", we’re assigning tonamethe text value"Lucía". - The variable
isStudentis of boolean type, which means it can only have two possible values:trueorfalse. So, if we determine that a person is a student, we would assign the valueisStudent = true; if not, it would beisStudent = false.
What’s valuable about variables is that, once assigned, they preserve the values for later use. Simply by referencing the variable name, we can access its content. For example, when referring to the variables age, name, and isStudent, we know we’re talking about Lucía, who is 25 years old and is a student.
Operators
For values and variables to be useful, it’s necessary to be able to manage operations that allow us to obtain a result.
Operators are usually represented through symbols or reserved words. Depending on the types of values, we can perform certain types of operations.
At this point it’s important to clarify that a variable will always contain a value. Therefore, operations are performed regardless of whether those values are represented in variables or not.
For example, the addition operator (+) performs the sum of two numeric values, like 2 + 3, whose result would be the numeric value 5. But this same operator, used on string values, creates a concatenation. For example, "Hello" + " world", would give as result the string: "Hello world".
Let’s see below some operators, keeping in mind that each programming language has extensive collections of operators:
Arithmetic operators
- The addition operator
+: Used to add two values, like in2 + 3, resulting in5. - The multiplication operator
*: Used to multiply two values, like in4 * 6, obtaining24as result.
In this category are the most common mathematical operators like subtraction, division, power, modulo, among others.
Assignment operators
- The simple assignment operator
=: Sets a value to a variable. For example,x = 5means that the value ofxis now5. - The compound assignment operator
+=: Adds the provided value to the previous value of the variable. In the case ofx += 3, it’s equivalent tox = x + 3, incrementing the value ofxby3.
⚠️ The assignment operator should not be confused with equality or equivalence in mathematics. The expression
x = x + 1mathematically doesn’t make sense, while in programming we’re incrementing the value ofxby 1.
Comparison operators
- The equality operator
==: checks if two values are equal. For example,x == 2, which would be true as long as the value ofxis2. - The
>=operator checks if the value on the left is greater than or equal to the value on the right. For examplex >= 5, would be true for the number5and any number greater than5.
Here would be the rest of comparison operators such as “greater than”, “less than”, “less than or equal to”, etc.
These operators make sense when used with variables, since it’s in this way that algorithms could behave one way or another depending on the value these take.
Logical operators
- The conjunction operator
&&: returnstrueif both expressions are true. It’s usually used together with comparison operators, for example:x > 5 && y < 10this expression would be true as long asxis greater than5andyis less than10. - The negation operator
!: returns the opposite value of a boolean expression. If for examplex > 5weretrue, that isxis greater than 5, then!(x > 5)would be false. This is very useful when we want to make a decision based on an opposite result, in the previous example!(x > 5)would only betrueifxis5or less than5.
Here we would have other operators, like conjunction and a series of binary or exclusion logical operators that we’ll review later.
Functions
Although functions are a mathematical term that takes variables and transforms them into outputs, they are also usually used in programming to encapsulate a piece of code and reuse it more easily.
The first use is more related to expressions while the second use represents a statement, that is, functions can be represented both as expressions and statements.
Let’s see some examples of function expressions.
- The function expression
f(x) = x + 2uses the addition operator to increment the variablexby 2. This function will return a numeric value, as long as the value ofxis also numeric. - The function expression
f(a, b) = (a - b) * 5uses multiple operators and also defines two parametersaandb. It will perform a subtraction ofaandband multiply that result by 5. As long asaandbare numeric values, this function will return a numeric value.
🪂 Unlike other expressions, the variables that are listed in the definition of a function, for example,
x,a, andbare called parameters.
⚙️ When we evaluate a function and replace its parameters with values, we call those values function arguments.
In general, the purpose of a function is to be able to reuse them to be called with different arguments, that is, so that their parameters have different values.
In our first example, if we give as argument the number 3, then the parameter x would be replaced by that value, and thus the function would be evaluated as f(3) = 5, giving as result the number 5.
Also, we could call the same function this time with the argument of the number 10, making the evaluation this time be f(10) = 12, returning the number 12.
🏭 Functions can become much more complex than the examples shown so far, they can contain from simple expressions, to even other functions with multiple arguments or no arguments and return values that don’t match the parameter values or even not return a value.
Let’s analyze an expression
Now that we understand everything that can compose an expression: values, variables, operators, and functions, let’s do an analysis of the following expressions:
life = 42- Values: The number
42is a numeric value. - Variables:
lifeis a variable that will store the value. - Operators:
=is an assignment operator.
- Values: The number
f(x) = 2x + b- Values: The number
2is a numeric value - Variables:
xis a variable that acts as a parameter,bis an external variable. - Operators:
=is an assignment operator,*(implicit in2x) is a multiplication operator,+is an addition operator. - Functions:
f(x)is a function that takes a parameterx.
- Values: The number
"👩" + "\u200d" + "🚀"- Values:
"👩","\u200d", and"🚀"are string type values. - Operators:
+is a text concatenation operator.
- Values:
Statements
Let’s remember again the definition of expression:
🧠 An expression is a combination of certain elements that are evaluated to produce a result.
But we’ve seen that there are operators that don’t necessarily produce a result like the assignment operator.
Also, in the example of our function f(a, b) = (a - b) * 5 its body (a - b) * 5 actually contains 2 expressions:
- The arithmetic expression
a - bthat produces a numeric result. - The arithmetic expression that uses the product operator to multiply the result of the previous expression
(a - b)with the number5, thus generating a new numeric result.
🤯 Statements are nothing more and nothing less than a set of one or multiple expressions, which may or may not produce a value.
Let’s analyze the following statement and the expressions that compose it: a = b * 2
2is a literal value expression.bis a variable expression.b * 2is an arithmetic expression.a = b * 2is an assignment expression.
Expressions in a statement
Since we know that a statement is a set of expressions, let’s analyze some examples of statements that contain them. It’s important to remember that each programming language allows certain types of expressions within a statement.
Below, let’s review the most common ones:
- Literal value expression: Represents constant and fixed values, like numbers, text strings, or boolean values. These expressions don’t depend on variables or additional calculations.
42;
("Hello world");
- Variable expression: Involves a variable that stores data and can be used to access those values.
age = 33;
age;
- Arithmetic expression:
Performs mathematical operations using arithmetic operators like
+,-,*,/, and%.
3 + 7;
15 / 3;
- Logical expression:
Evaluates conditions using logical operators like
&&,||, and!. The result is always a boolean value (trueorfalse).
true && false;
!true;
- String expression: Allows concatenating, manipulating, or evaluating operations with text strings.
"Hello" + " world";
- Relational expression:
Compares two values using operators like
<,>,<=,>=,==, and!=. Returns a boolean result.
5 < 10;
4 != 7;
- Conditional expression:
Uses the ternary operator (
? :) to evaluate a condition and return a value depending on whether the condition is true or false.
age = 20;
result = age > 18 ? "Adult" : "Minor";
- Function call expression: Executes a function and returns the result it generates, if any.
console.log("Hello world");
- Assignment expression: Assigns a value to a variable using the assignment operator (=).
x = 5;
y = x + 3;
Statements that don’t return a value
In programming, there are statements that execute a series of instructions without directly producing an output value.
Even so, they are essential for controlling the program execution flow, some examples are:
ifstatement: Evaluates a condition and executes a block of code if the condition is true.
if (age > 18) {
console.log("👵");
}
returnstatement: Used within a function to end its execution and, optionally, return a value.
function f(x) {
return;
};
Function statements
In some programming languages, functions can exist both as statements and expressions.
Functions as statements:
A function declaration is normally defined as a statement. Example:
function f(x) {
return x + 2;
}
Functions as expressions:
Functions can also be expressions and can be assigned to variables. Example:
g = (x) => x * 2;
Here, g is an anonymous function assigned to a variable.
Programming languages are more than syntax
Although initially values, variables, operators, and functions may seem like just symbols and syntax rules, in practice these fundamental elements allow us to build solutions to complex problems.
They are the basic pieces with which we can create from simple calculators to sophisticated artificial intelligence systems.
Understanding how these elements work is the first step to unleashing the true potential of any programming language.