Expressive JavaScript: Introduction

Original author: Marijn Haverbeke
  • Transfer


Translation of Marijn Haverbeke's Eloquent JavaScript . License the Creative
Commons Attribution-noncommercial license
. The code is licensed under MIT .


Content




This book tells how to get computers to do what you need from them. Computers are just as common today as screwdrivers - but they contain far more hidden complexities and are therefore harder to understand and harder to work with. For many, they remain alien, slightly threatening things.



We found two effective ways to reduce the communication gap between us - watery biological organisms that have a talent for social connections and lengthy reasoning, and computers - insensitive manipulators that work with meaningless data. The first is to turn to our sense of the physical world, and build interfaces that mimic it so that we can use our fingers to manipulate the forms on the screen. For a simple interaction with a computer, this is not bad.

But we did not find a good way to transfer to the computer with the help of movements and mouse clicks those things that the interface designer did not provide. In order to interact with a computer at more complex levels, for example, ask it arbitrary tasks to perform, our communication talent is better suited: we teach a computer language.

Human languages ​​allow you to combine words in a great many ways, so that we can say so many different things. Computer languages ​​are arranged in much the same way, although less grammatically flexible.

Over the past 20 years, working with a computer has become very common, and interfaces built on a language (and once it was the only way to communicate with a computer) are almost replaced by graphical ones. But they are still there - if you know where to look for them. One of these languages, JavaScript, is built into almost any web browser, and therefore is available on almost every computing device.

This book aims to introduce you to this language enough so that you can get the computer to do what you need.

About programming


I do not enlighten those who are not eager to learn, and I do not encourage those who do not want to seek answers on their own. If I show one corner of the square, and they do not come to me with the other three, I do not need to give repeated explanations.

Confucius


In addition to explaining JavaScript, I also want to explain the basic principles of programming. As it turns out, programming is hard. Typically, the basic principles are simple and straightforward. But programs built on these principles become so complex that they introduce their own rules and difficulty levels. You build your own maze, and you can get lost in it.

Perhaps at times reading will disappoint you. If you are new to programming, you will need to digest a lot. A lot of material will be combined in such a way that you will need to establish new relationships between its parts.

You yourself must justify the need for these efforts. If it’s hard for you to get through a book, you don’t need to think badly about yourself. Everything is all right with you - you just need to continue moving. Take a break, go back - and always make sure that you read and understand the sample programs. Training is a difficult job, but once you have learned something, it already belongs to you, and facilitates further steps.

The programmer creates universes for which he alone is responsible. In computer programs, universes of virtually unlimited complexity can be created.

Joseph Weisenbaum, “The Power of Computers and the Mind of People”


The program is a complex concept. This is a piece of text typed by a programmer, it is a guiding force that forces the computer to do something, it is data in the computer's memory, and at the same time it controls the work with the same memory. Analogies that try to compare programs with objects we know are usually not up to the task. One more or less suitable is the analogy with a machine. Many separate parts make up one whole, and to make it work, we need to imagine the ways in which these parts interact and what they bring to the work of the whole machine.

A computer is a machine that is designed to contain these intangible machines. Computers themselves can only perform simple actions. Their benefit is that they can do it very quickly. A program can combine these actions in a very clever way so that very complex actions are performed as a result.

For some of us, programming is a fun game. A program is a mental construct. It costs nothing to build it, it weighs nothing, and it easily grows under our fingers.

If not careful, size and complexity get out of hand, confusing even the person who writes it. This is a major programming problem: maintaining control of programs. When the program works, it's great. The art of programming is the ability to control complexity. A large program is under control, and is simply completed in its complexity.

Many programmers believe that this complexity is best managed using a small set of well-known techniques in programs. They described strict rules (“best practices”) about what form programs should have. And the most zealous among them consider those who deviate from these practices to be bad programmers.

What kind of hostility towards the wealth of programming - attempts to reduce it to something straightforward and predictable, to taboo all sorts of strange and beautiful programs! The landscape of programming techniques is enormous, captivating with its diversity, and so far little studied. This is a dangerous journey that lures and confuses an inexperienced programmer, but it just means that you must follow this path carefully and think with your head. As you learn, you will always meet new challenges and new uncharted territories. Programmers who do not learn new things stagnate, forget their joy, their work bores them.

Why language matters


In the beginning, at the birth of computer disciplines, there were no programming languages. The programs looked like this:

00110001 00000000 00000000
00110001 00000001 00000001
00110011 00000001 00000010
01010001 00001011 00000010
00100010 00000010 00001000
01000011 00000001 00000000
01000001 00000001 00000001
00010000 00000010 00000000
01100010 00000000 00000000


This is a program that adds numbers from 1 to 10, and displays the result (1 + 2 + ... + 10 = 55). It can be run on a very simple hypothetical machine. To program the first computers, it was necessary to install large arrays of switches in the desired positions, or to punch holes in punch cards and feed them to the computer. You can imagine what a tedious, error-prone procedure it was. Writing even simple programs required a lot of intelligence and discipline. Complex programs were almost unthinkable.

Of course, manually entering these mystical bit patterns (zeros and ones) made it possible for the programmer to feel like a wizard. And it was worth something in the sense of job satisfaction.

Each line of the specified program contains one instruction. In ordinary language, they can be described as follows:

  1. write 0 to memory 0
  2. write 1 to memory 1
  3. write the value of cell 1 to cell 2
  4. subtract 11 from cell value 2
  5. if cell 2 has value 0, then continue from step 9.
  6. add cell value 1 to cell 0
  7. add 1 to cell 1
  8. continue with point 3.
  9. print cell value 0


This option is easier to read than a bunch of bits, but it is still not very convenient. Using names instead of instruction numbers and memory locations can improve understanding.

  установить ‘total’ в 0
  установить ‘count’ в 1
[loop]
  установить ‘compare’ в ‘count’
  вычесть 11 из ‘compare’
  если ‘compare’ равно нулю, перейти на [end]
  добавить ‘count’ к ‘total’
  добавить 1 к ‘count’
  перейти на [loop]
[end]
  вывести ‘total’


Now it’s not so difficult to understand how the program works. Can you handle it? The first two lines assign the initial values ​​to the two memory areas. total will be used to calculate the result of the calculation, and count will monitor the number with which we are currently working. Lines using 'compare' are probably the strangest ones. The program needs to understand if count 11 is not equal to stop counting. Since our imaginary machine is quite primitive, it can only perform a check on the equality of the variable to zero, and decide whether to jump to another line. Therefore, it uses a memory area called 'compare' to calculate the value of count - 11 and make a decision based on that value. The next two lines add count to the result counter and increment count by 1 each time

Here is the same JavaScript program:

var total = 0, count = 1;
while (count <= 10) {
  total += count;
  count += 1;
}
console.log(total);
// → 55


A few more improvements. The main thing - there is no need to manually indicate the transitions between the lines. The while language construct does this on its own. She continues to calculate the block enclosed in braces until the condition is satisfied (count <= 10), that is, the value of count is less than or equal to 10. It is no longer necessary to create a temporary value and compare it with zero. It was boring, and the power of programming languages ​​is that they help get rid of boring details.

At the end of the program, upon completion of the while operation, the console.log operation is applied to the result for the purpose of output.

And finally, the program might look like this if we had convenient range and sum operations, which, accordingly, would create a set of numbers in a given interval and calculate the set amount:

console.log(sum(range(1, 10)));
// → 55


The moral of this fable is that the same program can be written both long and short, readable and unreadable. The first version of the program was completely vague, and the last - almost a real language - to write down the sum of the range of numbers from 1 to 10. In the following chapters we will look at how to do such things.

A good programming language helps the programmer to inform the computer about the necessary operations at a high level. It allows you to omit boring details, provides convenient building blocks (while and console.log), allows you to create your own blocks (sum and range), and makes combining blocks simple.

What is javascript?


JavaScript was introduced in 1995 as a way to add programs to web pages in the Netscape Navigator browser. Since then, the language has taken root in all major graphical browsers. It made it possible for modern web applications to appear - browser-based email clients, maps, social networks. And it is also used on more traditional sites to ensure interactivity and all kinds of bells and whistles.

It is important to note that JavaScript has little to do with another language called Java. A similar name was chosen for marketing reasons. When JavaScript appeared, the Java language was widely advertised and gained popularity. Someone decided that it would be nice to cling to this engine. And now we are not going anywhere on this behalf.

After the language went beyond Netscape, a document was written describing the work of the language so that the different programs that declare its support work the same way. It is called an ECMAScript standard by the name of an ECMA organization. In practice, you can talk about ECMAScript and JavaScript as the same thing.

Many people criticize JavaScript and say a lot of bad things about it. And much of this is true. The first time I had to write a program in JavaScript, I quickly felt disgusted - the language accepted almost everything that I wrote, while interpreting this not at all as I meant. This was mainly due to the fact that I had no idea what I was doing, but there was a problem: JavaScript is too liberal. It was conceived as a facilitation of programming for beginners. In reality, this makes it difficult to find problems in the program, because the system does not report them.

Flexibility has its advantages. It leaves room for different techniques, impossible in more rigorous languages. Sometimes, as we will see in the “modules” chapter, it can be used to overcome some of the flaws of the language. After I truly learned and worked with him, I learned to love JavaScript.

Several JavaScript versions have already been released. ECMAScript 3 was the dominant, widespread version during the rise of the language, from about 2000 to 2010. At that time, an ambitious 4th version was being prepared, in which several radical improvements and extensions of the language were planned. However, political reasons made changing the living popular language very difficult, and work on version 4 was discontinued in 2008. The less ambitious 5th version came out in 2009. Now most browsers support the 5th version, which we will use in the book.

JavaScript is not supported only by browsers. Databases like MongoDB and CouchDB use it as a scripting language and query language. There are several platforms for desktops and servers, the most famous of which Node.js, provides a powerful environment for programming outside the browser.

Code, and what to do with it


Code is the text that programs consist of. Most chapters of the book have code. Reading and writing code is an integral part of learning programming. Try not to just run through the eyes of examples - read them carefully and understand. At first it will be slow and incomprehensible, but you will quickly master the skills. The same goes for exercise. Do not imply that you understand them until you write a working option.

I recommend trying your solutions in a real language interpreter in order to immediately receive feedback, and I hope to be tempted to experiment further.

You can install Node.js and run programs with it. You can also do this in the browser console. Chapter 12 will explain how to embed programs in HTML pages. There are also sites likejsbin.com , allowing you to simply run programs in a browser. The book site has a sandbox for the code .

PS: You can support the original author by buying his book on Amazon . Translation author - through the form “Support the author” under the article.

Also popular now: