Let's learn Javascript. First lesson


JavaScript is primarily a client-side language, typically used for client-side work. With its help, you can develop applications with a wide variety of functionality. This could be: an analogue of a mechanical watch, various animations, graphic effects and more. Nothing prevents you from creating almost the entire web application in JS.

Today it is difficult to overestimate the role of JavaScript on the web. According to w3techs statistics, today over 95% of websites use JS. The remaining 5% are mainly business card sites and one-page websites. The incredible popularity of the language makes it one of the most desirable for learning and profitable in terms of future employment.

Founded in 1995 by Netscape. Initially intended as a scripting language for their Navigator 2 browser. At the beginning, it was called LiveScript. The developers took advantage of the wave of popularity of Java and changed the name to JavaScript. However, to this day they are often confused by novice developers. Many claim that these are the same languages ​​or have minor differences. This is not true at all, JS and Java are completely different languages. The only similarity between them is their names.

Initially, JS did not have most of the functions available today; its capabilities were extremely meager. The main goal was just to add a little interactivity to the page. The developers wanted the results after button clicks to be processed within one page.

As the web developed, along with the release of , JavaScript received carte blanche to actively develop many functions. Today, JS provides many more developer options than ever before.

JavaScript can now be used as a server-side language. Previously, JS was always considered purely as a client-side language that ran exclusively in the user's browser. To work with the server, I had to use something like , . This made it possible to operate requests on the server using JS.

Despite the ability to implement the server side in Node JS, most of the web uses PHP for this. This is not only the result of habit, but also of the lack of need for another language.

In the modern world, there is a boom in development for mobile devices, where JavaScript has found a place. This contributes to increased productivity of mobile gadgets and the widespread use of HTML5. JS allows you to implement a wide variety of features even in mobile applications.

Due to the release of new versions of Windows from 8 and newer, JavaScript began to be used to develop desktop applications for the listed operating systems. In other words, JS has long gone beyond the scope of a web language that is used exclusively by the browser.

Much of what was once called science fiction is now successfully implemented in JavaScript. This is especially clearly visible in the popular area of ​​IoT programming. Thus, JS can be successfully used to develop water programs by all existing smart devices that support the Internet. Today JS is found almost everywhere IT has reached. It is actually a popular and incredibly functional language that plans to continue to evolve.

Even during the emergence of the language, the Netscape and IE browsers created several different implementations of the language. To unify all implementations and restore a common denominator, the ECMAScript standard was developed (ECMA took over the management of standardization). If you see the term ECMAScript anywhere, it is an interchangeable synonym with JavaScript.

Already today, ECMA has developed a couple of standards for JS; they successfully reflect progress in the development of the language itself. Today, ECMAScript 6 version from 2015 is considered current. However, many browsers are still far from fully implementing this standard. It may take several more years to complete its implementation. For this reason, ES5 is often considered to be the standard that is fully supported by modern browsers.

JavaScript is an interpreted language, meaning it is executed through an interpreter. It receives all the necessary instructions from JS and follows them by executing or interpreting the code.

Development Tools

To create code in JS, you just need a text editor and a browser in which you can test the result. One of the simple and functional text editors that I would recommend using is Notepad++. In general, you can use any convenient one.

JavaScript also supports a number of development environments, such as Visual Studio, WebStorm, Netbeans. They help you create code much faster and easier.

Additional courses

On our website you can find additional courses on the JavaScript language. All courses are presented on.

JavaScript Syntax Tutorial

Before you start reading the JavaScript language tutorial, you should have knowledge of .

It will be a big plus in learning JavaScript syntax if you are already familiar with some 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 there is no need to worry; this JavaScript tutorial is intended for those who are starting to learn programming for the first time.

JavaScript (JavaScript) is a client-side programming language that can be used to control elements of an HTML page (HTML tags) and a web browser, make them move, respond to various events (mouse clicks, keyboard presses), and create many interesting programs (scripts): tests, animation, photo galleries (for example, like on VKontakte), games and much more.

How to learn JavaScript

Learning JavaScript is usually divided into four stages:
1. Master JavaScript syntax (this tutorial),
2. Study of DOM and BOM,
3. Managing DOM and BOM using JavaScript,
4. Studying various JavaScript libraries. jQuery is the most popular library at the moment (a jQuery tutorial should appear on this site at the end of 2015).

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, by accessing this address, can access one or another HTML tag and manipulate it (change color, size, position, etc.).

BOM is a browser document model. The structure is the same as the DOM, only instead of HTML page objects, there are browser objects: browser window, browser screen size, browsing history, status line, etc.

After studying the DOM and BOM, we begin to create more or less complex JavaScript scripts that interact with the page and the browser.

Then, having become a little more comfortable, they study some JavaScript library, for example jQuery, thanks to which you can create the same programs as in JavaScript, only much faster and more efficiently.

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

What programs can you write using JavaScript?

You can use it to create many interesting programs (scripts):
— you can create scripts that will change the elements of a website page or their location by clicking on one or another button,
- you can create animation,
— manipulate forms, for example, check user-entered data for correctness,
— create various tests, for example, like the Unified State Examination (school exams) and immediately get the result,
— thanks to BOM, you can find out the characteristics of the browser and 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 book is to teach you the basics of JavaScript syntax, introducing you to programming and concepts such as variables, data types, operations, branch statements, functions, loops, arrays, objects, etc. All this is found in other programming languages, so once you master JavaScript, it will be much easier for you to learn other languages, such as PHP, C++ or Python.

JavaScript Tutorial Structure

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

Examples in every chapter

With the Try It Yourself editor, you can edit all the examples and preview the results.

Example My First JavaScript Click on me to display the date and time Learn from the examples

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

This tutorial complements all explanations with refined "Try It Yourself" examples.

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

Why learn JavaScript?

JavaScript is one of the 3 languages ​​all web developers need to learn:

1. HTML Defining the content of web pages

2. CSS Specifying the Layout of Web Pages

3. JavaScript Programming Web Page Behavior

Web pages are not the only place where JavaScript is used. Many desktop and server programs use JavaScript. Node. js is the most famous. Some databases, such as MongoDB and CouchDB, also use JavaScript as a programming language.

Did you know?

JavaScript and Java are completely different languages, both in concept and design.

JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMA-262 is the official name of the standard. ECMAScript is the official name of the language.

Learning rate

In this tutorial, the learning speed is your choice.

Everything is up to you.

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

Always make sure you understand all "try it yourself" examples.

The program, which is traditionally called “Hello, world! ", is very simple. It outputs somewhere the phrase “Hello, world!”, or another similar one, using a certain language.

JavaScript is a language in which programs can be executed in different environments. In our case, we are talking about browsers and the Node.js server platform. If you haven't written a single line of JS code yet and are reading this text in a browser on a desktop computer, this means that you are literally seconds away from your first JavaScript program.

In order to write it, if you use Google Chrome, open the browser menu and select the Additional tools > Developer tools command. The browser window will be divided into two parts. In one of them the page will be visible, in the other a panel with developer tools will open, containing several bookmarks. We are interested in the Console tab. Click on it. Ignore what may already be present in the console (you can use the Ctrl + L key combination to clear it). We are now interested in the console invitation. This is where you can enter JavaScript code, which is executed by pressing the Enter key. Let's enter the following into the console:

Console.log("Hello, world!")
This text can be entered from the keyboard, or you can copy and paste it into the console. The result will be the same, but if you are learning to program, it is recommended to enter the program texts yourself rather than copy them.

After the program text is in the console, press the Enter key.

If everything is done correctly, the text Hello, world! will appear under this line. . Ignore everything else for now.


The first program in the browser console - outputting a message to the console

Another version of the browser “Hello, world!” consists of displaying a message window. This is done like this:

Alert("Hello, world!")
Here is the result of running this program.


Display a message in a window

Notice that the developer toolbar is now located at the bottom of the screen. You can change its location by using the menu with three dots in its title and selecting the appropriate icon. There you can also find a button to close this panel.

Developer tools, including the console, are also available in other browsers. The good thing about the console is that it is always at hand when you use the browser.

There are other ways to run JS code in the browser. So, in the typical usage of JavaScript programs, they are loaded into the browser to make web pages work. As a rule, the code is formatted as separate files with the .js extension, which are connected to web pages, but the program code can also be included directly in the page code. All this is done using the tag. When the browser encounters such code, it executes it. Details about the tag can be found on w3school.com. In particular, let's consider an example demonstrating how to work with a web page using JavaScript, given on this resource. This example can also be run using this resource (look for the Try it Yourself button), but we will do it a little differently. Namely, let's create a new file in some text editor (for example, in VS Code or Notepad++), which we will call hello.html , and add the following code to it:

document.getElementById("hello").innerHTML = "Hello, world!";
Here we are most interested in the line document.getElementById("hello").innerHTML = "Hello, world!"; , which is JS code. This code is enclosed in opening and closing tags. It finds an HTML element in the document with the identifier hello and changes its innerHTML property (that is, the HTML code contained inside this element) to Hello, world! . If you open the hello.html file in a browser, the specified text will be displayed.


Message output by JavaScript to an HTML element

As already mentioned, you can try the examples given on the website w3school.com right away. There are also specialized online environments for web development, and, in particular, for executing JS code. Among them, for example, codepen.io, jsfiddle.net, jsbin.com.

Here, for example, is what our example looks like, recreated using CodePen.


The HTML field contains the code describing the HTML element, the JS field contains the JavaScript code, and the result is displayed at the bottom of the page.

We said above that JavaScript programs can be executed on various platforms, one of which is the Node.js server environment. If you're going to learn JavaScript with a focus on server-side development, you should probably run examples using Node.js. Please note that, simply speaking, and without taking into account the specific support of specific language features by the versions of Node.js and the browser used, the same code will run in Node.js and in the browser, which uses the basic mechanisms of the language. That is, for example, the command console.log("Hello, world!") will work in both places. Programs that use browser-specific mechanisms will not run in Node.js (the same goes for attempts to run Node.js programs in a browser).

In order to launch our “Hello, world!” in the Node.js environment, install Node.js by downloading the appropriate distribution from here. Now let's create a hello.js file and place the following code in it:

Console.log("Hello, World!");
Using the command line, go to the folder in which this file is stored and run the following command:

Node hello.js
This is what the result of its execution will be:


Message output by Node.js

By the way, you may have noticed (and most likely noticed if you typed the code yourself) that in some of the above examples, semicolons are used at the end of lines, and in others they are not. In some, the text that we want to output to the console or as a message is surrounded by double quotes, and in others, by single quotes. Now you may be wondering why this is so, and how, if different versions of the code work without errors, you can write this code correctly. If we answer this question without going into detail and without taking into account some small details, then we can say that both options for using quotation marks and semicolons are acceptable, and that they work the same way. The choice of a particular option depends on the coding style followed by the programmer and on the needs of a certain fragment of the program. In addition, from these simple examples you could feel one of the characteristic features of JavaScript, which is that the language gives the programmer a certain freedom.

Now that you've had your first acquaintance with JavaScript, we suggest you talk in more detail about this language.

Understanding JavaScript JavaScript is one of the most popular programming languages ​​in the world. Created more than 20 years ago, it has come a long way in its development. JavaScript was intended to be a scripting language for browsers. At the very beginning, he had much more modest capabilities than now. It was mainly used to create simple animations, such as drop-down menus, and was known as part of Dynamic HTML technology (DHTML, dynamic HTML).

Over time, the needs of the web environment grew, in particular, new APIs appeared, and JavaScript needed to keep up with other technologies to support web development.

These days, JS is used not only in traditional browsers, but also beyond them. In particular, we are talking about the Node.js server platform, the possibilities for using JavaScript in the development of embedded and mobile applications, and solving a wide range of problems for which JavaScript has not been used before.

Key Features of JavaScript JavaScript is a language that has the following features:
  • High level. It gives the programmer abstractions that make it possible to ignore the specifics of the hardware on which JavaScript programs are executed. The language automatically manages memory using a garbage collector. As a result, the developer can focus on solving the problems facing him without being distracted by low-level mechanisms (although, it should be noted, this does not eliminate the need for rational use of memory). The language offers powerful and convenient tools for working with various types of data.
  • Dynamic. Unlike static programming languages, dynamic languages ​​are able, during program execution, to perform actions that static languages ​​perform during program compilation. This approach has its pros and cons, but it gives the developer such powerful features as dynamic typing, late binding, reflection, functional programming, changing objects at runtime, closures, and much more.
  • Dynamically typed. Variable types are not required to be specified during JS development. In the same variable, for example, you can first write a string and then an integer.
  • Weakly typed. Unlike strongly typed languages, weakly typed languages ​​do not force the programmer, for example, to use objects of certain types in certain situations, performing implicit type conversions if necessary. This gives more flexibility, but JS programs are not type safe, which makes type checking more difficult (TypeScript and Flow are aimed at solving this problem).
  • Interpretable. It is widely believed that JavaScript is an interpreted programming language, which means that programs written in it do not need to be compiled before execution. In this regard, JS is contrasted with languages ​​such as C, Java, Go. In practice, browsers, to improve program performance, compile JS code before executing it. This step, however, is transparent to the programmer and does not require additional effort from him.
  • Multi-paradigm. JavaScript does not force the developer to use any particular programming paradigm, unlike, for example, Java (object-oriented programming) or C (imperative programming). You can write JS programs using the object-oriented paradigm, in particular, using prototypes and classes that appeared in the ES6 standard. JS programs can also be written in a functional style, due to the fact that functions here are first-class objects. JavaScript also allows working in the imperative style used in C.
Yes, by the way, it should be noted that JavaScript and Java have nothing in common. These are completely different languages. JavaScript and ECMAScript standards, or ES, is the name of the standard that guides developers of JavaScript engines, that is, those environments where JS programs are executed. Various standards introduce new features into the language, when talking about which they often mention the name of the standards in an abbreviated form, for example, ES6. ES6 is the same as ES2015, only in the first case the number means the version number of the standard (6), and in the second case the year the standard was adopted (2015).

It so happens that in the world of web programming, the ES3 standard, adopted in 1999, has been relevant for a very long time. There is no fourth version of the standard (they tried to add too many new features to it and were never accepted). In 2009, the ES5 standard was adopted, which was a truly huge update to the language, the first in 10 years. After it, in 2011, the ES5.1 standard was adopted, and it also contained a lot of new things. The ES6 standard, adopted in 2015, also became very significant in terms of innovations. Since 2015, new versions of the standard have been adopted every year.

The most recent version of the standard at the time of publication of this material is ES9, adopted in June 2018.

Results Today we wrote “Hello, World!” in JavaScript, looked at the main features of the language and talked about its standardization. Next time we'll talk about the style of JavaScript texts and the lexical structure of programs.

Dear readers! If you were not familiar with JavaScript before reading this material, please tell us if you were able to run “Hello, world!”

JavaScript is a programming language that adds interactivity to your website (for example games, responses when buttons are pressed or data is entered in forms, dynamic styling, and animation). This article helps you get started with this exciting language and gives you an idea of ​​what is possible.

What is JavaScript, really?

Important : If you haven't been following along with the rest of our course, download this example code and use it as a starting point.

Variables Variable Explanation ExampleString Number Boolean Array Object
A sequence of text known as a string. To signify that the value is a string, you must enclose it in quote marks. let myVariable = "Bob";
A number. Numbers don"t have quotes around them. let myVariable = 10;
A True/False value. The words true and false are special keywords in JS, and don"t need quotes. let myVariable = true;
A structure that allows you to store multiple values ​​in one single reference. let myVariable = ;
Refer to each member of the array like this:
myVariable, myVariable, etc.
Basically, anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn. let myVariable = document.querySelector("h1");
All of the above examples too.

So why do we need variables? Well, variables are needed to do anything interesting in programming. If values ​​couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change the image displayed in an image gallery.

Comments

You can put comments into JavaScript code, just as you can in CSS:

/* Everything in between is a comment. */

If your comment contains no line breaks, it"s often easier to put it behind two slashes like this:

// This is a comment

Operators Events

Real interactivity on a website needs events. These are code structures which listen for things happening in the browser and runs code in response. The most obvious example is the click event, which is fired by the browser when you click on something with your mouse. To demonstrate this, enter the following into your console, then click on the current webpage:

Document.querySelector("html").onclick = function() ( alert("Ouch! Stop poking me!"); )

There are many ways to attach an event to an element. Here we select the element, setting its onclick handler property equal to an anonymous (i.e. nameless) function, which contains the code we want the click event to run.

Document.querySelector("html").onclick = function() ();

is equivalent to

Let myHTML = document.querySelector("html"); myHTML.onclick = function()();

It's just shorter.

Supercharging our example website

Now we"ve gone over a few JavaScript basics, let"s add a few cool features to our example site to see what is possible.

Adding an image changer

In this section, we"ll add an additional image to our site using some more DOM API features, using some JavaScript to switch between the two when the image is clicked.

  • First of all, find another image you"d like to feature on your site. Be sure it is the same size as the first image, or as close as possible.
  • Save this image in your images folder.
  • Rename this image "firefox2.png" (without quotes).
  • Go to your main.js file, and enter the following JavaScript. (If your "Hello world!" JavaScript is still there, delete it.) let myImage = document.querySelector("img"); myImage.onclick = function() ( let mySrc = myImage.getAttribute("src"); if(mySrc === "images/firefox-icon.png") ( myImage.setAttribute("src","images/firefox2. png"); ) else ( myImage.setAttribute("src","images/firefox-icon.png"); ) )
  • Save all files and load index.html in the browser. Now when you click the image, it should change to the other one!
  • If you get stuck, you can compare your work with our finished example code on GitHub.

    We have barely scratched the surface of JavaScript. If you have enjoyed playing, and wish to advance even further, head to our JavaScript learning topic.





    

    2024 gtavrl.ru.