--- title: Повторне введення в JavaScript (JS-підручник) slug: Web/JavaScript/A_re-introduction_to_JavaScript translation_of: Web/JavaScript/A_re-introduction_to_JavaScript ---
{{jsSidebar}}

Вступ

Чому повторне введення? Тому що {{Glossary ("JavaScript")}} відомий тим, що він є найпопулярнішою у світі мовою програмування. Його часто висміюють як іграшку, але під його шаром оманливої простоти чекають потужні мовні особливості. JavaScript зараз використовується неймовірним числом популярних додатків, які показують, що більш глибоке знання цієї технології є важливим вмінням для будь-якого веб-розробника або розробника мобільних пристроїв.

Варто почати з огляду історії мови. JavaScript був створений у 1995 році Бренданом Айком, коли він був інженером у Netscape. JavaScript був вперше випущений з Netscape 2 на початку 1996 року. Спочатку він мав назву LiveScript, але він був перейменований у злополучному маркетинговому рішенні, яке спробувало скористатися популярністю Java-мови Sun Microsystem - незважаючи на те, що вони мають мало спільного. З тих пір це стало джерелом плутанини.

Трохи пізніше Microsoft випустила дуже схожу та практично сумісну мову JScript який йшов разом з Internet Explorer 3. Через пару місяців Netscape відправила мову JavaScript до Ecma International, Європейську організацію, яка займається стандартами, яка випустила першу версію стандарту {{Glossary("ECMAScript")}} в 1997 року. Стандарт отримав значуще оновлення в  ECMAScript edition 3 в 1999 році, і залишається найстабільнішим до сьогоднішнього дня. Четверта версія була відхилена, через проблеми з ускладненням в мові. Більшість речей з четвертого видання послужили основою для стандарту ECMAScript edition 5, оприлюднений в грудні  2009 року, і для 6-го основного видання стандарту, оприлюдненого в червні  2015 року.

На замітку:  На далі по тексту ми будемо називати мову ECMAScript як "JavaScript".

На відміну від більшості мов програмування, JavaScript не наслідує концепцію введення(input) та виведенн(output). Він спроектований таким чином, щоб запускатися як мова сценаріїв, вбудованих в середовище виконання. Найпопулярніше середовище виконання це браузер, однак інтепретатори JavaScript присутні також в Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo's Widget engine, і навіть в серверному середовищі наприклад Node.js.

Загальний огляд

JavaScript це мультіпарадігматична, динамічна мова з типами та операторами, стандартними вбудованими об'єктами  та методами. ЇЇ синтаксис базован на мовах Java та C - взагалі, більша частина структури цих мов закладена в JavaScript. JavaScript підтримує об'єктно-орієнтований підхід  через прототипи об'єктів, замість класів (дивись більше про  успадкування через прототипи та ES2015 {{jsxref("Classes")}}). JavaScript також підтримує функціональне програмування — тому що  функції це  об'єкти, їх можна тримати в змінних та передавати як будь-які інші об'єкти.

Давайте почнемо огляд з блоків будови будь-якої мови: з типів. програми JavaScript керують значеннями-даними та ці значення належать до якогось типу. JavaScript має наступні типи данних:

... О, ще й  {{jsxref("undefined")}} та {{jsxref("null")}}, які є ... досить відокремленими типами. Та {{jsxref("Array")}}, який є спеціальним видом об'єкту. Також {{jsxref("Date")}} та{{jsxref("RegExp")}}, які є вбудованними видами об'єктів. Та, якщо бути технічно акуратними, функція це всього-навсього спеціальний тип об'єкту. Тож діаграмма типів має виглядати наступним чином:

Також є вбудований {{jsxref("Error")}} тип. На першій діаграммі усе видається простішим, та далі ми обговоримо усі типи, що були описані.

Числа (Numbers)

Numbers в JavaScript є "значення подвійної точністі 64-бітового формату IEEE 754", згідно специфікаціїї. Це має деякі цікаві наслідки. В JavaScript немає цілих чисел (integer), тож вам треба бути уважнішими з аріфметикою в порівнянні з математикою мов C або Java. Таким чином, ціле число насправді є неявним плаваючим.

Також, обережніше з такими випадками:

0.1 + 0.2 == 0.30000000000000004;

На практиці, цілі (integer) значення представляються як 32-бітні цілі, та деякі реалізації навіть зберігають їх таким чином до тих пір, поки не буде потреби виконати інструкцію, дійсну для числа (Number), але не для 32-бітного цілого числа. Це може бути важливо для побітових (bit-wise) операцій.

Підтримуються стандартні арифметичні оператори (arithmetic operators), включаючи додавання, віднімання, модуль (або залишок) тощо. Існує також вбудований об'єкт, про який ми не згадували раніше, так званий {{jsxref ("Math")}}, який забезпечує розширені математичні функції та константи:

Math.sin(3.5);
var circumference = 2 * Math.PI * r;

Ви можете конвертувати рядки (string) в цілі числа (integer) за допомогою вбудованої {{jsxref("Global_Objects/parseInt", "parseInt()")}} функції. Вона приймає опційним другим аргументом основу системи числення (яку бажано передавати завжди):

parseInt('123', 10); // 123
parseInt('010', 10); // 10

У браузерах попередніх версій рядки, що починаються з "0", розглядаються, як числа з основою 8 (radix 8), але це вже не є стандартом з 2013 року.  Вас може здивувати результат наступних дій в старших браузерах:

parseInt('010');  //  8
parseInt('0x10'); // 16

В цьому зразку коду ми бачимо  {{jsxref("Global_Objects/parseInt", "parseInt()")}} функції приймають перший string як число в вісімковій системі (octal) через передуючий "0", да другий string приймається як число в шістнадцятковій системі (hexadecimal) через передуючий  "0x". Шістнадцяткова нотація все ще оброблюється в нових браузерахю Тількі вісімкову було прибрано з мови.

Якщо бажаєте конвертувати бінарне число в звичайне ціле (integer), просто зміність базу (base):

parseInt('11', 2); // 3

Таким же чином, ви можете конвертувати числа із плаваючою комою, використавши вбудовані функції {{jsxref("Global_Objects/parseFloat", "parseFloat()")}}. На відміну від своїх двоюрідних сестер {{jsxref("Global_Objects/parseInt", "parseInt()")}} , parseFloat() завжди використовує десятичну базу.

Ви також можете використовувати унарний операнд + для конвертації в числа (numbers):

+ '42';   // 42
+ '010';  // 10
+ '0x10'; // 16

Спеціальне значення, що називається {{jsxref("NaN")}} (скорочення від  "Not a Number" - не число) повертається якщо строка є не-числом (non-numeric):

parseInt('hello', 10); // NaN

NaN токсичний! Якщо ви зробите його вхідними даними для будь-якої математичної операції - результатом буде також NaN:

NaN + 5; // NaN

Вы можете тестувати NaN, використовуючи вбудовану функцію  {{jsxref("Global_Objects/isNaN", "isNaN()")}}:

isNaN(NaN); // true

JavaScript також має спеціальні значення {{jsxref("Infinity")}} та -Infinity:

 1 / 0; //  Infinity
-1 / 0; // -Infinity

Ви можете тестувати Infinity, -Infinity таNaN значення, використвовуючи вбудовані вбудовані функції {{jsxref("Global_Objects/isFinite", "isFinite()")}}:

isFinite(1 / 0); // false
isFinite(-Infinity); // false
isFinite(NaN); // false
{{jsxref("Global_Objects/parseInt", "parseInt()")}} та {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} функції розкладають string допоки не зустрінуть символ, що не є валідним для заданого числового формату, потім повертає число, що було розгорнуто із string до цієї точки. Однак оператор "+" конвертує string до NaN якщо було виявлене некоректне значення. Просто спробуйте зробити парсінг для "10.2abc" кожним з методів у консолі та ви зрозумієте різницю краще.

Строки (Strings)

Строки в JavaScript є послідовністю знаків - Unicode characters. Це радісна новина для усіх, хто мав справи з інтернаціоналізацією ( internationalization). Якщо бути точнішими, це послідовність одиниць кодування UTF-16; кожна така одиниця представлена 16-бітовим числом. Кожний  Unicode знак представлен однією чи двома одиницями коду.

Якщо бажаєте представити строку із одного символа-знака, ви просто використовуєте строку, що складається з одного символа.

Що дізнатись довжину строки (в одиницях коду), зверніться до його  length властивості:

'hello'.length; // 5

Ось наша перша зустріч з об'єктами JavaScript! Ви помітили, що ви можете використовувати строку як {{jsxref("Object", "objects", "", 1)}} також? У строк є {{jsxref("String", "methods", "#Methods", 1)}} які дозволяють Вам керувати строками та мати доступ до інформації про строку:

'hello'.charAt(0); // "h"
'hello, world'.replace('hello', 'goodbye'); // "goodbye, world"
'hello'.toUpperCase(); // "HELLO"

Інші типи

JavaScript розрізняє {{jsxref("null")}}, якие є значенням, що показує свідому відсутність значення (та доступне лише через ключеве слово null), та {{jsxref("undefined")}}, яке є значенням типу undefined та вказує на неініціалізоване значення, яке ще не отримало присвоєння значення. Ми поговоримо про змінні пізніше, а зараз зазначимо, що в JavaScript можлива об'ява змінної без присвоєння значення. Якщо ви зробите це, тип змінної буде undefined. Взагалі, undefined  це константа.

В JavaScript є булевий тип, з можливими значеннями true та false (обидва є ключовими словами) Будь-яке значення може бути перетворено в булевий тип, згідно наступних правил:

  1. false, 0, пуста строка (""), NaN, null, таundefined стають false.
  2. все інше - true.

Ви можете зробити цю конвертацію безпосередньо за допомогою Boolean() функції:

Boolean('');  // false
Boolean(234); // true

Однак, це майже не використовується, тому що JavaScript буде мовчки виконувати це перетворення коли очікується булеве значення, як в if твердженні (дивися нижче). Тому ми інколи говоримо просто "вірне значення" та "хибне значення", маючи на увазі значення, що стає true та false відповідно, при перетворенні на булеве. Як альтернативу, такі значення можна назвати відповідно "правдоподібними" та "хибними".

Підтримуються такі булеві операції як && (логічний ТА), || (логічній АБО), та! (логічний НІ); дивися про це нижче.

Змінні

Нові змінні в JavaScript оголошуються за допомогою одного з трьох ключових слів: letconst, або var

let дозволяє оголосити змінну рівня блоку. Оголошена таким чином змінна доступна на рівні функціонального блоку, до якого вона входить

let a;
let name = 'Simon';

Наступний приклад демонструє область осяжності (scope) змінної, що оголошена за допомогою let:

// myLetVariable is *not* visible out here

for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) {
  // myLetVariable is only visible in here
}

// myLetVariable is *not* visible out here

const дозволяє оголосити змінні, чиї значення не збираються бути змінені. Такі змінні доступні з функційного блоку, де були оголошені.

const Pi = 3.14; // змінна Pi встановлена
Pi = 1; // викине помилку (error), тому що ви не можете змінювати постійні змінні (сonstant variable).


var є самим загальним ключовим словом оголошень змінних. Він не має обмежень, що мають попередні два ключових слова. Це тому що це був єдиний спосіб оголошувати змінні в JavaScript. Змінна, що оголошена за допомогою var доступна із функційного блоку, де була оголошена.

var a;
var name = 'Simon';

Наступний приклад демонструє область осяжності (scope) змінної, що оголошена за допомогою var:

// myVarVariable *є* видимою звідси

for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) {
  // myVarVariable є видимою для усієї функції
}

// myVarVariable *є* видимою звідси

Якщо ви оголосити змінну без присвоєння їй значення, її тип буде undefined.

Важлива різниця між JavaScript та іншими мовами, такими як Java це те, що в JavaScript, блоки не мають області осяжності (scope); тільки функції мають область осяжності. Тому, якщо змінна визначена у складі виразу за допомогою var  (наприклад, всередені структури контроля if), вона буде видимою для зовнішньої функції. Однак, починаючи з ECMAScript 2015, let таconst оголошення дозволяють створювати блочно-обмежені змінні.

Оператори

Числові оператори JavaScript це +, -, *, / та% що є оператором решти (що не слід плутати з модулем числа (modulo).) Значення присвоюються за допомогою =, та є також вирази компоновочного присвоєння такі як  += and -=. Це розширення виразу x = x operator y.

x += 5;
x = x + 5;

Ви можете використовувати  ++ and -- щоб збільшувати та зменьшувати відповідно. Вони можуть бути як в префіксному так і в  постфіксному положенні відносно значень.

+ оператор також робить складання строк:

'hello' + ' world'; // "hello world"

Якщо ви додаєте строку до числа (або інше значення) усе конвертуюеться насамперед в строку. Це може Вас здивувати:

'3' + 4 + 5;  // "345"
 3 + 4 + '5'; // "75"

Додавання пустої строки до якогось значення є зручним шляхом конвертування цього значення у строку.

Порівняння в JavaScript робляться за допомогою <, >, <= and >=. Це працює як для строк, так і для чисел. Рівність менш прямолінійна. Оператор подвійне-рівно (double-equals) призводить до примусової конвертації (coercion), якщо значення порівняння різних типів, інколи - з дивним результатом:

123 == '123'; // true
1 == true; // true

Щоб запобігти коерції, використовуйте потрійне-рівне:

123 === '123'; // false
1 === true;    // false

Є також оператори != та!==.

JavaScript також має  побітові операції. Якщо хочете їх використовувати - вони до Ваших послуг.

Control structures

JavaScript має схожий набір структур контроля з іншими мовами сімейства C. Ствердження умов підтримуються за допомогою if та else; Можете організовувати їх у ланцюги за бажанням:

var name = 'kittens';
if (name == 'puppies') {
  name += ' woof';
} else if (name == 'kittens') {
  name += ' meow';
} else {
  name += '!';
}
name == 'kittens meow';

JavaScript має while цикли та do-while цикли. Перший добре підходить для загального цикла; другий для циклів, де Ви бажаєте бути впевненими що тіло циклу буде виконано хоча б раз:

while (true) {
  // an infinite loop!
}

var input;
do {
  input = get_input();
} while (inputIsNotValid(input));

 for цикл в JavaScript це теж саме, що і в С та Java мовах: це дозволяє впровадити усю інформацію про цикл в єдиній лінії коду.

for (var i = 0; i < 5; i++) {
  // Буде виконано 5 разів
}

JavaScript також має два інших відомих варіанта циклу: for...of

for (let value of array) {
  // робиться щось з value
}

та for...in:

for (let property in object) {
  // робиться щось з property object
}

Оператори && та || використовують логіку скороченого обчислення  , це означає що чи буде обчислюватись другий операнд залежить від результату обчислення першого операнда. Дуже зручно перевіряти об'єкти на належність до null перед доступом до його атрибутів:

var name = o && o.getName();

Або для кешування значень (коли хибні значення є недійсними):

var name = cachedName || (cachedName = getName());

JavaScript має тернарний оператор для виразів умов:

var allowed = (age > 18) ? 'yes' : 'no';

Твердження switch може бути використано для багатогілкових умов на основі чисели чи строк:

switch (action) {
  case 'draw':
    drawIt();
    break;
  case 'eat':
    eatIt();
    break;
  default:
    doNothing();
}

Якщо не додати break твердження, виконання "провалиться" на наступний рівень. Це досить рідко може бути тим, чого ви хотіли — насправді варто конкретно позначити навмисний "прорив" коментарем, якщо ви дійсно мали на увазі це для сприяння налагодженню (debugging):

switch (a) {
  case 1: // провал нижче
  case 2:
    eatIt();
    break;
  default:
    doNothing();
}

Завершення за допомогою default за бажанням. Ви можете мати вирази в обидвах частинах switch та cases якщо бажаєте; порівняння буде робитися за допомогою оператора ===:

switch (1 + 3) {
  case 2 + 2:
    yay();
    break;
  default:
    neverhappens();
}

Об'єкти

JavaScript об'єкти можна уявляти як прості колекції пар ім'я-значення (name-value pairs). Таким чином, вони схожі на:

Те, що ця структура даних настільки широко використовується, є свідченням її універсальності . Через те, що усе (основні типи даних) в JavaScript це об'єкт, будь-яка програма JavaScript, природно, передбачає велику кількість пошукових запитів хеш-таблиць. Як добре, що запити такі швидкі!

 частина "ім'я" це строка JavaScript, а "значення" може бути будь яким з типів  JavaScript — включно об'єктами. Це дозволяє Вам будувати структури даних необмеженої складності.

Є два основних способи створити пустий об'єкт:

var obj = new Object();

Та:

var obj = {};

Це семантично одинаково; другий спосіб називається синтаксис буквального об'єкта (object literal syntax), та є більш зручним. Цей синтаксис також базовий для формату JSON та повинен бути бажаним завжди.

Синтаксис буквального об'єкту може бути використаний щоб ініціалізувати об'єкт у всій повноті:

var obj = {
  name: 'Carrot',
  'for': 'Max',
  details: {
    color: 'orange',
    size: 12
  }
}

Доступ до атрибутів може бути у вигляді ланцюга:

obj.details.color; // orange
obj['details']['size']; // 12

Наступний приклад створює об'єкт-прототип, Person та екземпляр цього прототипу, You.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

// Define an object
var You = new Person('You', 24);
// We are creating a new person named "You"
// (that was the first parameter, and the age..)

Після створення, до властивостей об'єкта можна отримати доступ одним із двох способів:

obj.name = 'Simon';
var name = obj.name;

та...

obj['name'] = 'Simon';
var name = obj['name'];

Вони також семантично рівнозначні. Другий метод має перевагу в тому, що ім'я властивості надається у вигляді рядка, а значить, його можна обчислити під час виконання. Однак використання цього методу запобігає застосуванню деяких оптимізацій двигуна JavaScript та мініфікаторів. Він також може бути використаний для встановлення та отримання властивостей із іменами, зарезервованими словами:

obj.for = 'Simon'; // Syntax error, тому що 'for' зарезервоване слово
obj['for'] = 'Simon'; // спрацьовує добре

Починаючи з ECMAScript 5, зарезервовані слова можна використовувати  як імена властивостей об'єкта "в буфі". Це означає, що при визначенні об’єктних літералів їх не потрібно "вбирати" в лапки. Див. Специфікацію ES5.

Детальніше про об'єкти та прототипи див. : Object.prototype. Пояснення прототипів  об’єктів та ланцюгів прототипів об'єктів див .: Inheritance and the prototype chain.

Масиви

Arrays in JavaScript are actually a special type of object. They work very much like regular objects (numerical properties can naturally be accessed only using [] syntax) but they have one magic property called 'length'. This is always one more than the highest index in the array.

One way of creating arrays is as follows:

var a = new Array();
a[0] = 'dog';
a[1] = 'cat';
a[2] = 'hen';
a.length; // 3

A more convenient notation is to use an array literal:

var a = ['dog', 'cat', 'hen'];
a.length; // 3

Note that array.length isn't necessarily the number of items in the array. Consider the following:

var a = ['dog', 'cat', 'hen'];
a[100] = 'fox';
a.length; // 101

Remember — the length of the array is one more than the highest index.

If you query a non-existent array index, you'll get a value of undefined returned:

typeof a[90]; // undefined

If you take the above into account, you can iterate over an array using the following:

for (var i = 0; i < a.length; i++) {
  // Do something with a[i]
}

You can iterate over an array using a for...in loop. Note that if someone added new properties to Array.prototype, they will also be iterated over by this loop.  Therefore this method is "not" recommended.

Another way of iterating over an array that was added with ECMAScript 5 is forEach():

['dog', 'cat', 'hen'].forEach(function(currentValue, index, array) {
  // Do something with currentValue or array[index]
});

If you want to append an item to an array simply do it like this:

a.push(item);

Arrays come with a number of methods. See also the full documentation for array methods.

Method name Description
a.toString() Returns a string with the toString() of each element separated by commas.
a.toLocaleString() Returns a string with the toLocaleString() of each element separated by commas.
a.concat(item1[, item2[, ...[, itemN]]]) Returns a new array with the items added on to it.
a.join(sep) Converts the array to a string — with values delimited by the sep param
a.pop() Removes and returns the last item.
a.push(item1, ..., itemN) Adds one or more items to the end.
a.reverse() Reverses the array.
a.shift() Removes and returns the first item.
a.slice(start[, end]) Returns a sub-array.
a.sort([cmpfn]) Takes an optional comparison function.
a.splice(start, delcount[, item1[, ...[, itemN]]]) Lets you modify an array by deleting a section and replacing it with more items.
a.unshift(item1[, item2[, ...[, itemN]]]) Prepends items to the start of the array.

Функції

Along with objects, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:

function add(x, y) {
  var total = x + y;
  return total;
}

This demonstrates a basic function. A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like, and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined.

The named parameters turn out to be more like guidelines than anything else. You can call a function without passing the parameters it expects, in which case they will be set to undefined.

add(); // NaN
// You can't perform addition on undefined

You can also pass in more arguments than the function is expecting:

add(2, 3, 4); // 5
// added the first two; 4 was ignored

That may seem a little silly, but functions have access to an additional variable inside their body called arguments, which is an array-like object holding all of the values passed to the function. Let's re-write the add function to take as many values as we want:

function add() {
  var sum = 0;
  for (var i = 0, j = arguments.length; i < j; i++) {
    sum += arguments[i];
  }
  return sum;
}

add(2, 3, 4, 5); // 14

That's really not any more useful than writing 2 + 3 + 4 + 5 though. Let's create an averaging function:

function avg() {
  var sum = 0;
  for (var i = 0, j = arguments.length; i < j; i++) {
    sum += arguments[i];
  }
  return sum / arguments.length;
}

avg(2, 3, 4, 5); // 3.5
This is pretty useful, but it does seem a little verbose. To diminish this code a bit more we can look at substituting the use of the arguments array through Spread syntax. In this way we can pass in any number of arguments into the function while keeping our code minimal. The spread operator is used in function declarations with the format: ...[variable]  and it will include within that variable the entire list of uncaptured arguments that the function was called with.  We will also replace the for loop with a for...of loop to return the values within our variable.
function avg(...args) {
  var sum = 0;
  for (let value of args) {
    sum += value;
  }
  return sum / args.length;
}

avg(2, 3, 4, 5); // 3.5
In the above code the variable args holds all the values that were passed into the function. 

It is important to note that wherever the spread operator is placed in a function declaration it will store all arguments after its declaration, but not before.
a.e. function avg(firstValue, ...args) will store the first value passed into the function in the firstValue variable and the remaining arguments in args
Another useful function but it does lead us to a new problem. The avg() function takes a comma separated list of arguments — but what if you want to find the average of an array? You could just rewrite the function as follows:
function avgArray(arr) {
  var sum = 0;
  for (var i = 0, j = arr.length; i < j; i++) {
    sum += arr[i];
  }
  return sum / arr.length;
}

avgArray([2, 3, 4, 5]); // 3.5

But it would be nice to be able to reuse the function that we've already created. Luckily, JavaScript lets you call a function and call it with an arbitrary array of arguments, using the {{jsxref("Function.apply", "apply()")}} method of any function object.

avg.apply(null, [2, 3, 4, 5]); // 3.5

The second argument to apply() is the array to use as arguments; the first will be discussed later on. This emphasizes the fact that functions are objects too.

JavaScript lets you create anonymous functions.

var avg = function() {
  var sum = 0;
  for (var i = 0, j = arguments.length; i < j; i++) {
    sum += arguments[i];
  }
  return sum / arguments.length;
};

This is semantically equivalent to the function avg() form. It's extremely powerful, as it lets you put a full function definition anywhere that you would normally put an expression. This enables all sorts of clever tricks. Here's a way of "hiding" some local variables — like block scope in C:

var a = 1;
var b = 2;

(function() {
  var b = 3;
  a += b;
})();

a; // 4
b; // 2

JavaScript allows you to call functions recursively. This is particularly useful for dealing with tree structures, such as those found in the browser DOM.

function countChars(elm) {
  if (elm.nodeType == 3) { // TEXT_NODE
    return elm.nodeValue.length;
  }
  var count = 0;
  for (var i = 0, child; child = elm.childNodes[i]; i++) {
    count += countChars(child);
  }
  return count;
}

This highlights a potential problem with anonymous functions: how do you call them recursively if they don't have a name? JavaScript lets you name function expressions for this. You can use named IIFEs (Immediately Invoked Function Expressions) as shown below:

var charsInBody = (function counter(elm) {
  if (elm.nodeType == 3) { // TEXT_NODE
    return elm.nodeValue.length;
  }
  var count = 0;
  for (var i = 0, child; child = elm.childNodes[i]; i++) {
    count += counter(child);
  }
  return count;
})(document.body);

The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging.

Note that JavaScript functions are themselves objects — like everything else in JavaScript — and you can add or change properties on them just like we've seen earlier in the Objects section.

Custom objects

For a more detailed discussion of object-oriented programming in JavaScript, see Introduction to Object Oriented JavaScript.

In classic Object Oriented Programming, objects are collections of data and methods that operate on that data. JavaScript is a prototype-based language that contains no class statement, as you'd find in C++ or Java (this is sometimes confusing for programmers accustomed to languages with a class statement.) Instead, JavaScript uses functions as classes. Let's consider a person object with first and last name fields. There are two ways in which the name might be displayed: as "first last" or as "last, first". Using the functions and objects that we've discussed previously, we could display the data like this:

function makePerson(first, last) {
  return {
    first: first,
    last: last
  };
}
function personFullName(person) {
  return person.first + ' ' + person.last;
}
function personFullNameReversed(person) {
  return person.last + ', ' + person.first;
}

s = makePerson('Simon', 'Willison');
personFullName(s); // "Simon Willison"
personFullNameReversed(s); // "Willison, Simon"

This works, but it's pretty ugly. You end up with dozens of functions in your global namespace. What we really need is a way to attach a function to an object. Since functions are objects, this is easy:

function makePerson(first, last) {
  return {
    first: first,
    last: last,
    fullName: function() {
      return this.first + ' ' + this.last;
    },
    fullNameReversed: function() {
      return this.last + ', ' + this.first;
    }
  };
}

s = makePerson('Simon', 'Willison');
s.fullName(); // "Simon Willison"
s.fullNameReversed(); // "Willison, Simon"

There's something here we haven't seen before: the this keyword. Used inside a function, this refers to the current object. What that actually means is specified by the way in which you called that function. If you called it using dot notation or bracket notation on an object, that object becomes this. If dot notation wasn't used for the call, this refers to the global object.

Note that this is a frequent cause of mistakes. For example:

s = makePerson('Simon', 'Willison');
var fullName = s.fullName;
fullName(); // undefined undefined

When we call fullName() alone, without using s.fullName(), this is bound to the global object. Since there are no global variables called first or last we get undefined for each one.

We can take advantage of the this keyword to improve our makePerson function:

function Person(first, last) {
  this.first = first;
  this.last = last;
  this.fullName = function() {
    return this.first + ' ' + this.last;
  };
  this.fullNameReversed = function() {
    return this.last + ', ' + this.first;
  };
}
var s = new Person('Simon', 'Willison');

We have introduced another keyword: new. new is strongly related to this. It creates a brand new empty object, and then calls the function specified, with this set to that new object. Notice though that the function specified with this does not return a value but merely modifies the this object. It's new that returns the this object to the calling site. Functions that are designed to be called by new are called constructor functions. Common practice is to capitalize these functions as a reminder to call them with new.

The improved function still has the same pitfall with calling fullName() alone.

Our person objects are getting better, but there are still some ugly edges to them. Every time we create a person object we are creating two brand new function objects within it — wouldn't it be better if this code was shared?

function personFullName() {
  return this.first + ' ' + this.last;
}
function personFullNameReversed() {
  return this.last + ', ' + this.first;
}
function Person(first, last) {
  this.first = first;
  this.last = last;
  this.fullName = personFullName;
  this.fullNameReversed = personFullNameReversed;
}

That's better: we are creating the method functions only once, and assigning references to them inside the constructor. Can we do any better than that? The answer is yes:

function Person(first, last) {
  this.first = first;
  this.last = last;
}
Person.prototype.fullName = function() {
  return this.first + ' ' + this.last;
};
Person.prototype.fullNameReversed = function() {
  return this.last + ', ' + this.first;
};

Person.prototype is an object shared by all instances of Person. It forms part of a lookup chain (that has a special name, "prototype chain"): any time you attempt to access a property of Person that isn't set, JavaScript will check Person.prototype to see if that property exists there instead. As a result, anything assigned to Person.prototype becomes available to all instances of that constructor via the this object.

This is an incredibly powerful tool. JavaScript lets you modify something's prototype at any time in your program, which means you can add extra methods to existing objects at runtime:

s = new Person('Simon', 'Willison');
s.firstNameCaps(); // TypeError on line 1: s.firstNameCaps is not a function

Person.prototype.firstNameCaps = function firstNameCaps() {
  return this.first.toUpperCase();
};
s.firstNameCaps(); // "SIMON"

Interestingly, you can also add things to the prototype of built-in JavaScript objects. Let's add a method to String that returns that string in reverse:

var s = 'Simon';
s.reversed(); // TypeError on line 1: s.reversed is not a function

String.prototype.reversed = function reversed() {
  var r = '';
  for (var i = this.length - 1; i >= 0; i--) {
    r += this[i];
  }
  return r;
};

s.reversed(); // nomiS

Our new method even works on string literals!

'This can now be reversed'.reversed(); // desrever eb won nac sihT

As mentioned before, the prototype forms part of a chain. The root of that chain is Object.prototype, whose methods include toString() — it is this method that is called when you try to represent an object as a string. This is useful for debugging our Person objects:

var s = new Person('Simon', 'Willison');
s; // [object Object]

Person.prototype.toString = function() {
  return '<Person: ' + this.fullName() + '>';
}

s.toString(); // "<Person: Simon Willison>"

Remember how avg.apply() had a null first argument? We can revisit that now. The first argument to apply() is the object that should be treated as 'this'. For example, here's a trivial implementation of new:

function trivialNew(constructor, ...args) {
  var o = {}; // Create an object
  constructor.apply(o, args);
  return o;
}

This isn't an exact replica of new as it doesn't set up the prototype chain (it would be difficult to illustrate). This is not something you use very often, but it's useful to know about. In this snippet, ...args (including the ellipsis) is called the "rest arguments" — as the name implies, this contains the rest of the arguments.

Calling

var bill = trivialNew(Person, 'William', 'Orange');

is therefore almost equivalent to

var bill = new Person('William', 'Orange');

apply() has a sister function named call, which again lets you set this but takes an expanded argument list as opposed to an array.

function lastNameCaps() {
  return this.last.toUpperCase();
}
var s = new Person('Simon', 'Willison');
lastNameCaps.call(s);
// Is the same as:
s.lastNameCaps = lastNameCaps;
s.lastNameCaps();

Inner functions

JavaScript function declarations are allowed inside other functions. We've seen this once before, with an earlier makePerson() function. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:

function betterExampleNeeded() {
  var a = 1;
  function oneMoreThanA() {
    return a + 1;
  }
  return oneMoreThanA();
}

This provides a great deal of utility in writing more maintainable code. If a function relies on one or two other functions that are not useful to any other part of your code, you can nest those utility functions inside the function that will be called from elsewhere. This keeps the number of functions that are in the global scope down, which is always a good thing.

This is also a great counter to the lure of global variables. When writing complex code it is often tempting to use global variables to share values between multiple functions — which leads to code that is hard to maintain. Nested functions can share variables in their parent, so you can use that mechanism to couple functions together when it makes sense without polluting your global namespace — "local globals" if you like. This technique should be used with caution, but it's a useful ability to have.

Замикання

This leads us to one of the most powerful abstractions that JavaScript has to offer — but also the most potentially confusing. What does this do?

function makeAdder(a) {
  return function(b) {
    return a + b;
  };
}
var x = makeAdder(5);
var y = makeAdder(20);
x(6); // ?
y(7); // ?

The name of the makeAdder() function should give it away: it creates new 'adder' functions, each of which when called with one argument adds it to the argument that it was created with.

What's happening here is pretty much the same as was happening with the inner functions earlier on: a function defined inside another function has access to the outer function's variables. The only difference here is that the outer function has returned, and hence common sense would seem to dictate that its local variables no longer exist. But they do still exist — otherwise the adder functions would be unable to work. What's more, there are two different "copies" of makeAdder()'s local variables — one in which a is 5 and one in which a is 20. So the result of those function calls is as follows:

x(6); // returns 11
y(7); // returns 27

Here's what's actually happening. Whenever JavaScript executes a function, a 'scope' object is created to hold the local variables created within that function. It is initialized with any variables passed in as function parameters. This is similar to the global object that all global variables and functions live in, but with a couple of important differences: firstly, a brand new scope object is created every time a function starts executing, and secondly, unlike the global object (which is accessible as this and in browsers as window) these scope objects cannot be directly accessed from your JavaScript code. There is no mechanism for iterating over the properties of the current scope object, for example.

So when makeAdder() is called, a scope object is created with one property: a, which is the argument passed to the makeAdder() function. makeAdder() then returns a newly created function. Normally JavaScript's garbage collector would clean up the scope object created for makeAdder() at this point, but the returned function maintains a reference back to that scope object. As a result, the scope object will not be garbage collected until there are no more references to the function object that makeAdder() returned.

Scope objects form a chain called the scope chain, similar to the prototype chain used by JavaScript's object system.

A closure is the combination of a function and the scope object in which it was created. Closures let you save state — as such, they can often be used in place of objects. You can find several excellent introductions to closures.