JavaScript の基本

この記事は翻訳作業中です。

JavaScriptはウェブサイトにインタラクティブ機能を追加するプログラミング言語です (例えばゲーム、ボタンが押されたときの応答、フォームに入力されたデータ、ダイナミックスタイリング、アニメーションなど) 。この記事では、このエキサイティングな言語を使い始めるのに役立ち、可能なことについて考えます。

JavaScript とは何ですか?

JavaScript (略して "JS" ) は HTML ドキュメントに適用すると、Web サイト上で動的な対話性を提供できる動的プログラミング言語 です。 Mozilla プロジェクト、Mozilla Foundation、Mozilla Corporation の共同設立者である Brendan Eich によって考案されました。

JavaScript は非常に多用途です。 ボタンのクリックに対するカルーセル、画像ギャラリー、レイアウトの変動など、小さなものから始められます。より多くの経験を生かして、ゲーム、アニメーション 2D および 3D グラフィックス、包括的なデータベース駆動型アプリケーションなどを作成することができます。

JavaScript は非常にコンパクトですが、一方非常に柔軟性があります。開発者はコア JavaScript 言語の上に多種多様なツールを作成し、最小限の労力で膨大な様々な機能を解き放つことができます。これらには以下を含みます :

  • ブラウザアプリケーションプログラミングインターフェイス (APIs) — HTML を動的に作成し、CSS スタイルを設定したり、ユーザーのウェブカメラからビデオストリームを収集したり操作したり、3D グラフィックスやオーディオサンプルを生成する機能を提供する Web ブラウザに組み込まれた API。
  • 開発者が Twitter や Facebook などの他のコンテンツプロバイダのサイトから機能を組み込むことを可能にするサードパーティの API。
  • 高速に HTML サイトやアプリケーションを構築できるサードパーティのフレームワークやライブラリ。

この記事は JavaScript の簡単な導入部です。今の段階では JavaScript のコア言語と上記のさまざまなツールの違いについて説明を行いますが、混乱させるようなことは行いません。 後に JavaScript の学習領域、およびその他の MDN の記事で詳細を学ぶことができます。

以下ではコア言語のいくつかの側面について紹介します。またいくつかのブラウザ API 機能についても説明します。楽しみましょう

"Hello world" の例

上記のセクションは本当にエキサイティングに聞こえるかもしれませんJavaScript は最も活気のある Web 技術の 1 つです。使い始めると、ウェブサイトは新しい次元の力と創造性に入ります。

しかし、JavaScript は HTML や CSS よりも快適に使うためには少し複雑です。小さなものから始め、小さな一貫した手順で作業を続ける必要があるかもしれません。まず、基本的な JavaScript をページに追加し、"hello world!"  の例を作成する方法を紹介します (プログラミング学習の基本) 。

重要 : 今までのコースを実施していない場合は、このサンプルコードをダウンロードして作業を進めてください。

  1. まず最初に、あなたのテストサイトに移動し、'scripts' (引用符なし) という名前の新しいフォルダを作成してください。そこで新しく作成した script フォルダに main.js という名前のファイルを作成してください。そのファイルを scripts フォルダーに保存してください。
  2. 次に、index.html ファイルの </body> タグの前に新しい行を追加し、以下の新しい要素を追加してください :
    <script src="scripts/main.js"></script>
  3. これは基本的には CSS の <link> 要素と同じ仕事をしていますJavaScript をページに適用し、HTML (CSS と同じくページ上の他のものにも)に影響を与えることができます。
  4. main.js ファイルに次のものを追加します :
    var myHeading = document.querySelector('h1');
    myHeading.textContent = 'Hello world!';
  5. 最後に、HTML ファイルと JavaScript ファイルを保存し、ブラウザで index.html を読み込みます。そうすると次のように見えるでしょう :

: <script> 要素を HTML ファイルの最下部の近くに置いたのは、HTML がファイルに現れる順番でブラウザによって読み込まれるからです。JavaScript が最初に読み込まれ、その下の HTML に影響すると思われる場合、JavaScript が動作するはずの HTML の前に JavaScript が読み込まれるため、JavaScript が機能しない可能性があります。したがって、HTML ページの下部に JavaScript を置くことが、しばしば最良の戦略です。

何が起きた?

あなたの見出しのテキストが JavaScript を使用して "Hello world!" に変更されました。最初に querySelector() という関数を使用して、見出しの参照を取得し、 myHeading という変数に格納します。 これは CSS セレクタを使用した場合と非常によく似ています。ある要素に対して何かをしたいときは、まずその要素を選択する必要があります。

その後 myHeading 変数の textContent プロパティ (見出しの内容を表す) の値を "Hello world!" に設定します。

: 上記で使用した両方の機能は、ドキュメントオブジェクトモデル (DOM) APIの一部であり、ドキュメントを操作できます。

言語の基本短期集中コース

JavaScript 言語の基本的な機能のいくつかを説明して、JavaScript 言語の仕組みをより深く理解できるようにしましょう。さらにこれらの機能はすべてのプログラミング言語に共通しています。これらの基本を習得すれば、何かをプログラムできるようになります!

重要 : この記事では、JavaScript のコンソールにサンプルコード行を入力して、何が起こっているかを確認してみましょう。JavaScript コンソールの詳細については、ブラウザの開発者ツールを参照してください。

Variables は、値を格納できるコンテナです。最初に var キーワードで変数を宣言し、それに続けて任意の名前を指定します :

var myVariable;

Note: A semi-colon at the end of a line indicates where a statement ends; it is only absolutely required when you need to separate statements on a single line, but some people believe that it is a good practice to put them in at the end of each statement. There are other rules for when you should and shouldn't use them — see Your Guide to Semicolons in JavaScript for more details.

Note: You can name a variable nearly anything, but there are some name restrictions (see this article on variable naming rules.) If you are unsure, you can check your variable name to see if it is valid.

Note: JavaScript is case sensitive — myVariable is a different variable to myvariable. If you are getting problems in your code, check the casing!

After declaring a variable, you can give it a value:

myVariable = 'Bob';

You can do both these operations on the same line if you wish:

var myVariable = 'Bob';

You can retrieve the value by just calling the variable by name:

myVariable;

After giving a variable a value, you can later choose to change it:

var myVariable = 'Bob';
myVariable = 'Steve';

Note that variables have different data types:

Variable Explanation Example
String A sequence of text known as a string. To signify that the variable is a string, you should enclose it in quote marks. var myVariable = 'Bob';
Number A number. Numbers don't have quotes around them. var myVariable = 10;
Boolean A True/False value. The words true and false are special keywords in JS, and don't need quotes. var myVariable = true;
Array A structure that allows you to store multiple values in one single reference. var myVariable = [1,'Bob','Steve',10];
Refer to each member of the array like this:
myVariable[0], myVariable[1], etc.
Object Basically, anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn. var 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.

コメント

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

演算子

An operator is a mathematical symbol which produces a result based on two values (or variables). In the following table you can see some of the simplest operators, along with some examples to try out in the JavaScript console.

Operator Explanation Symbol(s) Example
add/concatenation Used to add two numbers together, or glue two strings together. + 6 + 9;
"Hello " + "world!";
subtract, multiply, divide These do what you'd expect them to do in basic math. -, *, / 9 - 3;
8 * 2; // multiply in JS is an asterisk
9 / 3;
assignment operator You've seen this already: it assigns a value to a variable. = var myVariable = 'Bob';
Identity operator Does a test to see if two values are equal to one another, and returns a true/false (Boolean) result. === var myVariable = 3;
myVariable === 4;
Negation, not equal Returns the logically opposite value of what it precedes; it turns a true into a false, etc. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal. !, !==

The basic expression is true, but the comparison returns false because we've negated it:

var myVariable = 3;
!(myVariable === 3);

Here we are testing "is myVariable NOT equal to 3". This returns false because myVariable IS equal to 3.

var myVariable = 3;
myVariable !== 3;

There are a lot more operators to explore, but this is enough for now. See Expressions and operators for a complete list.

Note: Mixing data types can lead to some strange results when performing calculations, so be careful that you are referring to your variables correctly, and getting the results you expect. For example, enter "35" + "25" into your console. Why don't you get the result you expected? Because the quote marks turn the numbers into strings, so you've ended up concatenating strings rather than adding numbers. If you enter, 35 + 25 you'll get the correct result.

条件式

Conditionals are code structures which allow you to test if an expression returns true or not, running alternative code revealed by its result. The most common form of conditional is called if ... else.  So for example:

var iceCream = 'chocolate';
if (iceCream === 'chocolate') {
  alert('Yay, I love chocolate ice cream!');    
} else {
  alert('Awwww, but chocolate is my favorite...');    
}

The expression inside the if ( ... ) is the test — this uses the identity operator (as described above) to compare the variable iceCream with the string chocolate to see if the two are equal. If this comparison returns true, the first block of code is run. If the comparison is not true, the first block is skipped and the second code block, after the else statement, is run instead.

関数

Functions are a way of packaging functionality that you wish to reuse. When you need the procedure you can call a function, with the function name, instead of rewriting the entire code each time. You have already seen some uses of functions above, for example:

  1. var myVariable = document.querySelector('h1');
  2. alert('hello!');

These functions, document.querySelector and alert, are built into the browser for you to use whenever you desire.

If you see something which looks like a variable name, but has parentheses — () — after it, it is likely a function. Functions often take arguments — bits of data they need to do their job. These go inside the parentheses, separated by commas if there is more than one argument.

For example, the alert() function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what to write in the pop-up box.

The good news is you can define your own functions — in this next example we write a simple function which takes two numbers as arguments and multiplies them:

function multiply(num1,num2) {
  var result = num1 * num2;
  return result;
}

Try running the above function in the console, then test with several arguments. For example:

multiply(4,7);
multiply(20,20);
multiply(0.5,3);

Note: The return statement tells the browser to return the result variable out of the function so it is available to use. This is necessary because variables defined inside functions are only available inside those functions. This is called variable scoping. (Read more on variable scoping.)

イベント

Real interactivity on a website needs events. These are code structures which listen for things happening in browser, running 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 HTML 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.

Note that

document.querySelector('html').onclick = function() {};

is equivalent to

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

  1. 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.
  2. Save this image in your images folder.
  3. Rename this image 'firefox2.png' (without quotes).
  4. Go to your main.js file, and enter the following JavaScript. (If your "hello world" JavaScript is still there, delete it.)
    var myImage = document.querySelector('img');
    
    myImage.onclick = function() {
        var mySrc = myImage.getAttribute('src');
        if(mySrc === 'images/firefox-icon.png') {
          myImage.setAttribute ('src','images/firefox2.png');
        } else {
          myImage.setAttribute ('src','images/firefox-icon.png');
        }
    }
  5. Save all files and load index.html in the browser. Now when you click the image, it should change to the other one!

You store a reference to your image element in the myImage variable. Next, you make this variable's onclick event handler property equal to a function with no name (an "anonymous" function). Now, every time this image element is clicked:

  1. You retrieve the value of the image's src attribute.
  2. You use a conditional to check whether the src value is equal to the path to the original image:
    1. If it is, you change the src value to the path to the 2nd image, forcing the other image to be loaded inside the <image> element.
    2. If it isn't (meaning it must already have changed), the src value swaps back to the original image path, to the original state.

Adding a personalized welcome message

Next we will add another bit of code, changing the page's title to a personalized welcome message when the user first navigates to the site. This welcome message will persist, should the user leave the site and later return — we will save it using the Web Storage API. We will also include an option to change the user and, therefore, the welcome message anytime it is required.

  1. In index.html, add the following line just before the <script> element:
    <button>Change user</button>
  2. In main.js, place the following code at the bottom of the file, exactly as written — this takes references to the new button and the heading, storing them inside variables:
    var myButton = document.querySelector('button');
    var myHeading = document.querySelector('h1');
  3. Now add the following function to set the personalized greeting — this won't do anything yet, but we'll fix this in a moment:
    function setUserName() {
      var myName = prompt('Please enter your name.');
      localStorage.setItem('name', myName);
      myHeading.textContent = 'Mozilla is cool, ' + myName;
    }
    This function contains a prompt() function, which brings up a dialog box, a bit like alert(). This prompt(), however, asks the user to enter some data, storing it in a variable after the user presses OK. In this case, we are asking the user to enter their name. Next, we call on an API called localStorage, which allows us to store data in the browser and later retrieve it. We use localStorage's setItem() function to create and store a data item called 'name', setting its value to the myName variable which contains the data the user entered. Finally, we set the textContent of the heading to a string, plus the user's newly stored name.
  4. Next, add this if ... else block — we could call this the initialization code, as it structures the app when it first loads:
    if(!localStorage.getItem('name')) {
      setUserName();
    } else {
      var storedName = localStorage.getItem('name');
      myHeading.textContent = 'Mozilla is cool, ' + storedName;
    }
    This block first uses the negation operator (logical NOT, represented by the !) to check whether the name data exists. If not, the setUserName() function is run to create it. If it exists (that is, the user set it during a previous visit), we retrieve the stored name using getItem() and set the textContent of the heading to a string, plus the user's name, as we did inside setUserName().
  5. Finally, put the below onclick event handler on the button. When clicked, the setUserName() function is run. This allows the user to set a new name, when they wish, by pressing the button:
    myButton.onclick = function() {
      setUserName();
    }
    

Now when you first visit the site, it will ask you for your username, then give you a personalized message. You can change the name any time you like by pressing the button. As an added bonus, because the name is stored inside localStorage, it persists after the site is closed down, keeping the personalized message there when you next open the site!

結論

If you have followed all the instructions in this article, you should end up with a page that looks something like this (you can also view our version here):

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.

ドキュメントのタグと貢献者

 このページの貢献者: T.Ukegawa
 最終更新者: T.Ukegawa,