JavaScript
Author

(Ackerman, 2024, pp. 31-45)

1.1 Fundamentos de programación

Antes de empezar a programar, necesitas comprender algunos conceptos básicos de la programación. ¿Por qué escribimos programas? ¿Cómo funcionan? ¿Qué papel juega JavaScript en este contexto? ¿Y en qué se diferencia de otros lenguajes de programación?

1.1.1 Comunicarse con la computadora

Empecemos por la pregunta de por qué queremos escribir programas, o mejor dicho, qué objetivo perseguimos al hacerlo. Básicamente, programar consiste en dejar que una computadora se encargue de ciertas tareas. Estas pueden ser, por ejemplo, problemas complejos que a los humanos nos costaría resolver por nosotros mismos o cosas que nos ayudan a trabajar con mayor eficacia en la vida cotidiana. Por ejemplo, pensemos en los procesadores de texto, los programas de correo electrónico o nuestro navegador. Todas estas herramientas han sido programadas por alguien.

En pocas palabras, la tarea de un desarrollador es dar instrucciones a la computadora para que pueda realizar las tareas asignadas. En otras palabras, como desarrollador, formulas pasos individuales para resolver un problema específico, como ordenar datos en una tabla o validar los datos de un formulario ingresados ​​en una página web. La computadora evalúa los pasos uno por uno. Esto es similar a una receta de cocina. En ella, también se definen los pasos individuales que debes seguir para alcanzar tu objetivo. En programación, el desarrollador es quien proporciona a la computadora una receta.

En resumen, los pasos para resolver un problema (es decir, la receta) en informática y desarrollo de software se conocen generalmente como algoritmos. Por lo tanto, un programa (también llamado software o aplicación) es una secuencia de algoritmos y, por lo tanto, una secuencia de instrucciones que la computadora puede ejecutar.

Definición

En el desarrollo de software, los pasos definidos para resolver un problema se denominan colectivamente algoritmo. Esto es comparable a recetas de cocina, instrucciones de uso o manuales. En este sentido, un algoritmo es un conjunto de instrucciones para que la computadora resuelva un problema específico.

Definición

Un programa o pieza de software está compuesto de numerosos algoritmos diferentes.

Al principio, a los principiantes en programación les suele resultar difícil pensar como una computadora y definir los pasos de un algoritmo en consecuencia. Al fin y al cabo, las computadoras siguen las instrucciones que se les dan con mucha precisión. Mientras que un ser humano siempre puede usar su mente al revisar una receta de cocina y variar ciertos pasos según su experiencia, una computadora asume que los pasos formulados deben llevarse a cabo exactamente como se indican. Por otro lado, esto también significa que, como desarrollador, usted debe formular las instrucciones con la misma precisión y ponerse en el lugar de la computadora.

TipTip

Cuando empecé a programar en el año 2000, me preguntaba constantemente cómo alguien podría aprender a escribir programas y admiraba a los desarrolladores experimentados por sus conocimientos. Después de todos estos años, puedo decirte: solo se aprende haciéndolo uno mismo. Por lo tanto, no solo deberías leer este libro, sino trabajarlo de verdad y crear programas tú mismo una y otra vez. Sin embargo, no te presiones demasiado ni te estreses si algo no funciona de inmediato. Al fin y al cabo, como desarrollador, necesitas una cosa más que nada: perseverancia y la voluntad de aprender algo nuevo cada día.

1.1.2 Programming Languages

Deep down, computers works with zeros and ones; that much is common knowledge. A more professional term for “zeros and ones” is binary code or machine code or machine language. The background for this binary code is the technical level that only knows two states: zero for “power off” and one for “power on”.

Simply put, various combinations of zeros and ones ultimately make the computer’s hardware do various things, such as display a pixel on you moniyor in this or that color, respond to mouse movements or keyboard input, or send an email over the network.

But because it would be incredibly complicated (and disproportionately time-consuming) for developers like us to phrase the instructions for the computer in zeros and ones, clever people at some point invented programming languages that abstract and simplify this interaction with the computer.

Programming languages can be further classified into different categories depending on their degree of abstraction. JavaScript is one of the so-called high-level programming languages so it abstracts relatively far from the zeros and ones. Assembly languages, on the other hand, are much less abstract. They don’t require you to work with zeros and ones either, but the commands used are nevertheless relatively cryptic, and programming is comparatively complex (see Figure 1.1). The commands you use in JavaScript, on the other hand, are quite catchy, understanddable, and easy to remember after you get used to them, as you’ll soon see.

NoteNote

JavaScript is a high-level programming language.

As a developer, you store everything you program via a programming language in ordinary text files called source files. The content of such a file is called source text or source code.

Definition

The source code is what you as a developer write in a given programming language. Machine code, on the other hand, refers to the code that is read and executed by the computer.

For the computer to understand and implement the instructions written in the source code, the source code must be translated to a format that the computer can understand—that is, to the previously mentioned machine code made of zeros and ones (see Figure 1.2).

Basically, there are two different ways to achieve this: via compilers or via interpreters. (Explanations of both will follow shortly.) Depending on whether a programming language uses a compiler or an interpreter, it is a compiled programming language, an interpreted programming language or a so-called intermediate language.

Before we explain the exact diferences among these three language types and clarify what a compiler or an interpreter is, let’s note one point: JavaScript is an interpreted programming language. This has advantages, but also disadvantages, as we will see in a moment.

Compiled Programing Languages

In this case of compiled programming languages, a compiler converts the source code into machine code or into an executable machine code file (see Figure 1.3). This happens by translating the instructions written in the source code into a sequence of instructions for the computer. Programs generated by a compiler in this way can then be executed directly on the operating system for which they have bee compiled, without the need for any other auxiliary components.

Examples of compiled programming languages include C and C++. For example, in order to run a program written in C++, it must first be converted using an appropriate C++ compiler. But because the latter differs between operating systems, a separate version must be compiled for every operating system (see Figure 1.4).

To this end, you need a separate compiler for every operating system. To run the program on Windows, it must first be compiled on Windows using an appropriate compiler. To run it on Linux, it must be compiled with a compiler on Linux, and the same applies to macOS if the program is to be run on a Mac. Although there are approaches to compile code on one operating system to run on another operating system (e.g., on Linux to run on Windows or vice versa; this technique is called cross-compilation), this does not change the fact that you have to spend quite a lot of effort to get a C++ program up and running on different operating systems. And we haven’t even considered the processor architectures (32 bit and 64 bit), each of which requires a different compilation method.

Despite all the effort required, compiled programs still have a crucial advantage that we mentioned in passing: the machine code generated in each case can be executed on the respective operating system without auciliary tools. Thus, no other programs need to be installed on the operating system to run a program compiled into machine code. This is a significant difference from interpreted programs, which we will discuss next.

Definition

Programs compiled for a specific operating system are also called native programs or native applications.

Interpreted Programming Languages

With interpreted programming languages

Intermediate Languages

Overview of Different Ptogramming Language

1.1.3 Tools for Program Design

Flowcharts

Pseudocode