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.
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.
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.
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