[flaviocopes] The Programming Basics Course - The Main Concepts

After the introduction, let’s dive into some more advanced concepts of a how programming works, using the JavaScript language as an example

Input and output

A computer has one job. Wait for an input, do something (what we tell them, hopefully!) and return an output.

Yes, looks like they do a lot more. But if you bring things to simple terms, it’s all input and output. You open a program - you gave the input with a mouse click, or the command line. You click a button. You press a key. You … do things. The computer runs a program that is built to handle that input.

And the computer returns a result. Something moves on the screen. Words. Pictures. Things happen.

Internally, a lot happens between the time you give the input, and the time you receive the output. Which might be just a few milliseconds, but code (as we know) is executed really, really fast.

Variables

A variable is a way to store values into your programs, and to refer to them using meaningful names .

Suppose you have the number “5” and you want to give it a special meaning.

For example, the age of a child.

You can assign it to a variable. The exact syntax depends on the programming language, but in general terms you can imagine it being

childAge = 5

In JavaScript for example you would use

let childAge = 5

(read it as “let childAge be 5”)

Now you could use the childAge variable, which has the 5 value assigned, in other operations. Like printing:

print childAge
//this prints "5" to the screen

(I’m still using pseudocode)

Now, a variable can typically change its value.

If it’s the child birthday, you can change the value to

childAge = 6

Variables are an essential part of programming.

One thing that’s very important is naming your variables in the right way. As with many things, there’s no “one true way” of doing it. It also depends on your team, if you will work on a team. But one thing that is more or less universal is that it’s important to give variables a meaningful name, so that when you look at them in your programs, they can infer their meaning while you read the code.

childAge is a good example - it’s the age of a child.

Loops

Programmers are lazy people. Instead of repeating a task 10 times, they rather spend some time up front, create a procedure that can be repeated, and run that 10 times.

This can be done on several levels. By creating automated tasks for your day to day activities, for example.

When you do this inside your programs, that’s what we call a loop .

Here’s an example of a loop. It’s written using JavaScript:

const list = [1, 2, 3, 4, 5]
for (let value of list) {
  console.log(value)
}

This loop will run 5 times, exactly like the elements found in the list array, and will print the content it finds. The loop will automatically end when the list ends.

Some other kind of loops available in JavaScript do not have a fixed end like this. It’s the case of the while loop, which always checks for a condition before running the loop:

while (true) {
  //do something
}

In this case the condition is always true , so the loop will run forever. If you had

while (false) {
  //do something
}

the loop would never run, and the control goes to the instructions you give next.

Using loops you can usually decide to break when a particular situation happens.

In JavaScript this can be done using the break statement:

const list = [1, 2, 3, 4, 5]
for (let value of list) {
  console.log(value)
  break
}

This will break the loop at the end of the first execution, so instead of printing all the 5 numbers, it will only print one.

Loops can be tricky at times, but they are highly useful.

Conditionals

At some point in any program (as in life) you have to face a choice.

This is an essential part of programming.

Did the user type a number or a letter? Was it the number 1 or a number bigger than 5? Is this an image or a PDF file?

We call those conditionals . There is code that will only run if a condition is satisfied. Other code will not even run, if a condition is not met.

We wrap those portion of codes into blocks. In JavaScript, blocks are identified by parentheses.

The most common conditional is if . Available in most languages under this name, it verifies a condition before running the code contained in its block:

if (2 > 1) {
  //run this code
}

This is a simple example that always executes. Because 2 is bigger than 1. Usually you compare variables:

if (a > b) {
  //run this code
}

After an if statement you can link an else statement, to execute code if the if condition is not met:

if (a > b) {
  //run this code
} else {
  //run this other code
}

Those blocks can be nested, to create more complex scenarios:

if (a > b) {
  if (c > 5) {
    //run this code
  } else {
    //run this other code
  }
} else {
  //run this other code
}

Another conditional statement in JavaScript is switch . Compared to if , it allows for an easier definition of multiple choices:

switch (a) {
  case 1:
    //do something
    break
  case 2:
    //do something
    break
  case 3:
    //do something
    break
}

I mention JavaScript to give you the real syntax that you’re going to use, but those are all general constructs that you will find in many different languages, maybe slightly changed but more or less equivalent.

Another conditional in JavaScript is the ternary operator ?: which allows a more terse syntax:

isTrue ? /* do this */ : /* do that */

We’ll learn more about this, and the other conditionals, in the JavaScript Fundamentals course.

Functions

With variables, loops and conditionals you are already well equipped to create cool little applications.

Once you grow a certain point, however, it’s hard to keep things manageable. When you write down 100, 200, 500 lines of code, it’s all fun. But go past that number and you need a way to organize them.

Various programming languages have different ways to do so. JavaScript in particular offers one way using functions. Functions are not limited to JavaScript, of course - they are adopted into many others.

A function is a block of code with a name, which can be invoked and run when needed.

For example here’s a function:

function doSomething() {
  //code that is contained into doSomething()
}

Now into another part of the program you can call doSomething() and the code contained into it will execute.

Functions can accept arguments. In this way they can encapsulate a lot of functionality that the outer program does not need. If a function just needs a variable value to perform a calculation or save data to a database or communicate through the network, then that variable is all it should get from the rest of the program.

Here’s an example

function doSomething(aVariable) {
  //code that is contained into doSomething()
  console.log(aVariable)
}

Functions are great because they let you abstract your code, and reuse it in other places.

You can have multiple parts of a program share a common functionality into a function, so you don’t have to maintain a similar snippet of code in multiple parts of your codebase.

Modularizing the code into packages

Functions are great to organize code within one file, or a few files.

But what can you do when your files structure starts to become too crowded?

You reach for packages.

Packages are essentially similar to functions, except instead of abstracting away a piece of functionality to reuse in your program, you can remove them from your program altogether, and place them outside of it.

Multiple programs can now reuse a tiny functionality (or a bigger functionality) and you only have to maintain it in one place.

In JavaScript land, packages are commonly published to npm.

Importing a package is very easy, and it’s also common to create packages for all sort of things, even very small ones.

Other languages and communities have similar package repositories and ecosystems. Python has pip , for example.

It’s great when a language ecosystem is built around Open Source. JavaScript in particular is heavily rooted towards Open Source, and you can easily find free to use packages for nearly everything.

Types

We talked about variables before. A variable is a label associated to a value.

This value can has a type attached.

When it comes to types, you have 2 kind of programming languages: loosely typed and strongly typed.

And statically typed vs dynamically typed, but I won’t go into the explanation.

For now, just know that some languages really want you to deal with types, very explicitly, and some other languages let you be more dynamic. Typically, compiled languages are more strict on this matter.

JavaScript, Python, Ruby and other interpreted languages like to have loose types. Which means you can write

const number = 5

or

const name = 'Flavio'

without saying the first is a number, and the second is a string.

With JavaScript you’ll have several built-in types to work with: Object , Array , String , Number , Date , and more.

The type of a value identifies what you can do with it. It provides peculiar properties and methods you can call on it. For example a string can be trimmed using the trim() method. A number has other properties and methods.

In short, not all variables are equal.

Recursion

When we talked about function, I mentioned you can extract some portion of code, give it a name, and call it later.

For example say you have this code

const x = 1
const result = x * 2
console.log(result)
const anotherResult = 10 * 2
console.log(anotherResult)

You can take the x * 2 operation, assign it to a doubleNumber function:

function doubleNumber(num) {
  return num * 2
}

and now the code can be rewritten using

const x = 1
const result = doubleNumber(x)
console.log(result)
const anotherResult = doubleNumber(10)
console.log(anotherResult)

One interesting part is that functions can call themselves.

You might think: why? Or, why should I know this?

This has very practical implications, and can be especially useful when creating an algorithm, or a complex calculation.

The classic example is the factorial calculation. Given a number, the result should be the it, multiplied by the number - 1, multiplied by the number - 2, until you reach the number 1.

It’s hard to see how to create a general purpose function to solve this, until you add recursion to the mix:

function calculateFactorial(number) {
  if (number === 1) {
    return 1
  }
	return number * calculateFactorial(number - 1)
}

Objects

We introduced object oriented programming previously. This programming methodology, of course, is based on objects. But what are objects, exactly?

At some point during the global effort made by programmers to help themselves create better programs, faster, more efficiently and all, the idea came to introduce this concept of objects.

In object oriented programming, you define a set of classes, or types of objects.

An object is an instance of a class, and it contains both code and data. The data is abstracted away in to the object, and the object is responsible for providing methods (which are functions attached to an object) to manipulate this data.

Say you have a Dog class. You can create a myDog object by instantiating a new Dog:

const myDog = new Dog()

Roger is my dog’s name, so I can say so using

myDog.name = 'Roger'

A dog has an age:

myDog.age = 7

and we’ll have ways to retrieve this data.

The simplest way, in the case of JavaScript, is to just reference the property:

myDog.name //Roger

Here I defined public properties. In general, classes offer public and private properties. Private properties allow to encapsulate data, and only let it be accessed using methods that you define.

Now, we’ll talk a lot more about objects in the JavaScript Fundamentals course - in the meantime, I hope this little introduction served as an appetizer!

Data structures

During a Computer Science course, you’ll get a lot of education about data structures. They are a too broad field to be covered in this course (and I might create a dedicated course about them in the future!) but I will provide you a general introduction, just to know what they are all about.

Managing data is a complex problem. Especially organizing data in a way that’s efficient to store, and efficient to retrieve.

Sometimes the 2 things are not just compatible with each other, and depending on the application you need to create, you could choose one data structure over another.

Classic data structures are

  • set
  • stack
  • queue
  • struct
  • union
  • object
  • array
  • linked list
  • binary tree
  • graph
  • hash table
  • priority queue
  • heap

You might recognize some names here, as I talked about some of these things before. For example objects and arrays are implemented for you in JavaScript.

Data structures are very important to build efficient systems, but you might not find yourself in the situation where you have to pick an efficient storage system for your data right now, when you have zero programming experience.

My courses focus on JavaScript. With a low level programming language like C, for example, you don’t really have a lot of choices, because the language is very… primitive. And you need to learn data structures before you can write good code.

JavaScript is a higher level programming language, and you’re lucky that it can optimize things for you, without you having to do a lot of work.

As a beginning web developer you are not strictly required to jump into the complexity of data structures but I really encourage you to do so, when you’ll get better at your craft, even if they can take quite a bit of time to learn.

Algorithms

As with data structures, in a Computer Science course you’ll get to study algorithms a lot.

You might have heard the terms

  • bubble sort
  • quick sort
  • insertion sort
  • binary search
  • search by hashing
  • serial search

Most CS courses will introduce all of these, and you’ll get in all sorts of details about them. Not here, because we have very little time and lots of things to do! But I might create a dedicated course about them in the future, because they are important to know.

What’s very important is learning how to calculate the complexity of the algorithm. We call it Big-O .

Some algorithms scale very poorly with the growing amount of inputs.

Some others scale very well.

Ranging from most efficient to least efficient, here’s how we classify algorithms:

  • Constant - O(1)
  • Logarithmic - O(log n)
  • Linear - O(n)
  • Linearithmic - O(n log n)
  • Quadratic - O(n²)
  • Exponential - O(2^n)
  • Factorial - O(n!)  Let’s apply this to the time metric.

A constant efficiency means that if you have 1 input, or 10000 inputs, the time required to complete the algorithm is the same.

A linear efficiency means that the time required scales linearly with the number of inputs. 1 input equals to one second? Then 600 inputs equals to 10 minutes.

Of course it’s very hard to create efficient algorithms, and the more complex an algorithm is and the more central to the core business of your company/program, the bigger the benefits of making an algorithm more efficient.

GUI vs CLI

You can create (and find) many types of programs. We can generally classify them into 2 macro groups:

  1. programs that have a Graphical User Interface (GUI)
  2. programs that have a Command Line Interface (CLI)

The difference between the two is significant, and it’s the same between DOS and Windows, if you are familiar with those 2 environments.

Or the same between the Linux you run on a server, and the Gnome or KDE based Linux you run on your desktop computer.

GUI applications have an interface you interact with using the mouse, and you can clearly see it on the screen, typically inside a window, along with other GUI applications. Many GUI applications run at the same time.

A CLI applications is accessed from a terminal , a text based interface which only allows you to run one active application at a time.

Generally speaking, CLI applications are great for apps for pro users, that know how to access the terminal inside their system (it’s available on any kind of computer), and how to use any CLI app. They know how to find the help for the app, and are generally tech savvy.

A CLI application is the most flexible kind of application because the UI does not need to be filled with options - options are typed by the user if needed. They are best suited for one-time tasks. Or even long running tasks, provided you can run multiple terminal windows.

Think create-react-app , Vim, the C compiler, and more.

One special kind of CLI apps are backend applications that do not interface with the user on the system, but accept interactions across the network. In this case, the CLI is used to start (and stop) the application. Or to provide a way to instruct the system to run the application as a daemon (a long running process).

GUI applications on the other hand need a way to visually offer all the available options on the screen. They are best suited to provide rich interactions for mouse based inputs. Think Microsoft Word or Google Earth or the Chrome browser.

In JavaScript you will generally create both kind of applications. GUI apps using React, Vue, or any other framework that will run inside the browser (the actual GUI app, actually).

And CLI apps using Node.js, to provide services through network connections.