Programming 101
What is a Computer Program?
Computers can read text and understand it in many different ways. A computer program is just some text we write for the purpose of having the computer translate it into instructions that the computer will perform after that.
The story begins with you writing that text, for example:
Add 5 to 2 then print the result to the screen
You write that text in a language; we call it a programming language. The language I used above is just English. We need to use one of the programming languages that computers can understand, like Java, Python, or JavaScript.
To write the computer program text above with JavaScript, here is the syntax that we need:
let result = 5 + 2; console.log(result);
We can now tell the computer to read this program’s text and translate it into instructions it can perform. Computers can only understand 1s
and 0s
, so the text above will be translated into a stream of 1s
and 0s
. Something like:
001010000111010101110100011000000111011011100101011100110111010101111100001101000010100001111101011000000011010100110000110101100110000011100100111101100001110011010110100111101111110010100110111111101101110011101010000111001111100011111110110111100101010001100100111010101010011011001010110100001110110011010010010101101001010
Once the computer has instructions written in 1s
and 0s
, it can use its resources (like CPU, memory, network) to perform these instructions. For our example, it will use the CPU to do the math, the memory to save the result, and the screen pixels to show you that result.
You can test the program text above in your browser’s development console or just head to jscomplete.com/playground and paste the code in the editor panel and hit the run button. The magic will happen in the background to show you the answer in the preview panel.
Of course, this is a very simple program text with clear instructions, but no matter how complicated the program gets it will really remain just that: a set of instructions that you write in a programming language which the computer is going to translate and execute line by line.
To be able to write useful computer programs, you need to learn the syntax of a computer language. Programmers are fluent in their computer languages of choice just as they are fluent with their human languages. Fortunately, learning a computer language is a lot easier than learning a human language.
So in the program text that we wrote above in JavaScript, what is “let
”, “console
”, “log
”, and why is every line terminated with a semicolon? This is all syntax that you need to be fluent in.
We will start with some basic concepts in this article, then will do a full overview of JavaScript syntax after that.
The Concepts of Variables and Expressions
When we write:
let result = ...
We are basically telling the computer to create a variable. This is just the terminology that you need to start using. A variable represents a storage unit, a place in the computer memory. The computer will simply reserve a space in its memory and label it as result
.
You can actually instruct the computer to just reserve the space (without any initial value set in it):
let undefVar;
With the line of code above, the computer will just reserve the space in its memory and label it as undefVar
. The value of this undefVar
remains undefined
.
However, when we defined the result
variable in the previous section, we also instructed the computer to perform a mathematical operation, take the result of that operation, and place it in the memory space that is to be labeled result
.
That happened when we wrote 5 + 2
, which is known as an expression in the programmers' terminology. This expression contains an operator (the +
sign). The computer recognizes this operator and the integer values. It performs the math operation and figures out that this expression is equal to 7
, which is the value it can now use to change the content of the memory space that it is going to label as result
.
The computer understands many other operators. Go ahead and try the characters -
, *
, and /
in place of the +
.
You can also combine operators to solve more complex mathematical expressions. Try this expression, for example: 2.2 + 0.8 * 5
. Note how the mathematical precedence rules apply here as well, and so is the use of parenthesis to indicate an alternative. Try (2.2 + 0.8) * 5
.
The many expressions you attempted above all resulted in values which were stored in the memory space labeled result
.
The semicolon is the JavaScript’s way of saying we are done with this line. Without it, the computer is going to attempt to join the next line with current one. For example, the same addition example can be written on multiple lines like this:
let result = 5 + 2; console.log(result);
Since the first line did not have a semicolon, the computer continues to the line after that and only concludes the operation when it sees a semicolon.
Let’s now understand the next line. What is this console.log
thing?!
The Concepts of Objects and Functions
In the new language terminology that we are learning, console
is called an object and log
is called a function. The log
function is a property of the console
object. Let’s walk through these new concepts one by one.
An object is a special variable in memory that represents a list of key-value pairs. It is a collection of memory spaces, not just a single space like what was reserved for the result
variable above. Every memory space allocated for an object can be identified by a property on that object, which is often called a key. For example, here is an object with three memory spaces labeled result1
, result2
, and result3
:
let obj = { result1: 1 + 2; result2: 3 + 4, result3: 5 + 6, };
In this example, the computer will allocate a collection of three memory spaces and collectively label them as obj
. Then, it labels the first space as result1
, puts a value of 3
there (after evaluating that expression), puts a value of 7
in the second space, and finally 11
in the third space.
We can read the values out of this object using the dot notation. For example, to use the value of the result2
property, we do:
obj.result2
We can also change the value of result2
using the same dot notation:
obj.result2 = 42;
We can also use the bracket notation to read and modify any property:
// Read Value obj['result2'] // Modify Value obj['result2'] = 42;
The bracket notation has its special uses but in most cases the dot notation is preferable. For now, just be aware that there is a bracket notation and always use the dot notation.
You can add and remove memory spaces (properties) from any object later on.
The console
object above had a single memory space labeled log
. That property has a special value stored in it: a function.
A function in a computer program is exactly like a function in Math. It is a relation between a set of inputs and a set of outputs.
After we define a function, we can call it. That is what we did with console.log;
we called it with a single input: the result
variable. To call a function in JavaScript, we simply use the parenthesis syntax: functionName()
.
The console.log
function takes the result
input and prints it out to the console screen. It does not do any transformation on the input. Functions can do that too.
We did not need to define the console.log
function because it is already defined internally in the browser’s engine. It is actually not part of the JavaScript language itself but rather added to the browser’s environment.
JavaScript comes with many other predefined functions. For example, there is a built-in Math
object that has many mathematical constants and functions to calculate trigonometric operations, logarithms, square roots, exponent powers, and many other mathematical operations. Here are a few Math
expressions you can explore:
console.log( Math.pow(2, 5) // 3 to the power 5 ); console.log( Math.log2(32) // base 2 logarithm of 32 ); console.log( Math.max(7, 42, 1) // maximum value among all arguments ); console.log( Math.sqrt(16) // square root of 16 );
As a coder, you will be writing a lot of functions. So let’s learn how to do that.
Defining Functions
The syntax to define a function in JavaScript is to use the keyword function and give the function a name. For example:
function add(arg1, arg2) { // Do a transformation on arg1 and arg2 // Then return a value }
I named the function add
and made it receive two inputs: arg1
and arg2
.
Arg is short for argument. A function can have zero or more arguments. Inside the function body, which we created using the *curly brackets, we will have *access to arg1
and arg2
once that function is called. For example, we can *call the function add
using this syntax:
add(10, 5);
This means: execute the body of the function add
above and while you do that, assign the value 10
to arg1
and the value 5
to arg2
.
Inside the function’s body, we continue writing our program text line by line. In the example above, I used comments inside the body. These comments are simply ignored by the computer. They are there for the human eye only. Any line that begins with //
is a comment line in JavaScript. Different computer languages will have different syntaxes for these concepts, but the idea is the same.
In JavaScript, you can also do multiline comments using the /* … */
syntax:
/* All this text will simply be ignored by the computer */
Let’s now replace the comments with something the computer can do. Here is an example implementation of the function add
:
function add (arg1, arg2) { let result = arg1 + arg2; return result; }
Every time the add
function is called (elsewhere in the program text), the computer will reserve a memory space and label that as result
. It will then evaluate the expression arg1 + arg2
using the values we pass to the add
function as arguments when we call it. It will then place the result of that operation in the memory space that is labeled result
.
The line that follows begins with a return
keyword. That is what the output of this function is going to be. In this example, the function reads the memory space labeled result
and returns that value as the output.
How do we test this function? A function call is also an expression, which means we can use that output as the value for another variable. For example:
let output = add(10, 5); console.log(output);
The function add
allowed us to abstract the addition operation into its own entity instead of doing that operation directly like the first example we started with. This is a useful concept in programming for many reasons, but most importantly:
-
Many programs can now call the same
add
function. -
If someone else manages the
add
function, we do not have to worry about what is going on inside it. We can just use the function to get the expected behavior. The owner of theadd
function might later decide to use a different implementation to perform the addition operation and in that case our program - that used the function - would not be affected. -
The owner of the
add
function can test that function in isolation of the code that actually uses the function.
Functions are very useful. Whenever we want to make code generic and reusable, we can abstract that code into a function and call that function instead.
Practice Challenges
1 - Write a function multiply
that takes three arguments and multiplies them together.
Here is an example of the expected output:
multiply(1, 2, 3); // should return 6 multiply(10, 10, 10); // should return 1000
Starting Template: jscomplete.com/playground/SkrzLayYZ
Solution: jscomplete.com/playground/Hyd2XEGYZ
2 - Write a function that will calculate the area of a triangle given a base and a height measurements.
Here is an example of the expected output:
triangleArea({ base: 15, height: 4 }) // should return 30 triangleArea({ base: 6, height: 9 }) // should return 27
Hints:
-
The
triangleArea
function will receive one argument that will be an object. That object will have two properties:base
andheight
. -
You can use the dot notation to access these properties inside the function’s body.
Starting Template: jscomplete.com/playground/HyK4zVzFW
Solution: jscomplete.com/playground/r1VEmNztZ