Джава скрипт обучение с нуля. JavaScript Уроки и примеры. Выражения и операции

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

    Привет! Вы когда-нибудь задумывались о том, чтобы начать программировать? Лично я с детства мечтал научиться писать свои программы и игры. В последнее время во мне возник бурный интерес к этой деятельности и я задался для себя целью - понять и научиться работать, для начала, с таким языком программирования как JavaScript. Почему именно JavaScript?

    Так как я не имею за плечами опыта работы ни с какими языками, кроме базового курса HTML и СSS, JavaScript приглянулся мне своей универсальностью, стремительным ростом и необычной историей развития, которую я обязательно расскажу в одной из следующих статей. Говоря об универсальности, на данный момент применение JavaScript-кода не ограничивается одними лишь серверами и браузерами, но также используется при разработке мобильных приложений и программ для интернет-вещей.


    1. Sublime Text 2


    Лаконичный редактор кода общего назначения, способный работать со многими языками программирования. Он доступен для бесплатной загрузки под платформы Windows, Mac и Linux.

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

    В целом, Sublime Text является расширенной версией стандартного текстового редактора, но с более проработанным интерфейсом и уклоном под кодинг. Так что создание HTML-страниц в нём - полностью ручное кодирование, посему я не могу порекомендовать его для профессионально работы, но для новичков, типа нас с вами, этот редактор подойдет, дабы лучше усвоить принципы работы JS, HTML и CSS.

    2. Atom


    Atom - максимально гибкий в настройке текстовый редактор от разработчиков GitHub. Он бесплатен как для личного, так и для коммерческого использования по лицензии MIT. Его создатели активно следят за предложениями от пользователей и стараются своевременно пополнять редактор новыми функциями.


    Atom доступен для платформ Windows, Linux (Ubuntu, Fedora, Red Hat) и macOS. Также в программе имеется возможность выбора языка, на котором вы будете писать программу. Со стандартными плагинами поддерживается всего около 30 языков программирования: (C/C++, C#, Clojure, CSS, CoffeeScript, Markdown (GitHub Flavored), Go, Git, HTML, JavaScript, Java, JSON, Julia, Less, Make, Mustache, Objective-C, PHP, Perl, Property List (Apple), Python, Ruby on Rails, Ruby, Sass, Shell script, Scala, SQL, TOML, XML, YAML).

    Такого скромного софтверного арсенала на первое время должно хватить всем. Лично я все листинги буду создавать в Atom. Ну что, приступим!

    «Привет, мир!»


    В качестве примера для первого урока, по устоявшейся традиции среди программистов, мы создадим приветственную веб-страничку и подробно рассмотрим её устройство.

    Сначала немного теории. Вставка любого сценария Javascript в HTML-код производится с помощью использования тега и его вариаций. Например, при помощи атрибута src вы можете разместить прямую гиперссылку на файл содержащий код алгоритма в чистом виде, в нашем примере этот способ не использовался.

    Также существует рекомендация по использованию строчки