Как писать код в javascript
Перейти к содержимому

Как писать код в javascript

  • автор:

Советы по стилю кода

Это и есть искусство программирования – взять сложную задачу и написать такой код для её решения, который и правильно работает, и легко читается, понятен для людей. Для этого нужен хороший стиль написания кода. В этой главе мы рассмотрим составляющие такого стиля.

Синтаксис

Шпаргалка с правилами синтаксиса (подробнее смотрите ниже по тексту):

Не всё здесь однозначно, так что разберём эти правила подробнее.

Здесь нет железных правил. Это стилевые предпочтения, а не религиозные догмы.

Фигурные скобки

В большинстве JavaScript проектов фигурные скобки пишутся в так называемом «египетском» стиле с открывающей скобкой на той же строке, что и соответствующее ключевое слово – не на новой строке. Перед открывающей скобкой должен быть пробел, как здесь:

А что если у нас однострочная запись, типа if (condition) doSomething() , должны ли мы использовать фигурные скобки?

Вот различные варианты расстановки скобок с комментариями, посмотрите сами, какой вам кажется самым читаемым:

    �� Такое иногда бывает в коде начинающих. Плохо, фигурные скобки не нужны:

Для очень короткого кода допустима одна строка. Например: if (cond) return null . Но блок кода (последний вариант) обычно всё равно читается лучше.

Длина строки

Никто не любит читать длинные горизонтальные строки кода. Лучше всего разбивать их, например:

Максимальную длину строки согласовывают в команде. Обычно это 80 или 120 символов.

Отступы

Существует два типа отступов:

Горизонтальные отступы: 2 или 4 пробела.

Горизонтальный отступ выполняется с помощью 2 или 4 пробелов, или символа табуляции (клавиша Tab ). Какой из них выбрать – это уже на ваше усмотрение. Пробелы больше распространены.

Одно из преимуществ пробелов над табуляцией заключается в том, что пробелы допускают более гибкие конфигурации отступов, чем символ табуляции.

Например, мы можем выровнять аргументы относительно открывающей скобки:

Вертикальные отступы: пустые строки для разбивки кода на «логические блоки».

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

Вставляйте дополнительный перевод строки туда, где это сделает код более читаемым. Не должно быть более 9 строк кода подряд без вертикального отступа.

Точка с запятой

Точки с запятой должны присутствовать после каждого выражения, даже если их, казалось бы, можно пропустить.

Есть языки, в которых точка с запятой необязательна и редко используется. Однако в JavaScript бывают случаи, когда перенос строки не интерпретируется, как точка с запятой, что может привести к ошибкам. Подробнее об этом – в главе о структуре кода.

Если вы – опытный разработчик на JavaScript, то можно выбрать стиль кода без точек с запятой, например StandardJS. В ином случае, лучше будет использовать точки с запятой, чтобы избежать подводных камней. Большинство разработчиков их ставят.

Уровни вложенности

Уровней вложенности должно быть немного.

Например, в цикле бывает полезно использовать директиву continue , чтобы избежать лишней вложенности.

Например, вместо добавления вложенного условия if , как здесь:

Мы можем написать:

Аналогичная ситуация – с if/else и return .

Например, две нижеследующие конструкции идентичны.

Второй вариант является более читабельным, потому что «особый случай» n < 0 обрабатывается на ранней стадии. После проверки можно переходить к «основному» потоку кода без необходимости увеличения вложенности.

Размещение функций

Если вы пишете несколько вспомогательных функций, а затем используемый ими код, то существует три способа организации функций.

Объявить функции перед кодом, который их вызовет:

Сначала код, затем функции

Смешанный стиль: функция объявляется там, где она используется впервые.

В большинстве случаев второй вариант является предпочтительным.

Это потому, что при чтении кода мы сначала хотим знать, что он делает. Если сначала идёт код, то это тут же становится понятно. И тогда, может быть, нам вообще не нужно будет читать функции, особенно если их имена хорошо подобраны.

Руководства по стилю кода

Руководство по стилю содержит общие правила о том, как писать код, например: какие кавычки использовать, сколько пробелов отступать, максимальную длину строки и так далее – в общем, множество мелочей.

Когда все участники команды используют одно и то же руководство по стилю, код выглядит одинаково, независимо от того, кто из команды его написал.

Конечно, команда всегда может написать собственное руководство по стилю, но обычно в этом нет необходимости. Существует множество уже готовых.

Некоторые популярные руководства:

Если вы – начинающий разработчик, то начните со шпаргалки в начале этой главы. Как только вы освоитесь, просмотрите другие руководства, чтобы выбрать общие принципы и решить, какое вам больше подходит.

Автоматизированные средства проверки (линтеры)

Автоматизированные средства проверки, так называемые «линтеры» – это инструменты, которые могут автоматически проверять стиль вашего кода и вносить предложения по его улучшению.

Самое замечательное в них то, что проверка стиля может также найти программные ошибки, такие как опечатки в именах переменных или функций. Из-за этой особенности использовать линтер рекомендуется, даже если вы не хотите придерживаться какого-то конкретного «стиля кода».

Вот некоторые известные инструменты для проверки:

    – проверяет код на соответствие стилю JSLint, в онлайн-интерфейсе вверху можно ввести код, а внизу – различные настройки проверки, чтобы попробовать её в действии. – больше проверок, чем в JSLint. – пожалуй, самый современный линтер.

Все они, в общем-то, работают. Автор пользуется ESLint.

Большинство линтеров интегрированы со многими популярными редакторами: просто включите плагин в редакторе и настройте стиль.

Например, для ESLint вы должны выполнить следующее:

  1. Установите Node.JS.
  2. Установите ESLint с помощью команды npm install -g eslint (npm – установщик пакетов JavaScript).
  3. Создайте файл конфигурации с именем .eslintrc в корне вашего JavaScript-проекта (в папке, содержащей все ваши файлы).
  4. Установите/включите плагин для вашего редактора, который интегрируется с ESLint. У большинства редакторов он есть.

Вот пример файла .eslintrc :

Здесь директива "extends" означает, что конфигурация основана на наборе настроек «eslint:recommended». После этого мы уточняем наши собственные.

Кроме того, возможно загрузить наборы правил стиля из сети и расширить их. Смотрите https://eslint.org/docs/user-guide/getting-started для получения более подробной информации об установке.

Также некоторые среды разработки имеют встроенные линтеры, возможно, удобные, но не такие гибкие в настройке, как ESLint.

Итого

Все правила синтаксиса, описанные в этой главе (и в ссылках на руководства по стилю), направлены на повышение читаемости вашего кода. О любых можно поспорить.

Когда мы думаем о написании «лучшего» кода, мы должны задать себе вопросы: «Что сделает код более читаемым и лёгким для понимания?» и «Что может помочь избегать ошибок?». Это – основные моменты, о которых следует помнить при выборе и обсуждении стилей кода.

Чтение популярных руководств по стилю позволит вам быть в курсе лучших практик и последних идей и тенденций в стилях написания кода.

JavaScript Tutorial

JavaScript is the world’s most popular programming language.

JavaScript is the programming language of the Web.

JavaScript is easy to learn.

This tutorial will teach you JavaScript from basic to advanced.

Examples in Each Chapter

With our "Try it Yourself" editor, you can edit the source code and view the result.

Example

My First JavaScript

Use the Menu

We recommend reading this tutorial, in the sequence listed in the menu.

If you have a large screen, the menu will always be present on the left.

If you have a small screen, open the menu by clicking the top menu sign ☰ .

Learn by Examples

Examples are better than 1000 words. Examples are often easier to understand than text explanations.

This tutorial supplements all explanations with clarifying "Try it Yourself" examples.

If you try all the examples, you will learn a lot about JavaScript, in a very short time!

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

This tutorial covers every version of JavaScript:

  • The Original JavaScript ES1 ES2 ES3 (1997-1999)
  • The First Main Revision ES5 (2009)
  • The Second Revision ES6 (2015)
  • All Yearly Additions (2016, 2017, 2018, 2019, 2020)

Learning Speed

In this tutorial, the learning speed is your choice.

Everything is up to you.

If you are struggling, take a break, or re-read the material.

Always make sure you understand all the "Try-it-Yourself" examples.

The only way to become a clever programmer is to: Practice. Practice. Practice. Code. Code. Code !

Commonly Asked Questions

  • How do I get JavaScript?
  • Where can I download JavaScript?
  • Is JavaScript Free?

You don’t have to get or download JavaScript.

JavaScript is already running in your browser on your computer, on your tablet, and on your smart-phone.

JavaScript is free to use for everyone.

My Learning

Track your progress with the free «My Learning» program here at W3Schools.

Log in to your account, and start earning points!

This is an optional feature. You can study W3Schools without using My Learning.

JavaScript References

W3Schools maintains a complete JavaScript reference, including all HTML and browser objects.

The reference contains examples for all properties, methods and events, and is continuously updated according to the latest web standards.

Как писать код в javascript

JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.

// Tutorial //
How To Use the JavaScript Developer Console

This tutorial will go over how to work with the Console in JavaScript within the context of a browser, and provide an overview of other built-in development tools you may use as part of your web development process.

// Tutorial //
How To Add JavaScript to HTML

This tutorial will go over how to incorporate JavaScript into your web files, both inline into an HTML document and as a separate file.

// Tutorial //
How To Write Your First JavaScript Program

This tutorial will walk you through creating a “Hello, World!” program in JavaScript. To make the program more interesting, we’ll modify the traditional “Hello, World!” program so that it asks the user for their name. We’ll then use the name in a greeting. When you’re done with this tutorial, you’ll have an interactive “Hello, World!” program.

// Tutorial //
Understanding Syntax and Code Structure in JavaScript

In this tutorial, we’ll go over many of the rules and conventions of JavaScript syntax and code structure.

// Tutorial //
How To Write Comments in JavaScript

JavaScript comments are annotations in the source code of a program that are ignored by the interpreter, and therefore have no effect on the actual output of the code. Comments can be immensely helpful in explaining the intent of what your code is or should be doing.

// Tutorial //
Understanding Data Types in JavaScript

In this tutorial, we will go over how data types work in JavaScript as well as the important data types native to the language.

// Tutorial //
How To Work with Strings in JavaScript

A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. Strings in JavaScript are primitive data types and immutable, which means they are unchanging. As strings are the way we display and work with text, and text is our main…

// Tutorial //
How To Index, Split, and Manipulate Strings in JavaScript

In this tutorial, we will learn the difference between string primitives and the String object, how strings are indexed, how to access characters in a string, and common properties and methods used on strings.

// Tutorial //
How To Convert Data Types in JavaScript

This tutorial will guide you through converting JavaScript’s primitive data types, including numbers, strings, and Booleans.

// Tutorial //
Understanding Variables, Scope, and Hoisting in JavaScript

This tutorial covers what variables are, how to declare and name them, and also take a closer look at the difference between var, let, and const. It also goes over the effects of hoisting and the significance of global and local scope to a variable’s behavior.

// Tutorial //
How To Do Math in JavaScript with Operators

In this JavaScript tutorial, we will go over arithmetic operators, assignment operators, and the order of operations used with number data types.

// Tutorial //
Understanding Comparison and Logical Operators in JavaScript

The field of computer science has many foundations in mathematical logic. If you have a familiarity with logic, you know that it involves truth tables, Boolean algebra, and comparisons to determine equality or difference. The JavaScript programming language uses operators…

// Tutorial //
Understanding Arrays in JavaScript

In this tutorial, we will learn how to create arrays; how they are indexed; how to add, modify, remove, or access items in an array; and how to loop through arrays.

// Tutorial //
How To Use Array Methods in JavaScript: Mutator Methods

JavaScript has many useful built-in methods to work with arrays. Methods that modify the original array are known as mutator methods, and methods that return a new value or representation are known as accessor methods. In this tutorial, we will focus on mutator methods.

// Tutorial //
How To Use Array Methods in JavaScript: Accessor Methods

This tutorial will go over methods that will concatenate arrays, convert arrays to strings, copy portions of an array to a new array, and find the indices of arrays.

// Tutorial //
How To Use Array Methods in JavaScript: Iteration Methods

In JavaScript, the array data type consists of a list of elements. There are many useful built-in methods available for JavaScript developers to work with arrays. In this tutorial, we will use iteration methods to loop through arrays, perform functions on each item in an array, filter the desired results of an array, reduce array items down to a single value, and search through arrays to find values or indices.

// Tutorial //
Understanding Objects in JavaScript

Objects are an integral and foundational aspect of most JavaScript programs. For example, a user account object may contain such data as usernames, passwords, and e-mail addresses. Another common use case is a web shopping platform’s shopping cart that could consist of an array of many objects containing all the pertinent information for each item, such as name, price, and weight for shipping information. A to-do list is another common application that might consist of objects.

// Tutorial //
Understanding Date and Time in JavaScript

JavaScript comes with the built in Date object and related methods. This tutorial will go over how to format and use date and time in JavaScript.

// Tutorial //
Understanding Events in JavaScript

Events are actions that take place in the browser that can be initiated by either the user or the browser itself. In this JavaScript aticle, we will go over event handlers, event listeners, and event objects. We’ll also go over three different ways to write code to handle events, and a few of the most common events. By learning about events, you’ll be able to make a more interactive web experience for end users.

// Tutorial //
How To Work with JSON in JavaScript

This tutorial provides an introduction to working with JSON in JavaScript. Some general use cases of JSON include: storing data, generating data from user input, transferring data from server to client and vice versa, configuring and verifying data.

// Tutorial //
How To Write Conditional Statements in JavaScript

In programming, there will be many occasions in which you will want different blocks of code to run depending on user input or other factors. As an example, you might want a form to submit if each field is filled out properly, but you might want to prevent that form from…

// Tutorial //
How To Use the Switch Statement in JavaScript

Conditional statements are among the most useful and common features of all programming languages. “How To Write Conditional Statements in JavaScript” describes how to use the…

// Tutorial //
Using While Loops and Do. While Loops in JavaScript

Automation is the technique of making a system operate automatically; in programming, we use loops to automate repetitious tasks. Loops are one of the most useful features of programming languages, and in this this article we will learn about the while and do…while…

// Tutorial //
For Loops, For. Of Loops and For. In Loops in JavaScript

Loops are used in programming to automate repetitive tasks. In this tutorial, we will learn about the for statement, including the for…of and for…in statements, which are essential elements of the JavaScript programming language.

// Tutorial //
How To Define Functions in JavaScript

A function is a block of code that performs an action or returns a value. Functions are custom code defined by programmers that are reusable, and can therefore make your programs more modular and efficient. In this tutorial, we will learn several ways to define a…

// Tutorial //
Understanding Prototypes and Inheritance in JavaScript

JavaScript is a prototype-based language, meaning object properties and methods can be shared through generalized objects that have the ability to be cloned and extended. This is known as prototypical inheritance and differs from class inheritance. Among popular…

// Tutorial //
Understanding Classes in JavaScript

Understanding prototypical inheritance is paramount to being an effective JavaScript developer. Being familiar with classes is extremely helpful, as popular JavaScript libraries such as React make frequent use of the class syntax.

// Tutorial //
How To Use Object Methods in JavaScript

Objects in JavaScript are collections of key/value pairs. The values can consist of properties and methods, and may contain all other JavaScript data types, such as strings,…

// Conceptual-article //
Understanding This, Bind, Call, and Apply in JavaScript

The this keyword is a very important concept in JavaScript, and also a particularly confusing one to both new developers and those who have experience in other programming languages. In JavaScript, this is a reference to an object. In this article, you’ll learn what this refers to based on context, and you’ll learn how you can use the bind , call , and apply methods to explicitly determine the value of this .

// Tutorial //
Understanding Map and Set Objects in JavaScript

Introduced in ECMAScript 2015, Maps in JavaScript are ordered collections of key/value pairs, and Sets are collections of unique values. In this article, you will go over the Map and Set objects, what makes them similar or different to Objects and Arrays, the properties and methods available to them, and examples of some practical uses.

// Tutorial //
Understanding Generators in JavaScript

In ECMAScript 2015, generators were introduced to the JavaScript language. A generator is a process that can be paused and resumed and can yield multiple values. They can maintain state, providing an efficient way to make iterators, and are capable of dealing with infinite data streams. In this article, we’ll cover how to create generator functions, how to iterate over Generator objects, the difference between yield and return inside a generator, and other aspects of working with generators.

// Tutorial //
Understanding Default Parameters in JavaScript

In ECMAScript 2015, default function parameters were introduced to the JavaScript programming language. These allow developers to initialize a function with default values if the arguments are not supplied to the function call. Initializing function parameters in this way will make your functions easier to read and help you avoid errors caused by undefined arguments and the destructuring of objects that don’t exist. In this article, you will learn how to use default parameters.

// Tutorial //
Understanding Destructuring, Rest Parameters, and Spread Syntax in JavaScript

Introduced in ECMAScript 2015 (ES6), destructuring, rest parameters, and spread syntax provide more direct ways of accessing the members of an array or an object, and can make working with data structures quicker and more succinct. In this article, you will learn how to destructure objects and arrays in JavaScript, how to use the spread operator to unpack objects and arrays, and how to use rest parameters in function calls.

// Tutorial //
Understanding Template Literals in JavaScript

The 2015 edition of the ECMAScript specification (ES6) added template literals to the JavaScript language. Template literals are a new form of making strings in JavaScript that add a lot of powerful new capabilities, such as creating multi-line strings, using placeholders to embed expressions in a string, and parsing dynamic string expressions with tagged template literals. In this article, you will go over the differences between single/double-quoted strings and template literals.

// Tutorial //
Understanding Arrow Functions in JavaScript

Arrow functions are a new way to write anonymous function expressions in JavaScript, and are similar to lambda functions in some other programming languages like Python. They differ from traditional functions in the way their scope is determined and how their syntax is expressed, and are particularly useful when passing a function as a parameter to a higher-order function, like an array iterator method. In this article, you will find examples of arrow function behavior and syntax.

// Tutorial //
Understanding the Event Loop, Callbacks, Promises, and Async/Await in JavaScript

In order to avoid blocking code in JavaScript development, asynchronous coding techniques must be used for operations that take a long time, such as network requests made from Web APIs like Fetch. This article will cover asynchronous programming fundamentals, teaching you about the event loop, the original way of dealing with asynchronous behavior through callbacks, the updated ECMAScript 2015 (ES6) addition of promises, and the modern practice of using async/await.

// Tutorial //
Understanding Modules and Import and Export Statements in JavaScript

As the importance of JavaScript in web development grows, there is a bigger need to use third-party code for common tasks, to break up code into modular files, and to avoid polluting the global namespace. To account for this, ECMAScript 2015 (ES6) introduced modules to the JavaScript language, which allowed for the use of import and export statements. In this tutorial, you will learn what a JavaScript module is and how to use import and export to organize your code.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Подробное руководство по JavaScript

Учебник по JavaScript, с понятными и подробными материалами, содержащими множество примеров и решения различных реальных практических задач.

JavaScript – единственный язык программирования, встроенный в браузер. Он позволяет придать веб-страницам динамичность и интерактивность.

Обязательным условием для изучения JavaScript является знание двух других веб-технологий: HTML и CSS. В отличие от JavaScript, HTML и CSS – это языки для описания структуры и стилей веб-страниц.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *