Javascript programming training. JavaScript for Beginners - Simple Examples

By popular demand, we are launching a series JavaScript lessons... If you are determined to master JS, it means that you have a basic knowledge of HTML and CSS, since this is the foundation, without which it is difficult to understand what will be discussed.

From our side, I will try to explain in understandable language, to show with real examples from life, because everything is learned in comparison.

What is JavaScript, or how to understand for what purpose it is needed in web development!

We live in a world where everything is tangible, we implement the ideas that come to our heads. We build houses, cars, move around using various equipment. That is, what we can do in the real world can be imagined in comparison with HTML, where it acts as a building material, a foundation on which everything rests, and when CSS help we decorate this world, make it colorful, the way we would like to see it ourselves.

You are probably wondering if HTML and CSS are what surrounds us, so what is JavaScript? Where it manifests itself in our world.

I think it will be easier to explain using the example of the film by Gary Potter, I think many of you have watched it and will understand what will be discussed. According to the script of the film, we know that Gary possessed super powers, he was a wizard, and a magic wand helped him in this. It was the magic wand that gave him the opportunity to create magic, of such a level as he possessed knowledge, to make it unique.

JavaScript is a magic wand, which every web developer has, but what kind of magic you can create with it depends only on the developer's knowledge that he possesses. Those who have mastered given language, are magicians and work miracles in truth.


JavaScript language not complete without its HTML and CSS components. Many programmers mention three languages ​​that make up the "layers" of a web page: HTML, CSS, and JavaScript.

Html first hypertext markup language - provides structural layers expressively organizing page content, such as text, images, and other elements.

Second, CSS(Cascading Style Sheets), form beautiful design, the look and feel of HTML content.

And the third - JavaScript–Adds behavioral layers, animating the web page, making it interactive, that is, creating elements to interact with visitors.


In summary, to master the JavaScript language, you must have a good understanding of both HTML and CSS.

Programming can seem like incredible magic beyond the reach of mere mortals. However, most of his concepts are not difficult to understand. JavaScript is quite friendly to beginner programmers, but nevertheless, it is more complex than HTML or CSS, so in this series of lessons we will master the fundamental concepts of programming, so that you can apply them when writing scripts in JavaScript.

You will get acquainted with the new symbols (),,; , (),!, we will learn the designation of new words (var, null, else if), we will analyze the punctuation rules and the syntax of the language itself, and all this in order to work our magic.

The material was prepared by Denis Gorelov, write your comments and be sure to share this material with your friends.

  • Translation

The material, the translation of which we publish today, is devoted to the basics of JavaScript and is intended for novice programmers. It can also be thought of as a small reference to basic JS constructs. Here, in particular, we will talk about the data type system, about variables, about arrays, about functions, about object prototypes, and some other features of the language.

Primitive data types

JavaScript provides the following primitive data types: number, boolean, string, undefined, null. It should be noted right away that when working with primitive data types, for example, with string literals, we will be able to access their methods and properties without even performing an explicit conversion. The point here is that when trying to perform such operations, literals are automatically equipped with the appropriate object wrapper.

▍Numbers

There is only one type of number in JavaScript - double precision floating point numbers. This leads to the fact that the results of evaluating some expressions are arithmetically incorrect. You may already know that in JS the value of the expression 0.1 + 0.2 is not equal to 0.3. At the same time, when working with integers, such problems are not observed, that is, 1 + 2 === 3.

JavaScript has a Number object, which is an object wrapper for numeric values. Number objects can be created either using a command like var a = new Number (10), or you can rely on the automatic system behavior described above. This, in particular, allows the methods stored in Number.prototype to be invoked on numeric literals:

(123) .toString (); // "123" (1.23) .toFixed (1); //"1.2 "
There are global functions for converting values ​​of other types to numeric types. These are parseInt (), parseFloat () and the Number () construction, which in this case acts as a regular function that performs type conversion:

ParseInt ("1") // 1 parseInt ("text") // NaN parseFloat ("1.234") //1.234 Number ("1") // 1 Number ("1.234") //1.234
If in the course of an operation with numbers something is obtained that is not a number (in the course of some calculations, or when trying to convert something to a number), JavaScript will not throw an error, but will represent the result of such an operation as a value NaN (Not-a-Number, not a number). To check if a certain value is NaN, you can use the isNaN () function.

Arithmetic operations JS works in a fairly familiar way, but note that the + operator can perform both number addition and string concatenation.

1 + 1 //2 "1" + "1" //"11" 1 + "1" //"11"

▍Strings

Strings in JavaScript are sequences of Unicode characters. String literals are created by enclosing the text to be enclosed in double ("") or single ("") quotation marks. As already mentioned, when working with string literals, we can rely on the corresponding object wrapper, the prototype of which has many useful methods, including substring (), indexOf (), concat ().

"text" .substring (1,3) // ex "text" .indexOf ("x") // 2 "text" .concat ("end") // text end
Strings, like other primitive values, are immutable. For example, the concat () method does not modify an existing string, but creates a new one.

▍ Boolean values

Boolean data type in JS is represented by two values ​​- true and false. The language can automatically convert various values ​​to boolean data types. So, false, in addition to the boolean value false, are the values ​​null, undefined, "" (empty string), 0, and NaN. Everything else, including any objects, is the true value. In progress logical operations everything that is considered true is converted to true, and everything that is considered false is converted to false. Take a look at the following example. In accordance with the above principles, an empty string will be converted to false, and as a result of executing this code, the line This is false will be sent to the console.

Let text = ""; if (text) (console.log ("This is true");) else (console.log ("This is false");)

Objects

Objects are dynamic structures made up of key-value pairs. Values ​​can be of primitive data types, can be objects or functions.

Objects are easiest to create using the object literal syntax:

Let obj = (message: "A message", doSomething: function () ())
Object properties can be read, added, edited and deleted at any time. Here's how to do it:

  • Reading properties: object.name, object.
  • Writing data to properties (if the property being accessed does not exist, add a new property with the specified key): object.name = value, object = value.
  • Deleting properties: delete object.name, delete object.
Here are some examples:

Let obj = (); // create an empty object obj.message = "A message"; // add a new property obj.message = "A new message"; // edit the property delete object.message; // remove property
Objects in the language are implemented as hash tables. A simple hash table can be created using the Object.create (null) command:

Let french = Object.create (null); french ["yes"] = "oui"; french ["no"] = "non"; french ["yes"]; // "oui"
If you want to make an object immutable, you can use the Object.freeze () command.

To iterate over all the properties of an object, you can use the Object.keys () command:

Function logProperty (name) (console.log (name); // property name console.log (obj); // property value) Object.keys (obj) .forEach (logProperty);

▍Comparing values ​​of primitive types and objects

At practical work with primitive values, as already mentioned, you can perceive them as objects that have properties and methods, although they are not objects. Primitive values ​​are immutable; the internal structure of objects can change.

Variables

In JavaScript, variables can be declared using the var, let, and const keywords.

When using the var keyword, you can declare a variable and, if necessary, initialize it with some value. If a variable is not initialized, its value is undefined. Variables declared using the var keyword have functional scope.

The let keyword is very similar to var, the difference is that variables declared with the let keyword are block-scoped.

Variables declared using the const keyword also have block scope, which, given that the values ​​of such variables cannot be changed, it would be more correct to call them "constants". The const keyword, which "freezes" the value of a variable declared using it, can be compared to the Object.freeze () method that "freezes" objects.

If a variable is declared outside of any function, its scope is global.

Arrays

JavaScript arrays are implemented using objects. As a result, when we talk about arrays, we are, in fact, discussing objects that look like arrays. You can work with array elements using their indices. Numeric indices are converted to strings and used as names to access the values ​​of array elements. For example, a construct like arr is similar to a construct like arr ["1"], and both will give access to the same value: arr === arr ["1"]. According to the above, a simple array declared with the let arr = ["A", "B", "C"] command is represented as an object similar to the following:

("0": "A", "1": "B", "2": "C")
Deleting array elements using the delete command leaves "holes" in it. In order to avoid this problem, you can use the splice () command, but it works slowly, because, after removing an element, it moves the remaining elements of the array, in fact, shifting them to the beginning of the array, to the left.

Let arr = ["A", "B", "C"]; delete arr; console.log (arr); // ["A", empty, "C"] console.log (arr.length); // 3
Array methods make it easy to implement data structures such as stacks and queues:

// stack let stack =; stack.push (1); // stack.push (2); // let last = stack.pop (); // console.log (last); // 2 // queue let queue =; queue.push (1); // queue.push (2); // let first = queue.shift (); // console.log (first); // 1

Functions

Functions in JavaScript are objects. Functions can be assigned to variables, stored in objects or arrays, passed as arguments to other functions, and returned from other functions.

There are three ways to declare functions:

  • Classic function declaration (Function Declaration or Function Statement).
  • Using Function Expressions, also called Function Literals.
  • Using Arrow Function syntax.

▍Classic function declaration

With this approach to declaring functions, the following rules apply:
  • The first keyword on the line of a function declaration is function.
  • The function must be assigned a name.
  • A function can be used in code prior to its declaration by raising the function declaration to the top of the scope in which it is declared.
This is what a classic function declaration looks like:

Function doSomething () ()

▍Functional Expressions

Consider the following when using functional expressions:
  • The function keyword is no longer the first word in the function declaration line.
  • The function name is optional. Both anonymous and named functional expressions can be used.
  • The commands for calling such functions must follow the commands for their declaration.
  • Such a function can be invoked immediately after the declaration using the IIFE (Immediately Invoked Function Expression) syntax.
The functional expression looks like this:

Let doSomething = function () ()

▍Arrow functions

Arrow functions are essentially "syntactic sugar" for creating anonymous function expressions. It should be noted that such functions do not have their own this and arguments entities. An arrow function declaration looks like this:

Let doSomething = () => ();

▍Ways to call functions

Functions can be called in a variety of ways.

Normal function call

doSomething (arguments)

Calling a function as an object method

theObject.doSomething (arguments) theObject ["doSomething"] (arguments)

Calling a function as a constructor

new doSomething (arguments)

Calling a function using the apply () method

doSomething.apply (theObject,) doSomething.call (theObject, arguments)

Calling a function using the bind () method

let doSomethingWithObject = doSomething.bind (theObject); doSomethingWithObject ();
Functions can be called with more or fewer arguments than the number of parameters that were specified when they were declared. During the operation of the function, the "extra" arguments will be simply ignored (although the function will have access to them), the missing parameters will receive the value undefined.

Functions have two pseudo-parameters: this and arguments.

▍The this keyword

The this keyword represents the context of the function. The value it points to depends on how the function was called. Here are the meanings of the this keyword, depending on the method of calling the function (they, with code examples, the constructions of which are used here, are described above):
  • A common function call is window / undefined.
  • Calling the function as a method of the object - theObject.
  • A function call as a constructor is a new object.
  • Calling a function using the apply () method - theObject.
  • Calling a function using the bind () method - theObject.

▍The arguments keyword

The arguments keyword is a pseudo parameter that gives access to all the arguments used in the function call. It looks like an array, but it is not an array. In particular, it has no array methods.

Function reduceToSum (total, value) (return total + value;) function sum () (let args = Array.prototype.slice.call (arguments); return args.reduce (reduceToSum, 0);) sum (1,2, 3);
An alternative to the arguments keyword is the new syntax for the remaining parameters. In the following example, args is an array containing everything that is passed to the function when called.

Function sum (... args) (return args.reduce (reduceToSum, 0);)

▍The return statement

A function without a return statement will return undefined. When using the return keyword, pay attention to how the automatic semicolon insertion mechanism works. For example, the following function will return not an empty object, but the value undefined:

Function getObject () (return ()) getObject ()
To avoid this problem, place the opening curly brace on the same line as the return statement:

Function getObject () (return ())

Dynamic typing

JavaScript is a dynamically typed language. This means that concrete values ​​have types, but variables do not. During program execution, values ​​can be written to the same variable different types... Here's an example of a function that works with values ​​of different types:

Function log (value) (console.log (value);) log (1); log ("text"); log ((message: "text"));
To find out the type of data stored in a variable, you can use the typeof () operator:

Let n = 1; typeof (n); // number let s = "text"; typeof (s); // string let fn = function () (); typeof (fn); // function

Single-threaded execution model

The JavaScript runtime is single-threaded. This, in particular, is expressed in the impossibility of simultaneously executing two functions (if you do not take into account the possibilities of asynchronous code execution, which we do not touch upon here). The runtime has a so-called Event Queue, which stores a list of jobs to be processed. As a result, the single-threaded JS execution scheme does not have the problem of resource deadlocks, so there is no need for a locking mechanism. However, code that ends up in the event queue needs to execute quickly. If you overload the main thread with hard work in a browser application, the application page will not respond to user input and the browser will offer to close this page.

Exception Handling

JavaScript has a mechanism for handling exceptions. It works according to the principle that is quite usual for such mechanisms: the code that can cause an error is drawn up using the try / catch construction. The code itself is in a try block, errors are handled in a catch block.

It is interesting to note that sometimes JavaScript does not issue error messages when an abnormal situation occurs. This is due to the fact that JS did not throw errors prior to the adoption of the ECMAScript 3 standard.

For example, in the following code snippet, an attempt to modify a frozen object will fail, but no exception will be thrown.

Let obj = Object.freeze (()); obj.message = "text";
Some of the "silent" JS bugs manifest in strict mode, you can enable it using the "use strict" construct; ...

Prototype system

JS mechanisms such as constructor functions, the Object.create () command, and the class keyword are based on the prototype system.
Consider the following example:

Let service = (doSomething: function () ()) let specializedService = Object.create (service); console.log (specializedService .__ proto__ === service); // true
Here, the Object.create () command was used to create the specializedService object, the prototype of which was to be the service object. As a result, it turns out that the doSomething () method can be called by accessing the specializedService object. It also means that the __proto__ property of the specializedService object points to the service object.

Let's now create a similar object using the class keyword:

Class Service (doSomething () ()) class SpecializedService extends Service () let specializedService = new SpecializedService (); console.log (specializedService .__ proto__ === SpecializedService.prototype);
The methods declared in the Service class will be added to the Service.prototype object. Instances of the Service class will have the same prototype (Service.prototype). All instances will delegate method calls to the Service.prototype object. As a result, it turns out that methods are declared only once, in Service.prototype, after which they are "inherited" by all instances of the class.

▍ Prototype Chain

Objects can be "inheritors" of other objects. Each object has a prototype, the methods of which are available to it. If you try to access a property that is not in the object itself, JavaScript will start looking for it in the prototype chain. This process will continue until the property is found, or until the search reaches the end of the chain.

About functional programming in JavaScript

V JavaScript functions are objects of the first class, the language supports the mechanism of closures. This paves the way for implementing functional programming techniques in JS. In particular, we are talking about the possibility of using higher-order functions.

A closure is an internal function that has access to variables declared inside the parent function, even after the parent function has executed.

A higher-order function is a function that can take other functions as arguments, return functions, or both.

Functional programming in JS has been covered in numerous publications. If you are interested - here are some materials on this topic dedicated to

JavaScript syntax tutorial

Before you start reading JavaScript language tutorial you must have knowledge of.

It will be a big plus in learning JavaScript syntax if you are already familiar with a programming language such as PHP, C or Pascal, and also understand what a variable, data type, function, or array is.

However, if you are not familiar with programming languages, then you should not worry, given JavaScript tutorial just designed for those who are starting to learn programming for the first time.

JavaScript (JavaScript) Is a client-side programming language with which you can control elements of an HTML page (HTML tags) and a web browser, make them move, respond to various events (mouse clicks, keystrokes), create many interesting programs (scripts): tests, animations, photo galleries (for example, as in Vkontakte), games and much more.

How JavaScript is learned

The study JavaScript language is usually divided into four stages:
1. Mastering JavaScript syntax (this tutorial),
2. Study DOM and BOM,
3. Managing the DOM and BOM using JavaScript,
4. Learning various JavaScript libraries. jQuery- the most popular on this moment library (jQuery tutorial should appear on this site in late 2015).

The DOM is the Document Object Model. Thanks to DOM technology, HTML page tags begin to represent a tree of objects, and each object in this tree has its own unique address. The JavaScript language, referring to this address, can access this or that HTML tag and control it (change color, size, position, etc.).

BOM is a browser-based document model. The structure is the same as that of the DOM, only instead of HTML page objects, there are browser objects: browser window, browser screen sizes, visit history, status bar, etc.

After studying the DOM and BOM, they start creating more or less complex JavaScript scripts that interact with the page and the browser.

Then, with a little bit of familiarity, they learn some JavaScript library, for example jQuery, thanks to it, you can create the same programs as in JavaScript, only much faster and more efficiently.

Some webmasters start learning jQuery right away, skipping the previous three steps, but I do not recommend doing this, because in any case you need to understand JavaScript syntax and know DOM / BOM objects, their properties, methods and purposes.

What programs can be written using JavaScript

With the help you can create many interesting programs (scripts):
- you can create scripts that will change the elements of the site page or their location by clicking on this or that button,
- you can create animation,
- manipulate forms, for example, check the data entered by the user for correctness,
- create various tests, for example, the type of exam (school exams) and immediately get the result,
- thanks to the BOM, you can find out the characteristics of the browser and the computer of the user who visited your site, which allows you to create various visit counters,
- using JavaScript, you can even create games, cartoons and many other interesting and useful programs.

What is the purpose of this JavaScript tutorial?

The purpose of this JavaScript books is to educate you JavaScript syntax basics, introduce programming and concepts such as variables, data types, operations, branch operators, functions, loops, arrays, objects, etc. All this is found in other programming languages, so once you have mastered JavaScript, it will be much easier for you to learn other languages, such as PHP, C ++ or Python.

JavaScript tutorial structure

V JavaScript tutorial, the following topics and lessons will be covered.

JavaScript - comes into play when we need to perform some action on the client side that accessed our web page.

JavaScript can modify a web page without contacting the server, validate user input values, and perform any other operation.

This article has put together the basics to get you started using JavaScript.

Inserting a script directly into the page code

You can insert JS code right inside the page.

Removing the code into a separate file

Can be taken out JavaScript code to an external file and use a link to it on the page

The closing tag is required in this case.

It is best to insert scripts before the closing tag

Variables

Variable names

Variable names can begin with an uppercase or lowercase letter, an underscore, or the $ sign.

The name can contain numbers, but you cannot start the name of a variable with a number.

JavaScript is case sensitive: mytext and myText are two different variables.

Better to use CamelCase for naming, capitalizing each word in the variable name.

Declaring Variables

To declare variables in Javascript, use var.

Var myText; // undefined myText = "Hi!"; alert (myText);

Immediately after declaring a variable, its value is undefined.

You can assign a value to a variable when declaring:

Var myText = "Hi!";

You can also declare multiple variables in one var:

Var sum = 4 + 5, myText = "Hi!";

You can omit var when assigning a value, but it is best not to.

Variable types

In JavaScript you can use strings:

Var myText = "Hello!";

whole numbers:

Var myNumber = 10;

Fractional numbers:

var pi = 3.14;

Boolean values:

Var isBoolean = false;

JavaScript syntax details

Comments (1)

Comments on one line are highlighted with "//". Anything after these characters is considered a comment.

To comment out multiple lines, use "/ *" to mark the start of a comment and "* /" to mark the end of a comment

/ * here is commented code and it "s also comment * /

Separating Operators

To separate operators you need to use ";"

It is advisable, but not required, to use spaces to improve the readability of the text.

Working with strings

var str = 4 + 5 + "7"

will give a string value " 97 »To str

Var str2 = "7" + 4 + 5

will give a string value " 745 "In str2

The fact is that the value during addition is calculated sequentially - from left to right. When 2 numbers are added, the result is a number. When a string and a number are added, the number is treated as a string and the two strings are concatenated.

Converting a string to a number

To convert a string to a number, use parseInt () and parseFloat ()

These functions take two arguments. The first is the string that will be translated into a number and the second is the radix that will be used for translation. To interpret a string as decimal, you need to use 10 as the second argument

Var myNumber = parseInt ("345", 10);

JavaScript functions

Functions in JavaScript are declared like this:

Function myFunction () (Some JS code)

To return a value, use return:

Function myMultiplication (paramOne, paramTwo) (return paramOne * paramTwo)

You can declare an "anonymous" function by omitting the name for the function.

A function can be passed as a parameter to another function by specifying its name.

Objects

Everything in JavaScript inherits from Object.

Creating a new object

var person = new Object (); // create a person object person.firstname = "Andrew"; // add the first attribute person.lastname = "Peterson"; // add the second attribute person.getFullName = function () (// add the method return this.firstname + "" + this.lastname;)

The second, more concise option for creating an object

Var person = (// create a person object firstname: "Andrew", lastname: "Peterson", getFullName: function () (return this.firstname + "" + this.lastname;))

Working with object properties

var me = new Object ();

me ["name"] = "Serg";
me.age = 33;

Arrays in JavaScript

Array creation

var arr = new Array (11, "Hello!", true); // Create an array

New way of recording

Var arr =; // Create an array

Working with arrays in JavaScript

The number of elements in the array

var length = arr.length; // 3

Adding elements to an array - push

arr.push ("A new value");

Retrieving the last element of an array - pop

var lastValue = arr.pop ();

Combining arrays

var arr2 =; var longArray = arr.concat (arr2); // Concatenate two arrays arr and arr2 into one longArray

Join - merge all elements of an array

var longString = arr.join (":") // "11: Hello!: true"

Comparison and Boolean Functions in JavaScript

More less

var isTrue = 6> = 5; // more or equal

Equality

var isFalse = 1 == 2; // equals isTrue = 1! = 2; // not equal var alsoTrue = "6" == 6;

Identity

var notIdentical = "3" === 3 // false because the data types do not match notIdentical = "3"! == 3 // true because the data types do not match

IF statement

if (5< 6) { alert("true!"); } else { alert("false!") }

SWITCH statement

var lunch = prompt ("What do you want for lunch?", "Type your lunch choice here"); switch (lunch) (case "sandwich": console.log ("Sure thing! One sandwich, coming up."); break; case "soup": console.log ("Got it! Tomato" s my favorite. ") ; break; case "salad": console.log ("Sounds good! How about a caesar salad?"); break; case "pie": console.log ("Pie" s not a meal! "); break; default : console.log ("Huh! I" m not sure what "+ lunch +" is. How does a sandwich sound? ");)

Logical AND - &&

if (1 == 1 && 2 == 2) (alert ("true!");)

Logical OR - ||

if (1 == 1 || 2 == 3) (alert ("true!");)

Logical NOT -!

if (! (1 == 1)) (alert ("false!");)

Cycles

FOR

for (var i = 0; i< 10; i = i + 1) { alert(i); } var names = [ "Sergey", "Andrey", "Petr" ]; for (var i = 0, len = names.length; i < len; i = i + 1) { alert(names[i]); }

WHILE

while (true) (// Endless loop alert ("This will never stop!");) var names = ["Sergey", "Andrey", "Petr"]; while (names.length> 0) (alert (names [i]);)

DO WHILE

do (alert ("This will never stop!");) while (true) (// Endless loop

Strings

text = "Blah blah blah blah blah blah Eric \ blah blah blah Eric blah blah Eric blah blah \ blah blah blah blah blah Eric";

Substrings

Sometimes you don’t want to display the entire string, just a part of it. For example, in your Gmail inbox, you can set it to display the first 50 or so characters of each message so you can preview them. This preview is a substring of the original string (the entire message).

"some word" .substring (x, y) where x is where you start chopping and y is where you finish chopping the original string.

The number part is a little strange. To select for the "he" in "hello", you would write this: "hello". substring (0, 2);

Think of there being a marker to the left of each character, like this: 0-h-1-e-2-l-3-l-4-o-5.

If you chop at 0 and again at 2 you are left with just he.

More examples:

1. First 3 letters of "Batman"
"Batman" .substring (0,3)

2. From 4th to 6th letter of "laptop"
"laptop" .substring (3.6)

  • How to insert a script into an HTML document (general information);
  • JavaScript comments
  • how to declare variables and give them the correct names;
  • parsing the script and syntax of methods;
  • alert () method;
  • useful little thing: a "stub" for a temporarily broken link

From the author

There are many different subtleties in creating web pages. But there are also three whales. These are HTML, CSS and JavaScript.

I recommend organizing self-education as follows: as soon as you master the HTML syntax and learn how to make primitive pages with text, pictures and tables, immediately join the study of CSS. Once you understand how to work with CSS, start mastering JavaScript while expanding your "vocabulary" in all three languages. I think that in six months you will be able to build a very beautiful and functional website.

For a long time I didn't know how to get started with JavaScript. You came across textbooks that were either too abstract - theory, theory, and it was not clear how to apply it to practice, or, on the contrary, too specific: here's a set of ready-made recipes, take it and use it, but how it all turns is not your little mind.

Once I came across a textbook by Vadim Dunaev. Many, I know, scold this tutorial. In addition, I downloaded a disgusting scanned PDF, where instead of "()" there could be, for example, "Q", and the Latin letters in the codes were replaced (in places!) With similar Russian ones, which is why these codes do not work. In general, I had to pant. And, to be honest, if I had not read anything about JavaScript before, I would not have figured out these errors and would have joined the number of scolders. But then I was out of work, there was time to delve into it, and I liked the textbook. But it is very detailed and is designed for people who have already come into contact with programming.

Note 2012

Now, after a few years, I treat this textbook without the former enthusiasm. It is outdated, "sharpened" for IE, rather superficial; there are real errors and inaccuracies in the code, and some useful things are not found. But compared to those "tyap-blooper-guides" that search engines gave out in abundance, it was something.

So, I want to try to kill two birds with one stone. Write something that is understandable for any teapot and at the same time constructive and cognitive. So that this teapot, based on my advice, could write a simple, but completely original script.

Insert into HTML document

You've probably seen tags like this in HTML codes:

This gibberish between the tags is the script.

The tag itself

This attribute is optional. It should be used either to clarify the language version (javascript1.1, javascript1.2, etc.), or if you use another language (for example,

The type attribute, which indicates the type of text: text / javascript... It appeared in HTML 4.0. This is what I recommend to use.

Before moving on to the attribute src, let's find out in which sections of the HTML code you can insert scripts.

Any. But wisely.

Often the script specifies the output of specific text, as they say, here and now. Such a script is inserted directly into , "To the scene."

There are scripts with variable declarations that can be used in other scripts on the page, with functions that can be called from anywhere in the HTML code. It is most reasonable to place such scripts between tags. and .

But you can also do so to use the script on several web pages at once. To do this, its code must be written into a separate file with the extension .js(for example, myscript_1.js). Tags you no longer need to write in it.

And then, to call a script from a web page, we need the attribute src... It works in the same way as the corresponding tag attribute. :

This is how the same header or menu, written in the script file, is placed on different pages. This is especially helpful on those hosting services where SSI does not work.

You can also insert small scripts into some of the attributes of HTML tags, but more on that later.

Sometimes the script needs to be placed at the very end body or even after closing : for example, if we need the script to examine all links or all pictures in the document before executing. But more on that later, when we figure out how JavaScript works. You can peep.

Comments (1)

They say there are still browsers that do not understand scripts. There are also maniac users who are so pushed aside on security that they disable scripts. In this situation, the script will not be executed, but its code, the same "gibberish", will simply fall out on the screen.

So, so that it doesn't fall out, we enclose it in HTML comments.

Mmm ... what are those two slashes before closing a comment?

The closing comment is already in the "body" of the script. And JavaScript does not understand these clumsy HTML "brackets, for it this is a foreign body that generates an error. So, you need to hide this closing tag from the script, placing it as a JavaScript comment. In JavaScript, comments look a little more elegant: //. After this sign, the script does not see the closing brace of HTML, and HTML safely hides the script text, and no "left" entries are visible on the screen.

Since we have touched on comments, I must say that in JavaScript they have two forms - the same as in C and C ++ (and by the way, in CSS too).

// This form of comment // acts on only one line, // that is, on each new line // you need to put a comment mark. And this is the script code ... / * And this form of comment acts on as many lines as you like until it hits a closing icon that mirrors the starting one. * / And now again the script code ...

Don't confuse HTML comments and JavaScript comments! These are different languages, although they coexist “in one bottle”. Or, more precisely, in one bank. Like spiders ...

Let's get back to the issue of legacy browsers. For example, with the help of JavaScript you have made something like an animated banner out of two pictures. Then you can please users of "poor" browsers (and you, I hope, are not completely devoid of altruism) by seeing at least one of these pictures using the tag

In which editors to write scripts

Perhaps there are some special editors for JavaScript. I haven’t met such people and I haven’t looked for them too much. Typically, scripts are written in the same editors that are used to create web pages. For example, I love HomeSite. Writing a script in these editors is no different from writing it in a simple notepad, except for highlighting the code. And she sometimes helps a lot. Once I downloaded a script (from some German), but it does not work. I looked closely at the code and saw that the keyword switch for some reason it is not highlighted. I look - and there is no switch, a switsch, Donner, Wetter! I removed the letter - and off we go.

By the way, in all our examples, the code looks exactly like in the HomeSite window.

Right off the bat

The next example is plagiarism from Dunaev. But it is so simple and deep that I cannot resist. I have added here only a few details of the design of the recording, in order to explain them at the same time.

I warn you right away: this example is practically completely useless. But it concentrates many of the key concepts of the javascript language and its syntax.

Example 1

The script itself

If you copy this code into a blank Notepad page and save it as an .html file, you will see the following when you open the file:

Let's see how it comes out.

var x = 5;

Here we are declaring a variable x which is 5.

Stop! Do you know what a variable is?

If not, then click this and read the explanation.

How does a computer work? All data is stored on disk, and the place where it lies must be marked so that it is clear where to look for what. Any program (and a script is nothing more than a small program) works with some data. Therefore, it is convenient to immediately "fill in the place" for them. By this place, by this tagged memory and becomes a variable. Why "variable"? Because this area can be filled with different values. For example, when we work with a calculator, the numbers and actions with them that we enter are written by the program into the corresponding variables. And when you click the execute button, the algorithm takes over, using the values ​​that we entered.

In the program code, variables are denoted by names that we ourselves invent for them. There are certain rules for creating names, which may differ in different programming languages. The limitations that will be described below are specific to the JavaScript language.

var- a keyword for declaring a variable (variable in English).

x is the name of the variable.

Restrictions: Only Latin letters (of any case), numbers and underscore can be used in a variable name. In this case, the variable should not begin with numbers. And no spaces.

Correct variable names:

Invalid variable names:

JavaScript is case sensitive.

myvar, MyVar and myVar- different variables.

(By the way, about case. The name of the language itself is spelled with large J and S: JavaScript. There is a misconception that this is the way to write this word in HTML tags. But HTML is not case sensitive, so you can write there as you please. I'm used to small, like my favorite HomeSite, some big.)

In this script, the variable is assigned a value immediately upon declaration. It's not obligatory. The value can be assigned later. There is a semicolon at the end of the line. This is also not necessary in this case. But in large and complex scripts, this sometimes turns out to be important, so I show the full verbose entry. Dunaev's line looks simple x = 5, explicit declaration var not necessary here either. But (IMHO) it is still desirable.

In the next line, as you might guess, the variable is declared y... It has been assigned a value relative to the already declared x, 3 more than x.

And then the method is called alert ().

This method displays a dialog box with the message specified in parentheses. This is the syntax of all javascript methods: the name of the method and parentheses with its content.

The content of this method is the value of the y variable, and we will see an eight in the dialog window. Do you understand why?

Useful little thing

Since we got acquainted with the method alert (), then here is its simple and useful application: sometimes some pages of the site have not yet been made, but the links have already been prepared. It can be unpleasant to land on a "404 page". It's also not very pleasant to wait for it to load, and then find out that the section is under construction. I always plug similar links like this:

"javascript: alert (" This page is under construction ");"
> Menu item

By the way, here's another way for you to embed JavaScript code into HTML code. Here it is inserted into the attribute href link tag and is entered through the keyword " javascript:»(With a colon followed by a space: always pay attention to syntactic trivia). Also notice the traditional double quotes of the HTML attribute value and the "nested" single quotes in the text of the script itself.

We will very soon learn about the special "event" attributes of HTML tags, for example, onClick that are specifically designed to inject JavaScript code and do not require a keyword.

So, we learned:

how to declare a script in an HTML document, what forms have JavaScript comments, how to declare variables and give them correct names, and method syntax and specifically the alert () method.

And also learned: