본문 바로가기
JavaScript

소개 | Eloquent JavaScript 번역

by GangDev 2024. 11. 7.

이 책은 컴퓨터 교육에 관한 책이다.

컴퓨터는 오늘날 드라이버만큼이나 흔하지만, 훨씬 더 복잡하기 때문에 원하는 작업을 수행하도록 만드는 것이 항상 쉬운 것은 아니다.

 

컴퓨터에서 이메일을 표시하거나 계산기처럼 작동하는 등 일반적인 작업이라면 적절한 애플리케이션을 열고 작업을 시작할 수 있다.

하지만 독특하거나 개방적인 작업의 경우 적절한 애플리케이션이 없는 경우가 많다.

 

이때 프로그래밍이 필요할 수 있다.

프로그래밍은 프로그램컴퓨터에게 무엇을 해야 하는지 알려주는 일련의 정확한 명령어을 구성하는 행위다.

컴퓨터는 멍청하고 현학적인 존재이기 때문에 프로그래밍은 근본적으로 지루하고 답답한 작업이다.

 

다행히도 이러한 사실을 극복할 수 있다면, 그리고 멍청한 기계가 처리할 수 있는 용어로 생각하는 엄격함을 즐길 수 있다면 프로그래밍으로 보람을 느낄 수 있다.

프로그래밍을 사용하면 수작업으로는 몇 시간이 걸리는 일을 단 몇 초 만에 할 수 있습니다.

프로그래밍은 컴퓨터 도구가 이전에는 할 수 없었던 일을 할 수 있게 해주는 방법입니다.

게다가 퍼즐을 풀고 추상적인 사고력을 기를 수 있는 훌륭한 게임이기도 합니다.

 

Most programming is done with programming languages.

A programming language is an artificially constructed language used to instruct computers.

It is interesting that the most effective way we’ve found to communicate with a computer borrows so heavily from the way we communicate with each other.

Like human languages, computer languages allow words and phrases to be combined in new ways, making it possible to express ever new concepts.

대부분의 프로그래밍은 프로그래밍 언어로 이루어집니다. 

프로그래밍 언어는 컴퓨터에 명령을 내리는 데 사용되는 인위적으로 구성된 언어입니다. 

우리가 컴퓨터와 소통하는 가장 효과적인 방법이 사람과 사람 사이의 소통 방식에서 많이 차용되었다는 사실은 흥미롭습니다. 인간의 언어와 마찬가지로 컴퓨터 언어도 단어와 구를 새로운 방식으로 결합하여 새로운 개념을 표현할 수 있습니다.

At one point, language-based interfaces, such as the BASIC and DOS prompts of the 1980s and 1990s, were the main method of interacting with computers. For routine computer use, these have largely been replaced with visual interfaces, which are easier to learn but offer less freedom. But if you know where to look, the languages are still there. One of them, JavaScript, is built into every modern web browser—and is thus available on almost every device.

This book will try to make you familiar enough with this language to do useful and amusing things with it.

한때는 1980년대와 1990년대의 BASIC 및 DOS 프롬프트와 같은 언어 기반 인터페이스가 컴퓨터와 상호작용하는 주요 방법이었습니다. 일상적인 컴퓨터 사용의 경우, 이러한 인터페이스는 대부분 시각적 인터페이스로 대체되었는데, 이는 배우기 쉽지만 자유도가 떨어집니다. 하지만 어디를 찾아야 할지 안다면 언어들은 여전히 존재합니다. 그 중 하나인 자바스크립트는 모든 최신 웹 브라우저에 내장되어 있어 거의 모든 기기에서 사용할 수 있습니다. 이 책은 여러분이 이 언어에 익숙해져서 유용하고 재미있는 일을 할 수 있도록 도와줄 것입니다.

On programming

Besides explaining JavaScript, I will introduce the basic principles of programming. Programming, it turns out, is hard. The fundamental rules are simple and clear, but programs built on top of these rules tend to become complex enough to introduce their own rules and complexity. You’re building your own maze, in a way, and you can easily get lost in it.

There will be times when reading this book feels terribly frustrating. If you are new to programming, there will be a lot of new material to digest. Much of this material will then be combined in ways that require you to make additional connections.

자바스크립트에 대한 설명과 함께 프로그래밍의 기본 원리를 소개하겠습니다. 프로그래밍은 어렵습니다. 기본 규칙은 간단하고 명확하지만, 이 규칙을 기반으로 만들어진 프로그램은 자체 규칙과 복잡성을 도입할 만큼 복잡해지는 경향이 있습니다. 어떻게 보면 자신만의 미로를 만드는 것이기 때문에 그 안에서 쉽게 길을 잃을 수 있습니다. 이 책을 읽다 보면 몹시 답답하게 느껴질 때가 있을 것입니다. 프로그래밍을 처음 접하는 분이라면 소화해야 할 새로운 내용이 많을 것입니다. 이 자료의 대부분은 추가 연결이 필요한 방식으로 결합됩니다.

 

It is up to you to make the necessary effort. When you are struggling to follow the book, do not jump to any conclusions about your own capabilities. You are fine—you just need to keep at it. Take a break, reread some material, and make sure you read and understand the example programs and exercises. Learning is hard work, but everything you learn is yours and will make further learning easier.

필요한 노력을 기울이는 것은 여러분의 몫입니다. 책을 따라가는 데 어려움을 겪고 있다면 자신의 능력에 대해 섣불리 결론을 내리지 마세요. 여러분은 괜찮으니 계속 노력하면 됩니다. 잠시 휴식을 취하고 자료를 다시 읽으며 예제 프로그램과 연습 문제를 읽고 이해했는지 확인하세요. 학습은 힘든 일이지만, 배운 모든 것은 여러분의 것이며 앞으로의 학습을 더 쉽게 만들어 줄 것입니다.

When action grows unprofitable, gather information; when information grows unprofitable, sleep.

Ursula K. Le Guin, The Left Hand of Darkness

행동이 이익이 되지 않으면 정보를 수집하고, 정보가 이익이 되지 않으면 잠을 자세요. 어슐러 K. 르 귄, 어둠의 왼손

 

A program is many things. It is a piece of text typed by a programmer, it is the directing force that makes the computer do what it does, it is data in the computer’s memory, and, at the same time, it controls the actions performed on this memory. Analogies that try to compare programs to familiar objects tend to fall short. A superficially fitting one is to compare a program to a machine—lots of separate parts tend to be involved, and to make the whole thing tick, we have to consider the ways in which these parts interconnect and contribute to the operation of the whole.

프로그램은 여러 가지입니다. 프로그래머가 입력한 텍스트 조각이자 컴퓨터가 수행하는 작업을 지시하는 힘이며, 컴퓨터 메모리에 있는 데이터인 동시에 이 메모리에서 수행되는 작업을 제어합니다. 프로그램을 익숙한 사물과 비교하려는 비유는 부족한 경향이 있습니다. 표면적으로 적합한 비유는 프로그램을 기계에 비유하는 것입니다. 프로그램은 많은 개별 부품이 관여하는 경향이 있으며, 전체를 작동시키기 위해서는 이러한 부품이 서로 연결되고 전체 작동에 기여하는 방식을 고려해야 합니다.

 

A computer is a physical machine that acts as a host for these immaterial machines. Computers themselves can do only stupidly straightforward things. The reason they are so useful is that they do these things at an incredibly high speed. A program can ingeniously combine an enormous number of these simple actions to do very complicated things.

컴퓨터는 이러한 비물질적인 기계의 호스트 역할을 하는 물리적 기계입니다. 컴퓨터 자체는 어리석을 정도로 간단한 일만 할 수 있습니다. 컴퓨터가 매우 유용한 이유는 이러한 작업을 엄청나게 빠른 속도로 수행하기 때문입니다. 프로그램은 이러한 간단한 동작을 교묘하게 조합하여 매우 복잡한 작업을 수행할 수 있습니다.

A program is a building of thought. It is costless to build, it is weightless, and it grows easily under our typing hands. But as a program grows, so does its complexity. The skill of programming is the skill of building programs that don’t confuse the programmer. The best programs are those that manage to do something interesting while still being easy to understand.

프로그램은 생각의 건물입니다. 구축하는 데 비용이 들지 않고 무겁지 않으며 타이핑하는 손 아래에서 쉽게 커집니다. 하지만 프로그램이 커지면 복잡성도 커집니다. 프로그래밍의 기술은 프로그래머를 혼란스럽게 하지 않는 프로그램을 구축하는 기술입니다. 가장 좋은 프로그램은 이해하기 쉬우면서도 흥미로운 작업을 수행하는 프로그램입니다.

 

Some programmers believe that this complexity is best managed by using only a small set of well-understood techniques in their programs. They have composed strict rules (“best practices”) prescribing the form programs should have and carefully stay within their safe little zone.

일부 프로그래머는 프로그램에서 잘 이해된 몇 가지 기술만 사용하면 이러한 복잡성을 가장 잘 관리할 수 있다고 생각합니다. 그들은 프로그램이 가져야 할 형식을 규정하는 엄격한 규칙("모범 사례")을 만들어 그 안전한 작은 영역 내에서 신중하게 유지합니다.

This is not only boring—it is ineffective. New problems often require new solutions. The field of programming is young and still developing rapidly, and it is varied enough to have room for wildly different approaches. There are many terrible mistakes to make in program design, and you should go ahead and make them at least once so that you understand them. A sense of what a good program looks like is developed with practice, not learned from a list of rules.

이는 지루할 뿐만 아니라 비효율적입니다. 새로운 문제에는 종종 새로운 해결책이 필요합니다. 프로그래밍 분야는 젊고 여전히 빠르게 발전하고 있으며, 매우 다양한 접근 방식이 존재할 만큼 다양합니다. 프로그램 설계에는 끔찍한 실수들이 많이 있으며, 이를 이해하기 위해 한 번쯤은 실수를 해봐야 합니다. 좋은 프로그램이 어떤 것인지에 대한 감각은 규칙 목록에서 배우는 것이 아니라 연습을 통해 개발됩니다.

Why language matters

In the beginning, at the birth of computing, there were no programming languages. Programs looked something 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 to add the numbers from 1 to 10 together and print the result: 1 + 2 + ... + 10 = 55. It could run on a simple hypothetical machine. To program early computers, it was necessary to set large arrays of switches in the right position or punch holes in strips of cardboard and feed them to the computer. You can imagine how tedious and error prone this procedure was. Even writing simple programs required much cleverness and discipline. Complex ones were nearly inconceivable.

이것은 1에서 10까지의 숫자를 더하고 결과를 인쇄하는 프로그램입니다 : 1 + 2 + ... + 10 = 55. + 10 = 55. 간단한 가상의 컴퓨터에서 실행할 수 있습니다. 초기 컴퓨터를 프로그래밍하려면 큰 스위치 배열을 올바른 위치에 설정하거나 판지 조각에 구멍을 뚫어 컴퓨터에 공급해야했습니다. 이 과정이 얼마나 지루하고 오류가 발생하기 쉬웠는지 상상할 수 있습니다. 간단한 프로그램을 작성하는 데에도 많은 영리함과 규율이 필요했습니다. 복잡한 프로그램은 거의 상상할 수 없었습니다.

Of course, manually entering these arcane patterns of bits (the ones and zeros) did give the programmer a profound sense of being a mighty wizard. And that has to be worth something in terms of job satisfaction.

Each line of the previous program contains a single instruction. It could be written in English like this:

물론 이러한 난해한 비트 패턴(1과 0)을 수동으로 입력하는 것은 프로그래머에게 강력한 마법사가 된 듯한 깊은 느낌을 주었습니다. 그리고 그것은 직업 만족도 측면에서 가치가 있을 것입니다. 이전 프로그램의 각 줄에는 하나의 명령어가 포함되어 있습니다. 영어로 다음과 같이 작성할 수 있습니다:

  1. Store the number 0 in memory location 0.
  2. Store the number 1 in memory location 1.
  3. Store the value of memory location 1 in memory location 2.
  4. Subtract the number 11 from the value in memory location 2.
  5. If the value in memory location 2 is the number 0, continue with instruction 9.
  6. Add the value of memory location 1 to memory location 0.
  7. Add the number 1 to the value of memory location 1.
  8. Continue with instruction 3.
  9. Output the value of memory location 0.

Although that is already more readable than the soup of bits, it is still rather obscure. Using names instead of numbers for the instructions and memory locations helps.

이미 비트 수프보다는 가독성이 높지만 여전히 다소 모호합니다. 명령어와 메모리 위치에 숫자 대신 이름을 사용하면 도움이 됩니다.

  Set “total” to 0.
  Set “count” to 1.
[loop]
  Set “compare” to “count”.
  Subtract 11 from “compare”.
  If “compare” is 0, continue at [end].
  Add “count” to “total”.
  Add 1 to “count”.
  Continue at [loop].
[end]
  Output “total”.

Can you see how the program works at this point? The first two lines give two memory locations their starting values: total will be used to build up the result of the computation, and count will keep track of the number that we are currently looking at. The lines using compare are probably the most confusing ones. The program wants to see whether count is equal to 11 to decide whether it can stop running. Because our hypothetical machine is rather primitive, it can test only whether a number is zero and make a decision based on that. It therefore uses the memory location labeled compare to compute the value of count - 11 and makes a decision based on that value. The next two lines add the value of count to the result and increment count by 1 every time the program decides that count is not 11 yet.

Here is the same program in JavaScript:

이 시점에서 프로그램이 어떻게 작동하는지 알 수 있을까요? 처음 두 줄은 두 개의 메모리 위치에 시작 값을 지정합니다. total은 계산 결과를 쌓는 데 사용되고 count는 현재 보고 있는 숫자를 추적합니다. 비교를 사용하는 줄은 아마도 가장 혼란스러운 줄일 것입니다. 이 프로그램은 실행을 중지할지 여부를 결정하기 위해 count가 11과 같은지 확인하려고 합니다. 이 가상의 기계는 다소 원시적이기 때문에 숫자가 0인지 여부만 테스트하고 이를 기반으로 결정을 내릴 수 있습니다. 따라서 비교라는 레이블이 붙은 메모리 위치를 사용하여 카운트 - 11의 값을 계산하고 이 값에 따라 결정을 내립니다. 다음 두 줄은 카운트 값을 결과에 더하고 프로그램이 카운트가 아직 11이 아니라고 판단할 때마다 카운트를 1씩 증가시킵니다. 다음은 동일한 프로그램을 자바스크립트로 작성한 예시입니다:

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

This version gives us a few more improvements. Most importantly, there is no need to specify the way we want the program to jump back and forth anymore—the while construct takes care of that. It continues executing the block (wrapped in braces) below it as long as the condition it was given holds. That condition is count <= 10, which means “the count is less than or equal to 10”. We no longer have to create a temporary value and compare that to zero, which was just an uninteresting detail. Part of the power of programming languages is that they can take care of uninteresting details for us.

At the end of the program, after the while construct has finished, the console.log operation is used to write out the result.

Finally, here is what the program could look like if we happened to have the convenient operations range and sum available, which respectively create a collection of numbers within a range and compute the sum of a collection of numbers:

이번 버전에서는 몇 가지 개선 사항이 더 추가되었습니다. 가장 중요한 것은 프로그램이 앞뒤로 이동하는 방식을 더 이상 지정할 필요가 없다는 점입니다. 구성이 이를 처리하기 때문입니다. 주어진 조건이 유지되는 한 그 아래에 있는 블록(중괄호로 둘러싸인)을 계속 실행합니다. 이 조건은 카운트 <= 10으로, "카운트가 10보다 작거나 같다"는 뜻입니다. 이제 더 이상 임시 값을 만들어 0과 비교할 필요가 없으므로 흥미롭지 않은 세부 사항일 뿐입니다. 프로그래밍 언어의 힘 중 하나는 흥미롭지 않은 세부 사항을 처리할 수 있다는 점입니다. 프로그램 마지막에 while 구조가 완료된 후 console.log 연산을 사용하여 결과를 기록합니다. 마지막으로, 범위 내의 숫자 집합을 만들고 숫자 집합의 합을 계산하는 편리한 연산 범위와 합을 사용할 수 있다면 프로그램의 모습은 다음과 같습니다:

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

The moral of this story is that the same program can be expressed in both long and short, unreadable and readable ways. The first version of the program was extremely obscure, whereas this last one is almost English: log the sum of the range of numbers from 1 to 10. (We will see in later chapters how to define operations like sum and range.)

A good programming language helps the programmer by allowing them to talk about the actions that the computer has to perform on a higher level. It helps omit details, provides convenient building blocks (such as while and console.log), allows you to define your own building blocks (such as sum and range), and makes those blocks easy to compose.

이 이야기의 교훈은 동일한 프로그램을 길고 짧게, 읽을 수 없는 방식과 읽을 수 있는 방식으로 표현할 수 있다는 것입니다. 프로그램의 첫 번째 버전은 매우 모호했지만, 마지막 버전은 1에서 10까지의 숫자 범위의 합을 기록하는 거의 영어에 가깝습니다. (합과 범위 같은 연산을 정의하는 방법은 다음 장에서 살펴보겠습니다.) 좋은 프로그래밍 언어는 프로그래머가 컴퓨터가 수행해야 하는 작업에 대해 더 높은 수준에서 이야기할 수 있게 함으로써 프로그래머를 도와줍니다. 세부 사항을 생략하고, 편리한 빌딩 블록(예: while 및 console.log)을 제공하며, 자신만의 빌딩 블록(예: 합계 및 범위)을 정의할 수 있고, 이러한 블록을 쉽게 작성할 수 있게 해줍니다.

What is JavaScript?

JavaScript was introduced in 1995 as a way to add programs to web pages in the Netscape Navigator browser. The language has since been adopted by all other major graphical web browsers. It has made modern web applications possible—that is, applications with which you can interact directly without doing a page reload for every action. JavaScript is also used in more traditional websites to provide various forms of interactivity and cleverness.

자바스크립트는 1995년 넷스케이프 네비게이터 브라우저에서 웹 페이지에 프로그램을 추가하기 위한 방법으로 도입되었습니다. 이후 이 언어는 다른 모든 주요 그래픽 웹 브라우저에서 채택되었습니다. 이를 통해 최신 웹 애플리케이션, 즉 모든 작업을 수행할 때마다 페이지를 새로 고치지 않고도 직접 상호 작용할 수 있는 애플리케이션이 가능해졌습니다. 자바스크립트는 보다 전통적인 웹사이트에서도 다양한 형태의 상호 작용과 영리함을 제공하기 위해 사용됩니다.

 

It is important to note that JavaScript has almost nothing to do with the programming language named Java. The similar name was inspired by marketing considerations rather than good judgment. When JavaScript was being introduced, the Java language was being heavily marketed and was gaining popularity. Someone thought it was a good idea to try to ride along on this success. Now we are stuck with the name.

자바스크립트는 자바라는 프로그래밍 언어와는 거의 아무런 관련이 없다는 점을 알아두는 것이 중요합니다. 비슷한 이름은 올바른 판단보다는 마케팅적인 고려에서 비롯된 것입니다. 자바스크립트가 도입될 당시에는 자바 언어가 대대적인 마케팅을 펼치며 인기를 얻고 있었습니다. 누군가는 이러한 성공에 편승하는 것이 좋은 생각이라고 생각했습니다. 이제 우리는 그 이름에 갇혀 있습니다.

 

After its adoption outside of Netscape, a standard document was written to describe the way the JavaScript language should work so that the various pieces of software that claimed to support JavaScript could make sure they actually provided the same language. This is called the ECMAScript standard, after the Ecma International organization that conducted the standardization. In practice, the terms ECMAScript and JavaScript can be used interchangeably—they are two names for the same language.

넷스케이프 외부에서 자바스크립트가 채택된 후, 자바스크립트를 지원한다고 주장하는 다양한 소프트웨어가 실제로 동일한 언어를 제공하는지 확인할 수 있도록 자바스크립트 언어의 작동 방식을 설명하는 표준 문서가 작성되었습니다. 이를 표준화를 수행한 Ecma 국제 단체의 이름을 따서 ECMAScript 표준이라고 부릅니다. 실제로 ECMAScript와 JavaScript라는 용어는 같은 언어에 대한 두 가지 이름으로 혼용하여 사용할 수 있습니다.

 

There are those who will say terrible things about JavaScript. Many of these things are true. When I was required to write something in JavaScript for the first time, I quickly came to despise it. It would accept almost anything I typed but interpret it in a way that was completely different from what I meant. This had a lot to do with the fact that I did not have a clue what I was doing, of course, but there is a real issue here: JavaScript is ridiculously liberal in what it allows. The idea behind this design was that it would make programming in JavaScript easier for beginners. In actuality, it mostly makes finding problems in your programs harder because the system will not point them out to you.

자바스크립트에 대해 끔찍한 말을 하는 사람들이 있습니다. 이 중 많은 부분이 사실입니다. 저도 처음으로 자바스크립트로 무언가를 작성해야 했을 때 자바스크립트를 경멸하게 되었습니다. 제가 입력한 거의 모든 내용을 받아들이지만 제 뜻과는 전혀 다른 방식으로 해석해 주었기 때문입니다. 물론 제가 무엇을 하고 있는지 전혀 몰랐던 것과도 관련이 있지만, 여기에는 진짜 문제가 있습니다: 자바스크립트는 허용하는 것이 엄청나게 자유롭다는 것입니다. 초보자도 쉽게 자바스크립트로 프로그래밍할 수 있도록 하자는 것이 이 디자인의 아이디어였습니다. 실제로는 시스템이 문제를 지적하지 않기 때문에 프로그램에서 문제를 찾는 것이 더 어려워지는 경우가 대부분입니다.

 

This flexibility also has its advantages, though. It leaves room for techniques that are impossible in more rigid languages and makes for a pleasant, informal style of programming. After learning the language properly and working with it for a while, I have come to actually like JavaScript.

하지만 이러한 유연성에는 장점도 있습니다. 더 엄격한 언어에서는 불가능한 기술을 사용할 수 있는 여지를 남겨두고 즐겁고 비공식적인 프로그래밍 스타일을 만들 수 있습니다. 저는 자바스크립트를 제대로 배우고 한동안 자바스크립트로 작업한 후 실제로 자바스크립트를 좋아하게 되었습니다.

 

There have been several versions of JavaScript. ECMAScript version 3 was the widely supported version during JavaScript’s ascent to dominance, roughly between 2000 and 2010. During this time, work was underway on an ambitious version 4, which planned a number of radical improvements and extensions to the language. Changing a living, widely used language in such a radical way turned out to be politically difficult, and work on version 4 was abandoned in 2008. A much less ambitious version 5, which made only some uncontroversial improvements, came out in 2009. In 2015, version 6 came out, a major update that included some of the ideas planned for version 4. Since then we’ve had new, small updates every year.

자바스크립트에는 여러 버전이 있었습니다. 대략 2000년부터 2010년까지 자바스크립트가 대세로 떠오르던 시기에 널리 지원된 버전은 ECMAScript 버전 3이었습니다. 이 기간 동안 언어에 대한 여러 가지 급진적인 개선과 확장을 계획한 야심찬 버전 4에 대한 작업이 진행 중이었습니다. 널리 사용되고 있는 언어를 급진적인 방식으로 변경하는 것은 정치적으로 어려운 일이었고, 버전 4에 대한 작업은 2008년에 중단되었습니다. 2009년에는 논란의 여지가 없는 일부 개선만 이루어진 훨씬 덜 야심찬 버전 5가 나왔습니다. 2015년에는 버전 4에서 계획된 아이디어 중 일부가 포함된 대규모 업데이트인 버전 6이 출시되었습니다. 그 이후로 매년 새로운 소규모 업데이트가 있었습니다.

 

The fact that JavaScript is evolving means that browsers have to constantly keep up. If you’re using an older browser, it may not support every feature. The language designers are careful to not make any changes that could break existing programs, so new browsers can still run old programs. In this book, I’m using the 2024 version of JavaScript.

Web browsers are not the only platforms on which JavaScript is used. Some databases, such as MongoDB and CouchDB, use JavaScript as their scripting and query language. Several platforms for desktop and server programming, most notably the Node.js project (the subject of Chapter 20), provide an environment for programming JavaScript outside of the browser.

자바스크립트가 진화하고 있다는 사실은 브라우저도 이를 지속적으로 따라잡아야 한다는 것을 의미합니다. 구형 브라우저를 사용하는 경우 모든 기능을 지원하지 않을 수 있습니다. 언어 설계자는 기존 프로그램을 손상시킬 수 있는 변경을 하지 않도록 주의하여 새 브라우저에서 이전 프로그램을 계속 실행할 수 있도록 합니다. 이 책에서는 2024 버전의 JavaScript를 사용하고 있습니다. 웹 브라우저만이 자바스크립트가 사용되는 유일한 플랫폼은 아닙니다. MongoDB 및 CouchDB와 같은 일부 데이터베이스는 스크립팅 및 쿼리 언어로 JavaScript를 사용합니다. 데스크톱 및 서버 프로그래밍을 위한 여러 플랫폼, 특히 20장의 주제인 Node.js 프로젝트는 브라우저 외부에서 JavaScript를 프로그래밍할 수 있는 환경을 제공합니다.

 

Code, and what to do with it

Code is the text that makes up programs. Most chapters in this book contain quite a lot of code. I believe reading code and writing code are indispensable parts of learning to program. Try to not just glance over the examples—read them attentively and understand them. This may be slow and confusing at first, but I promise that you’ll quickly get the hang of it. The same goes for the exercises. Don’t assume you understand them until you’ve actually written a working solution.

I recommend you try your solutions to exercises in an actual JavaScript interpreter. That way, you’ll get immediate feedback on whether what you are doing is working, and, I hope, you’ll be tempted to experiment and go beyond the exercises.

코드는 프로그램을 구성하는 텍스트입니다. 이 책의 대부분의 장에는 꽤 많은 코드가 포함되어 있습니다. 코드를 읽고 코드를 작성하는 것은 프로그래밍을 배우는 데 없어서는 안 될 부분이라고 생각합니다. 예제를 훑어보는 데 그치지 말고 주의 깊게 읽고 이해하려고 노력하세요. 처음에는 느리고 혼란스러울 수 있지만 금방 익숙해질 수 있을 것입니다. 연습 문제도 마찬가지입니다. 실제로 작동하는 솔루션을 작성하기 전까지는 이해했다고 가정하지 마세요. 실제 자바스크립트 인터프리터에서 연습 문제에 대한 솔루션을 작성해 보시기 바랍니다. 이렇게 하면 자신이 하고 있는 일이 제대로 작동하는지 즉각적인 피드백을 받을 수 있으며, 연습 문제를 넘어서는 실험을 해보고 싶은 유혹을 느낄 수 있을 것입니다.

 

When reading this book in your browser, you can edit (and run) all example programs by clicking them.

Running the programs defined in this book outside of the book’s website requires some care. Many examples stand on their own and should work in any JavaScript environment. But code in later chapters is often written for a specific environment (the browser or Node.js) and can run only there. In addition, many chapters define bigger programs, and the pieces of code that appear in them depend on each other or on external files. The sandbox on the website provides links to ZIP files containing all the scripts and data files necessary to run the code for a given chapter.

브라우저에서 이 책을 읽을 때 모든 예제 프로그램을 클릭하여 편집(및 실행)할 수 있습니다. 이 책에 정의된 프로그램을 이 책의 웹 사이트 외부에서 실행하려면 약간의 주의가 필요합니다. 많은 예제는 독립적으로 존재하며 어떤 자바스크립트 환경에서도 작동해야 합니다. 그러나 이후 장의 코드는 특정 환경(브라우저 또는 Node.js)을 위해 작성된 경우가 많으며 해당 환경에서만 실행할 수 있습니다. 또한 많은 장에서 더 큰 프로그램을 정의하며, 그 안에 나타나는 코드 조각은 서로 또는 외부 파일에 의존합니다. 웹사이트의 샌드박스는 해당 챕터의 코드를 실행하는 데 필요한 모든 스크립트와 데이터 파일이 포함된 ZIP 파일 링크를 제공합니다.

 

Overview of this book

This book contains roughly three parts. The first 12 chapters discuss the JavaScript language. The next seven chapters are about web browsers and the way JavaScript is used to program them. Finally, two chapters are devoted to Node.js, another environment to program JavaScript in. There are five project chapters in the book that describe larger example programs to give you a taste of actual programming.

이 책은 크게 세 부분으로 구성되어 있습니다. 처음 12장에서는 JavaScript 언어에 대해 설명합니다. 다음 7장은 웹 브라우저와 웹 브라우저를 프로그래밍하는 데 JavaScript를 사용하는 방식에 대해 설명합니다. 마지막으로 두 장은 JavaScript를 프로그래밍할 수 있는 또 다른 환경인 Node.js에 대해 다룹니다. 이 책에는 실제 프로그래밍을 맛볼 수 있는 대규모 예제 프로그램을 설명하는 5개의 프로젝트 챕터가 있습니다.

 

The language part of the book starts with four chapters that introduce the basic structure of the JavaScript language. They discuss control structures (such as the while word you saw in this introduction), functions (writing your own building blocks), and data structures. After these, you will be able to write basic programs. Next, Chapters 5 and 6 introduce techniques to use functions and objects to write more abstract code and keep complexity under control.

After a first project chapter that builds a crude delivery robot, the language part of the book continues with chapters on error handling and bug fixing, regular expressions (an important tool for working with text), modularity (another defense against complexity), and asynchronous programming (dealing with events that take time). The second project chapter, where we implement a programming language, concludes the first part of the book.

The second part of the book, Chapters 13 to 19, describes the tools that browser JavaScript has access to. You’ll learn to display things on the screen (Chapters 14 and 17), respond to user input (Chapter 15), and communicate over the network (Chapter 18). There are again two project chapters in this part: building a platform game and a pixel paint program.

Chapter 20 describes Node.js, and Chapter 21 builds a small website using that tool.

이 책의 언어 부분은 자바스크립트 언어의 기본 구조를 소개하는 네 개의 장으로 시작합니다. 이 장에서는 제어 구조(예: 이 소개에서 살펴본 동안 단어), 함수(자신만의 빌딩 블록 작성), 데이터 구조에 대해 설명합니다. 이를 통해 기본적인 프로그램을 작성할 수 있습니다. 다음으로 5장과 6장에서는 함수와 객체를 사용해 보다 추상적인 코드를 작성하고 복잡성을 제어하는 기술을 소개합니다. 조잡한 배달 로봇을 만드는 첫 번째 프로젝트 장 이후에는 오류 처리와 버그 수정, 정규식(텍스트 작업에 중요한 도구), 모듈성(복잡성에 대한 또 다른 방어 수단), 비동기 프로그래밍(시간이 걸리는 이벤트 처리)에 관한 장으로 언어 부분이 이어집니다. 프로그래밍 언어를 구현하는 두 번째 프로젝트 장에서는 이 책의 첫 번째 부분을 마무리합니다. 책의 두 번째 부분인 13장부터 19장까지는 브라우저 자바스크립트에서 액세스할 수 있는 도구에 대해 설명합니다. 화면에 사물을 표시하고(14장과 17장), 사용자 입력에 응답하고(15장), 네트워크를 통해 통신하는 방법(18장)을 배우게 됩니다. 이 파트에는 다시 플랫폼 게임과 픽셀 페인트 프로그램 구축이라는 두 개의 프로젝트 챕터가 있습니다. 20장에서는 Node.js에 대해 설명하고, 21장에서는 해당 도구를 사용해 작은 웹사이트를 구축합니다.

 

Typographic conventions

In this book, text written in a monospaced font will represent elements of programs. Sometimes these are self-sufficient fragments, and sometimes they just refer to part of a nearby program. Programs (of which you have already seen a few) are written as follows:

이 책에서 단칸 글꼴로 작성된 텍스트는 프로그램의 요소를 나타냅니다. 때로는 자급자족할 수 있는 단편이거나 주변 프로그램의 일부를 참조하는 경우도 있습니다. 프로그램(이미 몇 가지를 보셨을 겁니다)은 다음과 같이 작성됩니다:

function factorial(n) {
  if (n == 0) {
    return 1;
  } else {
    return factorial(n - 1) * n;
  }
}

Sometimes, to show the output that a program produces, the expected output is written after it, with two slashes and an arrow in front.

프로그램이 생성하는 출력을 보여주기 위해 예상 출력을 그 뒤에 슬래시 두 개와 화살표를 앞에 붙여 표시하는 경우가 있습니다.

console.log(factorial(8));
// → 40320

Good luck!