Menu
Is free
registration
home  /  Installation and setup / Software for working with javascript. What is the best editor for HTML, PHP, CSS, JS code? Conditions and cycles

Software for working with javascript. What is the best editor for HTML, PHP, CSS, JS code? Conditions and cycles

Java Script It! - A nice program for creating good effects on JavaScript. With this program you will clearly make your life easier when creating sites. Basically, it is intended for people who are too lazy to write scripts themselves and generally anything in JavaScript. Of course, when she created it, she focused on beginners, although to work with it you still need minimal knowledge of HTML.

What is javascript?

JavaScript is an object-oriented scripting programming language designed to create active HTML pages. By “active” here we mean HTML pages that host all kinds of dynamically changing web elements, for example:

  • Menus that appear when you hover over the mouse.
  • Small animated images following the cursor or, for example, moving to a certain part of the page when clicking on any element.
  • Information blocks (e.g. with brief description goods) with automated time scrolling and much more.

Those. JavaScript allows you to create web elements that interact in any way with the user, reacting to mouse movements, keystrokes, page scrolling in a browser, etc. In the same list should be added and fully automated web elements that perform any action without user intervention.

As in any other programming language, JavaScript contains concepts such as variables, arrays, logical arithmetic calculations, etc. etc. Those. Using JavaScript, you can perform complex calculations, manage large amounts of data and much more that remains outside the field of view of the site visitor.

Even more opportunities for the programmer are opened by the fact that JavaScript is an object-oriented programming language, but this issue will not be considered here.

Learning JavaScript through Java Script It!

One of the main reasons for such a high popularity of JavaScript among beginner web programmers is the possession of this programming language, the so-called "low entry threshold". Those. To learn it, basic knowledge of HTML and the CSS markup language are sufficient.

Java Script It! provides tools for quickly inserting a variety of ready-made web elements written in JavaScript into an HTML page. All available items are divided into 3 categories:

  1. Applets - elements that perform some independent function: banner, animated text, moving image, etc.
  2. Scripts - basically, user-driven web elements are presented here: forms for entering text by mask (dates, passwords, etc.), blocks that allow you to create slide shows with automatic scrolling of images, various system buttons (for example, to open dialog boxes to upload files to the site).
  3. And DHTML are a variety of interactive elements consisting of HTML markup, cascading CSS tables and JavaScript scripts (for example, drop-down menus or pop-up windows / forms).

Any of the available items has its own settings. For simplicity and convenience of their input / change a special form is provided.

Paste JavaScript code with Java Script It! Looks like that:

  • The user creates an .htm or html file on disk. You can also use a ready-made HTML file filled with some code.
  • Next, select one of the available web elements, then fill out the form with its settings (for example, dimensions, menu item names, etc.).
  • The generated JavaScript code is inserted into the HTML file at the desired position for the user (this is done in the form of web element settings).
  • Done.

In Java Script It! built-in standard Windows browser plug-in Internet explorer, i.e. the result of the work is displayed immediately after finishing the web element setup. You can see the result in any other browser, for which it is enough to open the created / edited HTML file in it.

If you open the source code of an HTML page in a browser, you can view and study the JavaScript code itself. Here you can edit it by changing different meanings manually. Thus, the user will be able to get the basic skills of JavaScript programming, namely, how the code is inserted into the HTML document, which commands are used to configure certain properties of the web element, etc.

Of course, Java Script It! You can use it to fill web pages with various active elements, but due to the obsolescence of the program, it is more suitable for familiarizing yourself with the basics of programming in JavaScript.


This chapter is about the JavaScript scripting language. You will learn what JavaScript is and why it is needed.

Consider the features of creating dynamics on the page, processing forms, as well as working with layers and styles.
Javascriptis an object-oriented scripting programming language with syntax slightly similar to C syntaxes, Perland Python. Although the language has a similar name to the language java programming, they have nothing in common except part of the name.

Currently Javascriptit is mainly used to create scripts embedded in web pages that allow full control of both the web pages themselves and the web browsers in which these web pages are open. Thus language Javascriptin most cases used to create interactive web pages and web applications.

The Internet is built on technology " client server».
Servers are computers or programs that provide any services to clients, such as a web server or email server.
Clients are computers or programs that use what servers offer, such as web browsers or email clients.

Scenarios Javascript- these are small programs that run on the user's computer when downloading from the server along with web pages.

JavaScript Scope

From the very beginning of its development, the JavaScript language has been used to write various client-side scripts. They were widely used to solve problems such as, for example, checking information entered by the user on a form before sending it to the server or programming responses to user actions that make web pages interactive. Today, using the JavaScript language, whole web applications are already being created, some of which are not much inferior to their desktop "brothers." Good examples such web applications can be found among the services of Google, for example Google Calendar - a multifunctional organizer in a web browser and Google doc & Spreadsheet is a text and spreadsheet editor that allows you to work with office documents directly in a web browser window. To create dynamic content on web pages, the language used to create dynamic pages is HTML Dynamic HTML, which is again a key part of JavaScript.

JavaScript is used not only on the Internet, but also in programs such as, for example, Adobe Dreamweaver, Adobe acrobat Reader and Adobe Photoshop to expand their capabilities, similar to using the Visual Basic language in Microsoft Office.

Now let's look at creating scripts and how to embed them in an HTML document.

Scripting

We will analyze all the stages of creating a JavaScript script - from organizing a working environment to connecting code to an HTML document.

Almost any text editor is suitable for working on scripts, allowing you to create regular text files and save them with the htm or html extension. For example, in the operating room windows system Among the standard ones there are two suitable text editors - Notepad and WordPad. There are also editors specifically designed to create web pages, such as Microsoft FrontPage and Adobe Dreamweaver (formerly known as Macromedia Dreamweaver). Such editors allow you to create web pages using visual tools, and then switch to code display mode and make custom changes, such as adding scripts. Unlike ordinary text editors, in such editors, the syntax of the HTML and JavaScript languages \u200b\u200bis highlighted, which is very convenient.

In addition, on the Internet you can find a large number of other text editors that allow you to create web pages and highlight the syntax of the HTML and JavaScript languages. These editors also have many other useful features that greatly simplify the process of creating web pages and developing scripts. Many of these editors are distributed for free or shareware, and you may like some of them.

You will create scripts that manage web pages, so to check the functionality of these documents you will need some kind of web browser. Please note that by checking the performance of your creation in one web browser, you cannot be sure of its performance in others. Therefore, it is advisable to check web pages in several web browsers, and the more there are, the better.

Web developers have to reckon mainly with the features of the web browser Microsoft Internet Explorer Therefore, your web pages must be tested in this web browser, which is available in each operating system Windows
Web browsers are also very popular. Mozilla firefox and Opera, which strive to meet standards as much as possible. Mozilla Firefox can be downloaded from http://www.mozilla.ru/, and Opera from the site.

Consider separately debugging a program (script). When the script is large, it’s not so easy to figure it out and debugging, that is, the process of finding and eliminating errors, can take up most of the development time of the entire program (or script). To simplify and speed up debugging created special programscalled debuggers. A typical debugger has such features as step-by-step execution of a program with a stop in each line of code or at breakpoints previously marked for this, as well as tracking and changing the values \u200b\u200bof each variable directly during program execution.

There are many programs for debugging JavaScript scripts. For example, the Microsoft Script Debugger has everything you need to successfully debug JavaScript scripts. It is used in conjunction with the Microsoft Internet Explorer web browser. This installer is distributed free of charge by Microsoft, and can be downloaded from the site. In addition, this debugger is distributed with microsoft editor FrontPage as part of microsoft programs Script Editor, which is practically no different from Microsoft Script Debugger.

There are also other debuggers, for example, for the Mozilla Firefox web browser, they are created as extensions. In particular, the FireBug debugger can be downloaded from the site, and if you go to this page in the Mozilla Firefox web browser, the debugger will be installed immediately.

We will not consider the debugging process in this book, since this is a separate topic that requires careful study. To write simple scripts, no debugging is required.

Script embedding

Consider embedding scripts in web pages.
Scripts are embedded in an HTML document in three standard ways:

text as a script in any language. The scripting language is specified using the type attribute. For example, to indicate the JavaScript language, the following code is used:

This attribute can be omitted, since the value "text / javascript" is the default value.

You can use comments in script code - text that is ignored by the JavaScript interpreter. Comments // and

Comments can also be multi-line, which facilitates debugging the script and allows you to comment out the problem part of the code. For this purpose, the character sets / * and * / are used, as, for example, in the following code:

Scripts can be contained in the web page itself, as described above, and in a separate file. Tag

...

4. Save the file, for example with the name script1.html.
After creating a web page with a script, you can see how it will look in a web browser. To make sure that the script works as it should, check it in all web browsers installed on your computer.
5. Launch a web browser and open the created web page in it.

So, if you did everything correctly, ten messages “Hello world !!!” will appear on the screen of your web browser (Fig. 2.3).

When developing scripts, usually both the text editor in which the web page is created and several web browsers in which the health of the created web page are checked are simultaneously opened. After making changes to the script, just switch to a web browser and click the Update button.


Fig. 2.3. Your first web browser script

JavaScript Syntax and Essentials

Now we will explain the basic elements of the JavaScript language: variables, data types, expressions, various operators, functions, etc. This knowledge is basic, since without them it is impossible to understand the rest of the material.

Work with information

Any program or script works with information, that is, they receive some data, process it according to their own algorithm, and then, as a rule, return a certain result in the form of an image, sound, file, signal to another program, etc.

Client scripts often act as a buffer between the user and the server program, carrying out preliminary processing and verification of data.

Client scenarios can receive information in the following ways:

/ data embedded in the script by the developer (initial values);
/ data received from the user using the forms;
/ data transmitted via URL;
/ information obtained by processing events, for example, when you move the mouse pointer, click or press a key;
/ data received from other sites or transmitted by the server program.

Consider input / output of information in JavaScript using the following three methods: alert (), prompt (), and confirm (). These methods generate various message boxes.

Alert () method

The alert () method displays a warning dialog box with the corresponding message. After reading the message, the user must click on the OK button to close the window. The argument to this method is a string.

In the simplest case, the warning text enclosed in quotation marks is entered inside parentheses (Listing 2.3).

Listing 2.3. Work with warning

Work with warning

The warning window is generated by the browser itself, so the appearance of the window in different browsers may vary. In fig. 2.4 shows a window generated using the presented code in Internet Explorer.


Fig. 2.4. Work with warning

Prompt () method

The prompt () method is used to receive data from the user (Listing 2.4).

Listing 2.4. Work with the request

Work with the request

When you call it, a prompt dialog box appears with a text box. This method can contain two arguments. The first argument is the message displayed in the dialog box. The second argument is the default text, which should appear in the corresponding field. In addition, this method returns a value - the text that the user entered.

After launching the page with the above code, a request appears (Fig. 2.5), followed by a warning.


Fig. 2.5. Work with the request

In this example, a variable is used to demonstrate the operation of the prompt () method, and an expression is used as an argument in the alert () method. We will analyze these concepts below.

In the prompt () method, you can omit the second argument, that is, specify only one line.

Confirm () method

The confirm () method displays a confirmation dialog box that contains two buttons: OK and Cancel. Listing 2.5 shows the code for creating a confirmation window, but the difference between the OK and Cancel buttons is not emphasized in this scenario.

Listing 2.5.Confirmation Work

Confirmation Work

Clicking on any of the buttons will close the dialog box (Fig. 2.6).


Fig. 2.6. Confirmation Work

The script may respond differently to clicks on the OK and Cancel buttons.

Variables and Data Types

During the interpretation of the script, the browser breaks the code into separate characters, words or phrases that it can recognize. These elements are called tokens. In JavaScript, tokens are divided into four types: identifiers, keywords, literals, and operations.

Identifiers

Identifiersare the names that denote variables, functions, and objects. Some names cannot be used as identifiers, as they have a special meaning. Identifiers are formed using combinations of different characters with the following restrictions:

/ all identifiers must begin with a letter;
/ after the first letter, the remaining characters can be letters and numbers;
/ letters are all uppercase and lowercase letters of the Latin alphabet: from A to Z and from a to z;
/ the underscore (_) acts as a letter and is often used instead of a space that cannot be used in identifiers;
/ the dollar symbol ($) acts as a letter and is usually used when automatically generating code.

TIP
Do not use identifiers in one scenario that differ only in upper and lower case characters, such as flagId and FlagID. These are various identifiers that can cause subtle errors.

In the table. 2.1 Examples of valid and invalid identifiers are provided.

Valid Invalid
count 2my
x new
X my№
is_well is well

Table 2.1. JavaScript ID Examples

Please note that the new identifier, although it contains permitted characters, is one of the keywords, therefore it cannot act as a user identifier.

Key words and reserved words

Keywords are predefined identifiers that form the core of the JavaScript language. These words have a special meaning and perform certain functions. Keywords cannot be used for user identifiers. In the table. 2.2 is a list of JavaScript keywords.

break else new typeof
case finally null var
catch for return void
continue function switch while
default if this with
delete in throw
do instanceof try

Table 2.2. JavaScript Keywords

abstract enum int short
boolean export interface static
byte extends long super
char final native synchronized
class float package throws
const goto private transient
debugger implements protected volatile
double import public

Table 2.3. JavaScript Reserved Words

Literals

Literalsare numbers or strings that are used to represent values \u200b\u200bin JavaScript. Information can be very diverse, so the meanings are of various kinds. The simplest data types in JavaScript are called basic data types: numbers, strings and logical values.

JavaScript numbers are of two types: integers and floating-point numbers. Integer values \u200b\u200bcan be positive, for example 1, 2, 3, negative, for example –1, –2, –3, and equal to zero. In addition, integer values \u200b\u200bcan be expressed in decimal, octal, or hexadecimal notation.

Numbers in decimal format can include any sequence of digits from 0 to 9 that does not start from zero.

Numbers in octal format can include any sequence of digits from 0 to 7, which necessarily starts from zero.

Numbers in hexadecimal format can include any sequence of digits from 0 to 9 and letters from a to f, which must begin with 0x.

Consider examples of representing integers in various formats (table. 2.4).

Decimal format Octal format Hexadecimal format
45 055 0x2d
– 255 – 0377 - 0xff
10000000 046113200 0 × 989,680
10 012 0XA

Table 2.4. Integer Examples

Floating-point numbers define decimal numbers with a fractional part. These numbers can be expressed in the usual form or in exponential notation. In the latter case, the symbol is used to represent the order e or E. The decimal mantissa and order can be positive or negative. The following are examples of floating point numbers.

1.4142135623730950488016887242097 -35.0 4567.0002 3.4e100 -5.456e-3 0.007

JavaScript supports logical data types that can take only two values: true (true) and false (false). Logical (Boolean) quantities are necessary to deal with conditions that you will meet later in this chapter.

ATTENTION!
The keywords true and false must be entered in lower case letters.

The most commonly used JavaScript data type is probably a string. Lineis a character set (possibly empty) enclosed in single or double quotes. Two types of quotation marks are used because a string can contain quotation marks of some kind. The following are examples of string literals:

"Line of text" "Russia!" "4567" "" "Operating Systems" "Lewis Carroll" Alice in Wonderland ""

Sometimes it may be necessary to instruct the computer to use special characters, such as tabs or line feeds. To include any Unicode character in the string, you need to enter its code after the service character \\ u in the form \\ uXXXX. In the table. 2.5 provides the most commonly used control characters.

Control sequence Unicode Description Symbol
\\ b \\ u0008 Return to one position (backspace)
\\ t \\ u0009 Horizontal tab
\\ n \\ u000A Line feed (new line)
\\ v \\ u000B Vertical tab
\\ f \\ u000C Page feed
\\ r \\ u000D Carriage return
\\ u0022 Double quote »
\’ \\ u0027 Single quote
\\ \\ u005C Backslash \

Table 2.5. Control characters

Often control characters are used to align data (Listing 2.6).

Listing 2.6. Aligning data with control characters

Alignment with escape characters

The dialog box created by the alert () method depends on the browser, so alignment in different browsers is different. The above code is adapted to the Microsoft Internet Explorer program (Fig. 2.7).


Fig. 2.7. Alignment with escape characters

In addition to numbers, strings, and logical quantities, there are two more special types of data: functions and objects. Functions can be built-in, such as alert (), or they can be created by the developer. In addition, functions may belong to an object (in this case they are called methods) Objects can also be embedded (for example, document), or they can be created by a programmer. The null value is considered to be an object.

Variables

Variable- This is the name assigned to the computer’s memory cell that stores certain data while the script is running. Variables make it easier for a programmer to manipulate data.

The variable name is an identifier, therefore, follows the same rules.

Before using a variable, you must declare it, that is, reserve a place to store data. To declare a variable, the var keyword should be followed by its identifier. You can declare several variables at once by specifying their names with a comma:

Var myData1; var x, y, z; var k, msg1, msg2, IM;

In the process of declaring a variable, you can initialize it, that is, set the initial value for it:

Var myStr \u003d "Hello,"; var k \u003d 1000, x \u003d 12, y \u003d –5; var s \u003d 1.34e-5, msg11 \u003d "Error", Flag \u003d false;

Until a variable receives a value, it is undefined - undefined. To determine the type of a variable, you can use the typeof operation, which returns a string with the type of the variable (Listing 2.7).

Listing 2.7. Data types

Data types

Data types


In the above code, we used the document.write () method to display information, which allows us to append a line of text directly to the page (Fig. 2.8).


Fig. 2.8. Data types

To display the text, the values \u200b\u200bof the variables and their type, the argument of this method is a rather complex expression. The expressions will be explained in more detail below.

Scope variables are divided into global and local. A variable declared inside a function is local, and only this function has access to its value. Local variables are created and destroyed along with the corresponding function. Global variables are declared outside functions. Such variables allow functions to exchange data.

Array- This is a special variable that allows you to store multiple values \u200b\u200bat once. Typically, these values \u200b\u200bare related, such as the names of the months and days of the week. Arrays can greatly simplify code and, when using loops, reduce the complexity of developing a script.

Consider an example of declaring and setting values \u200b\u200bfor array elements (Listing 2.8).

Listing 2.8. Work with array

Work with array

Please note that when declaring an array, the number of elements is indicated in parentheses, and when accessing an element, its index is specified in square brackets. In addition, the numbering of array elements in JavaScript starts from scratch, so the stars element will be the first element in the array.

JavaScript makes it possible to display all elements of the array, rather than listing them one at a time. To do this, turn to the array itself. The result is a string in which all elements of the array are listed with a comma (Fig. 2.9).


Fig. 2.9. Output all array elements

Values \u200b\u200bof array elements can be specified when declaring an array. In this case, you do not need to specify the number of elements in the array (listing 2.9).

Listing 2.9. Array initialization

Array initialization

The dimension of the array can be omitted, since JavaScript does not require this. An array can be expanded as data is added. Moreover, you can declare an item with an index nthat will increase the length of the array to n + 1. You can find out the length of the array using the length property (Listing 2.10).

Listing 2.10. Array size

Array size

Despite the fact that there are actually 6 elements in the array, the length of the array is 100 (Fig. 2.10).


Fig. 2.10. Array size

Expressions

Expressionsare operands combined by operations. Usually, values \u200b\u200band variables act as operands, but other expressions can also appear. For example, the expression 4 + 6 adds up two values, resulting in the value 10. And the expression q \u003d 5 sets the variable q to 5. If the manipulations are performed with one value, then the operation is called unary, and if over two - binary. Next, consider the operations in JavaScript.

Assignment Transactions

One commonly used operation is the assignment operation. In the simplest case, this operation assigns a value to a variable:

This operation can be used simultaneously for several variables:

msg1 \u003d msg2 \u003d "Hello"

Other assignment operations are combinations of assignment operations and arithmetic or bitwise operations (table. 2.6).


Table 2.6. Combined Assignment Operations

Arithmetic operations

/ Addition is a plus sign (+). For example, 5 + 7 \u003d 12.
/ Subtraction - minus sign (-). For example, 67 - 43 \u003d 24.
/ Multiplication - asterisk (*). For example, 2 * 2 \u003d 4.
/ Division is a slash (/). For example, 45/5 \u003d 9.
/ The remainder of the division is the percentage (%). For example, 7% 5 \u003d 2.
/ Arithmetic operations are used to work with numbers.

In programming, the operations of increasing or decreasing a variable by one are very common (increment and decrement operations). The increment is indicated by the sequence ++ and decrement by sequence . For instance, i ++ is an alternative to expression i \u003d i + 1.

Distinguish between the prefix and postfix form of these operations. In the case of a prefix operation, an increment or decrement is first performed, and then the expression is calculated:

i \u003d 4
++ i * 2 \u003d 10

If a postfix operation is used, then the expression is calculated first, and then the variable is increased or decreased:

i \u003d 4
i ++ * 2 \u003d 8

Listing 2.11 shows how to work with arithmetic operations.

Listing 2.11. Arithmetic operations

Arithmetic operations

Arithmetic operations


In this example, you will notice that arithmetic operations obey mathematical rules. For example, multiplication takes place before addition (Fig. 2.11).

This is done due to the priority of operations, which can be changed using parentheses.


Fig. 2.11. Arithmetic operations

Comparison operations

Comparison operations are used to match operands. In these operations, operands can be not only numbers, but also strings, logical quantities, and objects. In the table. 2.7 provides all the comparison operations.


Table 2.7. Comparison operations

Listing 2.12 shows the code that uses the comparison operation.

Listing 2.12. Comparison operations

Comparison operations

Comparison operations


The code above compares the variables i \u003d 5 and m2 \u003d "5 ″. They are considered equal, but not identical (Fig. 2.12).


Fig. 2.12. Comparison operations

String Operations

As already mentioned, strings can be compared. In addition, they can be combined using the concatenation operation. (+) that we have done more than once. For instance:

S1 \u003d "Hello"; S2 \u003d ","; S3 \u003d "World!"; S \u003d S1 + S2 + "" + S3;

As a result, the variable S will contain the string "Hello World!".

Thanks to automatic casting, you can combine numbers and strings:

"year" + 2008 \u003d "year 2008"

Logical operations

Logical operations allow you to combine expressions that return logical quantities. JavaScript supports three logical operations.

Logical AND operation (&&) returns trueonly if both operands are true. For instance, (12) .

Logical OR operation (||) returns trueif at least one operand is true. For instance, (22) .

Logical operation NOT (!) is unary and reverses the value of a logical quantity.

Conditional operations

JavaScript has an operation ?: , which assigns the value of a variable depending on the condition. Consider the following example:

Var sign \u003d (a\u003e \u003d 0)? "Positive": "Negative";

The result of the expression before the question mark affects the value of the variable: if the value is true, then the expression before the colon is calculated, if false, then the expression after the colon is determined. In our case, if the variable a is greater than or equal to 0 variable signtakes the value "Positive", otherwise - the value "Negative".

In JavaScript, there are also operations (for example, bitwise), which are quite rare and are needed when solving specific problems, so we will not consider them.

Conditions and cycles

There are branching mechanisms for changing the order of code execution in JavaScript (if and switch statements)allowing you to choose one of the alternative actions depending on the condition. For repeated code execution, loop operators are used. (while, for and do). Loops are also convenient for manipulating arrays.

If statement

Operator ifcontrols the sequence of command execution. The syntax for this statement is as follows:

If (boolean expression) (operators)

The logical expression is computed first, then if it is equal to true, statements are executed; if it is equal false, then the operators are skipped and the script continues to run.

Consider an example. Let's say the function f (x) defined as follows:

X + 10, at x< 0 f(x)= x2 + 4, при 0 ≤ x ≤ 5 5 / x, при x > 5

You can use the code in Listing 2.13 to determine the value of this function at a specific point.

Listing 2.13. An example of the if statement

An example of the if statement

If .. else statement

It is often convenient to use the full form of a conditional statement. Using this operator, you can specify the actions to be performed if the logical expression is equal to false:

If (boolean expression) (operators1) else (operators2)

Moreover, it is possible to combine elsewith another operator if. In this case, you can consider several alternative options and execute the corresponding operators:

If (boolean expression1) (operators1) else if (boolean expression2) (operators2) else (operators3)

We rewrite the previous script to define the function using the if..else operator (Listing 2.14).

Listing 2.14. An example of the if..else statement

An example of the if..else statement

As you can see from this code, curly braces are optional if only one statement is executed. However, it is recommended that you always use them to simplify code reading.

Switch statement

The switch statement compares a value with many other values. The same effect can be achieved with the help of several if statements, however, the switch statement allows you to create a short and clear code:

Switch (expression) (case value1: statements case value2: statements .. default: statements)

Suppose you want to create a script that translates animal names from English (Listing 2.15).

Listing 2.15.

Switch statement example

This code allows you to translate one of the three names of animals (Fig. 2.13).


Fig. 2.13. The result of the switch statement

Note the break statement, which terminates the switch statement. Otherwise, the remaining code will be executed in the switch statement, regardless of the value of the variable.

The for statement is used to create a loop. This statement has the following syntax:

For (initialization expression; condition expression; loop expression) (operators)

An initialization expression usually serves to set the initial value of the loop counter. The condition expression terminates the loop when it evaluates to false. A loop expression typically increments or decrements a loop counter. Any of these expressions can be omitted, but the corresponding semicolon should be put.

Listing 2.16 shows the code to find the factorial of n! \u003d 1 ∙ 2 ∙ 3 \u200b\u200b∙ ... ... ∙ n using the for loop.

Listing 2.16. Finding a factorial using the for statement

Factorial using the for statement

In this code, a cycle from 1 to x is organized, while for simplicity, the entered value is not checked for validity. Based on this, you can, for example, get the value Infinity (infinity) with a large value of x.

The while statement is similar to the for statement, but it does not initialize or increment the counter in its declaration. The syntax for this statement is as follows:

While (condition expression) (operators)

If the condition expression in the while loop is false, then the statements will never be executed.
Listing 2.17 shows the code to find the factorial using a while loop.

Listing 2.17. Finding a factorial using a while statement

Factorial using the while statement

Do .. while loop

The do..while statement is almost identical to the while statement. However, in this statement the condition is checked at the end, therefore it guarantees the execution of the operators at least once, regardless of the truth of the condition:

Do (statements) while (condition expression)

Listing 2.18 shows the code to find the factorial using the do..while loop.

Listing 2.18. Finding factorial using do..while operator

Factorial using the do..while operator

For .. in loop

The for..in loop allows you to execute statements for almost every property of an object. The syntax for this statement is as follows:

For (property in object) (operators)

For example, using this operator, you can increment all elements of an array (Listing 2.19).

Listing 2.19. Using the for..in operator

Example of using the for..in operator

As a result of the execution of this code, all elements of the array a will increase by 1 (Fig. 2.14).


Fig. 2.14. Increment array elements

Break and continue statements

Sometimes during the execution of a cycle, it becomes necessary to interrupt the entire cycle or one of its iterations. The break and continue statements are used for this purpose. The break statement completely stops the execution of the loop and transfers control to the statements following the loop. The continue statement interrupts the current loop execution and proceeds to the next loop step. The difference in how these operators work is shown in Listing 2.20.

Listing 2.20. Using loop exit statements

Example of using loop exit statements

This code allows you to determine the quotient of the number and elements of the array a entered by the user. Moreover, among the elements of this array there may be zeros, then it is necessary to enter a dash “-” in the array element with the result b. The result of processing the code in this case you see in Fig. 2.15.


Fig. 2.15. Using loop exit statements

The above code also demonstrates the ability to embed one loop in another. You can exit the while loop only when zero is entered (default value). If you enter other numbers, the cycle will not end the job. A for loop at runtime is sometimes interrupted if the element of array a is zero (to avoid division by zero).

The code editor is a handy tool for every programmer. And everyone picks up for himself: someone appreciates functionality, someone mobility, for someone the main thing is design and convenience. Someone even likes to write code in Notepad, but it's like trying to build a house with a hammer.

JavaScript is a powerful and moody language. On the one hand, a lot of frameworks and libraries, on the other - not the simplest syntax and dangers associated with the "dynamics". Therefore, to work with it, it is important to choose an editor. The right choice will provide you with clean code, high development speed, minimum errors and the pleasure of working. Spend a lot of time choosing one of the hundreds of existing editors, so we did some of the work for you. Here are the top 5.

Webstorm

JetBrains WebStorm is beautiful in both of its manifestations: as an IDE it supports working with version control systems, allows you to remotely deploy code, as an editor - standard amenities, such as syntax highlighting, auto-completion, navigation.

Benefits:

  • LiveEdit - view changes made to the code without the need to save it;
  • interaction with frameworks, for example React, Angular, Meteor;
  • more than a hundred built-in tests to detect errors;
  • integration with Mocha, Protractor, Jest, Karma for unit tests;
  • full-scale debugger for debugging code on the server and client sides;
  • navigation for simultaneous work with several files;
  • code completion, syntax highlighting.

Disadvantages:

  • costs $ 129 for the first year of work;
  • for beginning coders, the functionality is redundant.

Visual studio code

Visual Studio IDE branch aimed at working with code. It is easy to learn, convenient to use, and at the same time functional.

Benefits:

  • contextual autocompletion, both syntax and used variables, modules, functions, etc .;
  • debugger with breakpoints, call stack, interactive console;
  • support for snippets and templates;
  • git integration
  • convenient and simple interface;
  • free editor.

Disadvantages:

  • few plugins.

Sublime text

Convenient and time-tested cross-platform editor, with a customizable interface and the ability to perform trivial actions using hot keys.

Benefits:

  • hotkeys;
  • code navigation in the form of a mini-map;
  • the ability to change the visual theme;
  • snippet support;
  • highlighting, auto-completion of variables and syntax;
  • multiple editing through the use of pointers;
  • build system support;
  • syntax checking right during input;
  • autosave.

Disadvantages:

  • the full version costs $ 70;
  • lack of a code analyzer for linking.

Atom editor

Git's code editor, which appeared in 2015, copies the design of Sublime Text and is wrapped in Chromium.

Benefits:

  • more than 50 open modules;
  • convenient and pleasant interface;
  • free;
  • code completion and highlighting;
  • package manager, which is already more than 3.5 thousand;
  • flexible settings for the editor, plug-ins, interface themes;
  • editing and navigation using hot keys.

Disadvantages:

  • low productivity;
  • empty equipment "out of the box."

Brackets

In 2014, Brackets frightened off programmers with bugs and shortcomings, but now it is gradually regaining confidence with new high-quality functionality.

Benefits:

  • rich equipment "out of the box";
  • live Preview mode - a preview of edits in the browser in real time;
  • package manager;
  • display in the code used images and colors;
  • auto-completion and syntax highlighting;
  • code analyzer;
  • free.

Disadvantages:

  • strict orientation to the web and HTML + CSS + JavaScript;
  • slow development;
  • slow performance due to preview features.

Nowadays javascript It occupies a leading position when it comes to the client side of software products and is used by professional programmers and web developers around the world. javascript It is a powerful programming language with many advanced features and infrastructures like jQuery, YUI, SproutCore, and Cappuccino. But it has certain drawbacks, for example, javascript in different browsers works differently and can limit access to the website and its user friendliness. But these factors should not limit the possibilities of this wonderful language.

For many programmers, working with javascript may seem a bit complicated, but we have many tools for javascript developers that are not only easy to use, but also show great results in minutes. Having knowledge in javascript, you can perform any tasks - writing documentation, editing, testing, debugging, etc.

Documentation Tools

jGrouseDoc is a tool that allows you to generate API documentation from comments in the source code (program) and thus document all the necessary concepts, functions, variables, classes, interfaces, namespaces, etc., which results in an excellent custom product.


JSDoc Toolkit is an application written using javascript to automatically generate template formats and multilingual HTML documentation from javascript commented source code.

Compression tools


JSCompress is an online javascript compressor that compresses javascript files using compression algorithms like JSMin and Packer, and compressed javascript files are just perfect for your work environment, as their size is reduced by 30% –90%.


YUI Compressor is a javascript reducer designed to get a higher compression ratio than other tools can provide. Starting with version 2.0, YUI Compressor compresses CSS files using a port based on the regular Isaac Schluter expression.


javascript Compressor compresses and optimizes your javascript files. Because of this, they load faster and thus reduce bandwidth usage. Because of this, function names and global variables remain intact.


Scriptalizer is an online tool to reduce your Java and CSS scripts, which allows you to save hard disk space by reducing code size. It also removes extra spaces, tabs and blank lines, newlines and comments, and also blocks delimiters.

Formatting tools


JSbeautifier is an online tool that reformatts and indents bookmarklets (from the words bookmark and applet), “untidy” javascript code fragments and decompresses scripts, and also unravels complex script fragments. Just paste your code and click on the “Decorate” button.

Editors and Toolkits for the IDE


Aptana Studio is a web development work environment from a leading company in its field, which combines powerful software products for working with HTML, CSS and javascript. Aptana RadRails is a complete development environment for building professional applications with a rich extension of Ruby & Rails, javascript, CSS and HTML code.


The Spket IDE is a powerful development toolkit for javascript and XML, as well as javascript, XUL / XBL and Yahoo Widget. Provides features such as code extension, syntax highlighting, and content plan.


Komodo Edit is a free, multi-language open source editor for easier writing of quality code. It supports PHP, Python, Ruby, Perl, and Tcl, as well as javascript, CSS, HTML, and template languages \u200b\u200bsuch as RHTML, Template-Toolkit, HTML-Smarty, and Django.

Debugging tools


Firebug is the most powerful web development tool used to validate HTML and style and layout modifications in real time, to accurately analyze network usage and performance. The javascript debugger can be used with any browser.


Blackbird is an open source project that offers an easy way to log messages in javascript and an attractive console for viewing and filtering them, thus minimizing or completely eliminating the use of the alert () function.


Faux Console is javascript that can be inserted into a document to get the basic setup console in IE, and you can use the YUI files or the console.log () file to log information between browsers.


JS Bin is a web application that helps javascript and CSS snippets be tested in a specific context and build code together. Allows you to edit and test javascript and HTML.


JSON is a data format that is gaining popularity these days and is widely used in many AJAX Web 2.0 sites. Many sites that offer APIs return data in JSON format. Often in the data provided by JSON, spaces are compressed in order to reduce the amount of data transferred. This site provides you with a quick and easy way to format JSON so that you can read it.


Eclipse Marketplace Client (MPC) is a rich client interface for viewing and installing Eclipse-based solutions. MPC provides strong installation integration between the Eclipse workbench and the Eclipse Marketplace, plus prints of third-party solutions.


Venkman is a javascript installer for Mozilla based on browsers such as Firefox 3.x, Netscape 7.x, Seamonkey 1.x, and Mozilla Seamonkey 2.x. The installer is also available as an extension package in XPI format.


JS.Class is a set of tools for creating object-oriented javascript programs based on Ruby. It also offers a powerful package manager, the purpose of which is to help download your applications and support all major web browsers, including Rhino, Node.Js and Narhwal.

Testing tools


Sugartest makes it easy to write tests for javascript, it runs on top of JsUnitTest, like DSL, which has install, uninstall, embedded content, no dependencies, and the work is done using simple and at the same time expressive syntax.


jSLint takes the javascript source and scans or notes problems. If he finds a problem, he displays a message describing it, and also indicates the location where there should not be a syntactic problem, and also checks the style selection and structural programs.


Created by John Resig and Jan Odvarko, FireUnit introduces a simple javascript API for conducting a simple test to log it and view it in a new Firebug tab.


JsUnit is a module that tests the structure of the client side of javascript, which acts as a JUnit port, and also includes a platform for automating testing in various browsers and computers running various operating systems.


YUI Test is a testing environment for browser-based javascript solutions in which you can easily add unit testing to javascript solutions. The YUI Test also provides an advanced error detection feature for those methods that move errors, asynchronous tests for checking events, Ajax-based communications, and more.


JSpec is a very small but very powerful testing environment that uses its own grammar and preprocessor, and includes many alphabetic abbreviations, readable syntax, support for Async and Rhino, a nested description, a general mode of operation, support for accessories, ajax simulation and much another.


JSLitmus is a lightweight tool for creating highly specialized javascript control tasks that works with all the most common browsers. It has an open source, MIT-style license, adaptive test cycles and can also be placed on existing web pages or applications.


The outstanding javascript Checker is used to track a ;; elements on the web page, and when it finds an HTML element with inline events, it highlights this section with a red border and javascript: links are crimson.

Other useful tools


PrettyPink is a javascript variable dumper built into the browser that allows you to print objects of any type for viewing during setup sessions in table format. It does not require any style sheets or images, it can work with an infinite number of nested objects, protects against circular / duplicate links and is fully compatible with JSLint.


Firediff is an extension for Firebug designed to track changes in the DOM and CSS, that is, it monitors changes, which provides an opportunity to understand the functionality of the application, and also records changes made and adjusts the display of the page.


JS charts is a javascript chart generator that allows you to create charts using a variety of patterns, such as bar charts and simple line charts.


PageSpeed \u200b\u200bis an open source Firefox / Firebug add-on that is used to evaluate the performance of web pages and get recommendations for improving them. It also speeds up your site, reduces the use of line bandwidth and hosting costs.


Rockstar Web Profiler or Razor includes three components, namely, RockStar Profiler Server for analyzing network connections and server performance, RockStar Profiler Probe for analyzing client-side performance and RockStar Profiler Console, which is information for analyzing collected performance data.


The mobile (under Safari) javascript structure, in a reduced form, weighs less than 8 Kb, accesses the Sizzle lab on the iPhone, supports CSS transitions and animations, is object-oriented and easily extensible.


php.js is an open source project for porting high-level PHP functions to low-level javascript platforms, for example, web browsers, browser extensions, AIR and SSJS engines, for example, V8, Rhino and SpiderMonkey.


JSSpec is a javascript "BehaviorDrivenDevelopment" structure that shows the difference between expected and actual values, clearly shows the line of damage, supports conditional execution of support for IE 6 or IE 7, FireFox 2 and Safari 3.


MochaUI is a library of user interfaces in the form of a web application built on top of Mootools javascript used in web applications, web elements on the desktop, websites, widgets and separate dialog boxes.


Highlight.js highlights the syntax in the sample code on blogs, forums and, in general, on any web page. Automatically finds code blocks, determines the language and selects it.

Libraries of utilities and components for javascript


Uploadify is a jQuery plugin that makes it easy to integrate multiple downloads into your website and which requires Flash or any other internal development language. The basic implementation is quite simple and offers tremendous room for modification for advanced users.


Burst is an example of a characteristic animation using javascript and HTML5 technologies and without any use of Flash technology. An SVG file is created using Inkscape. Burst is syntactically similar to jQuery.


JSTestDriver builds a javascript test machine that can be easily integrated into continuous build systems; it allows you to quickly run tests on various browsers to facilitate the development of TDD styles and provides quick test execution, fully controlled DOM, command line control and so on.


Booklaylet is a bookmarklet wrapper code programmed to load any content from another page into an open window using div and iframe layers. Works with Firefox, Safari, and Opera, but doesn’t work with Internet Explorer.


javascriptools is a set of javascript components, functions, and classes in which functions perform basic operations with objects, strings, data arrays, form fields, and so on. The set has a dynamic table that supports paging files, sorting and editing them and is fully customizable with CSS.


liteAJAX is proof of the concept of lightweight AJAX classes.


JSPDF is a library for generating PDF documentation using javascript and open source. It can be used in extensions of Firefox, the server side of javascript with URL data in some browsers.


Narwhal is a cross-platform, multi-interpretation javascript development environment that builds javascript applications and frameworks such as Nitro. Includes a package manager, a module system and a standard library for several javascript interpreters.

Useful javascript libraries and other tools


Tablecloth is an easy and unobtrusive way to add style and style to your html element tables. It has the function of assigning even / odd class names to alternative lines, adds class names for mouse position above and outside a specific area.


Moousture is a javascript-only mouse movement library with the ability and flexibility to minimize for you. The library is written in Mootools, which follows object-oriented standards. Its goal is to begin work on the future structure of mouse movements in any browser, including modern mobile devices.


jQuery Tools is a collection of the most important user interface components for modern sites, where all the tools can be used together, expanding, configuring and utilizing. It is used by large sites around the world.


Tipimage is used to create and manage tooltips over images, creates square parts of images, and attaches to each description, which is shown as a cloud of tips. Also supports the use of a special callback function.


qGallery is a small command line program that processes jpeg images and specially renames files in some folder structures to form a static HTML gallery for publications, automatically creates image indexes for previews, comments for each image, and additional images and HTML can be added later.


LivePipe UI is a set of high-quality widgets and controls for WEB 2.0 applications using the Prototype javascript Framework, where each control is well tested, fully open, documented and flexibly replaced with a more simplified option in browsers without javascript enabled.


javascript Virtual keyboard is a reusable system for adding a graphical keyboard interface to test fields, password fields and text fields. It also provides easy access to special characters.


Unobtrusive Table Actions Script can strip the table, supports moving the cursor over the horizontal and vertical menu bar and effects for moving the cursor over individual cells can work with rowSpans and ColSpans, and also works quickly in Internet Explorer.


Glassbox is a lightweight javascript user interface that uses Prototype and Script.aculo.us to achieve some effects. GlassBox allows you to easily build bright glowing frames, color schemes, and Flash-like effects.

Glimmer is an interactive design tool or Windows application that can easily create animations and a sense of interaction, as well as other effects. It also generates jQuery, XHTML and CSS.


Bookmarklets are used to perform useful functions. Bookmarklet allows you to create URLs from javascript and add it to your Favorites. Enter your javascript code and Bookmarklets will do the rest.


the javascript Regex Generator generates the correct relative to the base expressions, in which you should only enter data for testing and mark the parts that the Regex should compare. The beta version of the tool allows you to add seven groups.


Compatibility Master Table contains links to individual tables. It also has keys for compatibility tables, which determine whether it is fully supported, with difficulty, or not at all.

It's no secret that nowadays Javascript has become one of the most popular programming languages. In the distant 90s, at the time of the emergence of the language, when it was created with the sole purpose of adding interactivity to web pages and improving the process of interacting with the user, who would have thought that he would reach such unprecedented heights. After all, now you can do almost anything on it. Want to write a website: both a backend and a frontend in JavaScript? you are welcome! Want to write a mobile app in JavaScript? no problems. Program the microcontroller - and JavaScript will come to your aid.

Of course, there are small disadvantages in the approach of using JavaScript everywhere, but if you think about it, then how much time and effort can be saved by learning only one language, especially if the same application should work on different platforms. Speak different platforms? Hmm ... Exactly - on different platforms - now JS can afford desktop applications for Windows, Linux, Mac, as you ask? The answer is simple: meet - Nw.js.

Node.js - A software platform based on the V8 engine that translates our script into machine code. This platform was created in 2009 mainly for working with the backend sites.

Webkit - A free engine developed by Apple. It was first announced as part of Safari in 2003.
So, the code written in JS for this technology will have access to both Node.js modules and a standard browser API (respectively WebKit)

Fast start

All this is certainly good, but where do you start? On github, you can find and download the source repository. Here you can also find direct download links for the platform on which development will be conducted. Among other things, we need installed node.js.

After the necessary software has been downloaded and installed, you wrote your application on your favorite JS (see below for how to do this) and localized everything in one folder. Half the job is done, now the most difficult and long thing remains - to pack everything into one file and prepare for distribution. For simplification, you can use ready-made libraries, for example nw-builder. Installing the library will not be difficult if you have already worked with node.js. As you know, node.js includes npm package managerwhich you need to work from the command line. In order to put any library, you need to run the command:

\u003e npm install [library_name] [options]
Please note that the library can be installed both locally and globally, for local installation use the option --save-devfor global -g. Thus, we put our collector for NW.js globally by running the command:

\u003e npm install nw-builder -g
In order to build our application, you need to run the command (with a large number of options, see the documentation):

\u003e nwbuild -p [platform_name] -o [path_to_folder_for_assembled_version] [application_path]
The platform name can be the following values: win32, win64, osx32, osx64, linux32, linux64.

During development, there is no need to build the application every time, you can just launch it as it is and it will open in a separate window. To do this, run the nw.exe application from the command line and pass the path to the folder with your application as parameters. In addition, if you are working under Windows, you can simply drag and drop the folder with the application source code onto JS using the drag-n-drop method (note that it is the entire folder) in nw.exe.

Hello world!

Now that you know how to run the application, how to assemble it into a single file, let's write something. By tradition, the introduction to the new platform begins with the writing of the Hello, world application.

For this application, we do not even need Javascriptonly HTML. Create a folder with the name HelloWorld. Put the file inside index.html with the following markup:

Hello world

Hello, world, from NW.js

In addition, for each application under NW.js, a file is required, which must be called package.json. Information will be taken from it to build the application. Create the simplest version of the file and put it in the folder HelloWorld. So:

("name": "hello-world", "version": "1.0.0", "description": "First application", "main": "index.html", "author": "Developer", "window ": (" toolbar ": false," width ": 500," height ": 200))
The contents of the file are clear without explanation (note that required fields are only main and name) AT main you need to write a markup file, which will be the entry point to the application. Section window adjusts the window parameters (in this case, we turn off the toolbar and set the window size to 500x200).

In addition, you can configure fields such as (for a complete list of options, refer to the documentation):

  • icon - specify the path to the icon (override the standard)
  • position - you can specify the position of the window at boot ( null, center or mouse)
  • min_width, min_height, max_width, max_height - window size limitation
  • resizable - a logical value that indicates whether the user can resize the window
  • fullscreen - Enable full-screen mode
  • kiosk - enable kiosk mode
  • transparent - make the window transparent
The application is created and you can run it. After starting (for how to do this, see the section above), you should get the following window:

The application is written, but there is only one div element in it and there is absolutely no logic, but what if we have rich markup for elements and complex logic? An element of the configuration file comes to our aid toolbarwhich we set to false. In order to make debugging tools available, you must set toolbar to true. Having done this when starting the application, we get the following window:

After clicking on the button in the upper right corner another window will open in which the familiar developer tools will be displayed:

Work with native controls

NW.js allows you to work with native controls. Consider the example menu. To work with native UI controls in nw.js, you must use the module nw.guiwhich can be connected as follows:

Var gui \u003d require ("nw.gui");
General template for using controls:

Var element \u003d new gui.ElementName (option);
Thus, to create menu items, you can use the following design:

Var menu \u003d new gui.Menu ();
In addition, any properties of the object we created can be easily changed with standard JS constructs, for example like this:

Menu.title \u003d "(! LANG: New Title"; !}
The menu is created, now you need to fill it in, there are methods for manipulating child elements:

Menu.append (new gui.MenuItem ((label: "Label of menu item"))); menu.removeAt (0);
In addition, for a more flexible addition of elements to the menu, you can use the method insertwhose parameters you want to pass MenuItem and position number where to insert it ( the position before the first element corresponds to 0).

To access the created elements, you can use the property items:

Menu.items.title \u003d "(! LANG: New title" !}
Please note that you cannot directly create elements:

Menu.items \u003d new gui.MenuItem (); // WRONG
The most important thing when working with native controls is to remember that any error when working with them can lead to the collapse of the entire application, therefore, it is necessary to be extremely careful and whenever possible when deleting elements, also set the variable to null. In this way to remove control, you can do the following:

Control.remove (); control \u003d null;
For more convenient work with controls, they are inherited from EventEmitter, so the good news is that we can easily work with events, for example like this:

Menuitem.on ("click", function () (// do something useful));
A menu has been created, but if you run the application, you will not see any menu. To display the menu, there is a popup method, in the parameters of which it is necessary to transfer the coordinates for displaying the menu.

To demonstrate the main features of the menu, add the following script to the previously created project Hello world:

Var gui \u003d require ("nw.gui"); var menu1 \u003d new gui.Menu (); menu1.append (new gui.MenuItem ((label: "Item 1"))); var subMenu1 \u003d new gui.Menu (); subMenu1.append (new gui.MenuItem ((label: "Item 2"))); menu1.append (new gui.MenuItem ((label: "Submenu", submenu: subMenu1))); document.body.addEventListener ("contextmenu", function (ev) (ev.preventDefault (); menu1.popup (ev.x, ev.y); return false;));
After starting the application, we can see the created context menu for the body. Thus, we can define a context menu for any item.

Add tags