Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Dasar JavaScript

Terjemahan ini belum lengkap. Mohon bantu menerjemahkan artikel ini dari Bahasa Inggris.

JavaScript adalah bahasa pemograman yang digunakan untuk menambahkan fitur interaktif pada website anda, seperti ketika ingin membuat game, melakukan perubahan ketika mengklik tombol, efek dinamik, animasi, dan masih banyak lagi. Tutorial ini adalah dasar dari JavaScript yang akan memberikan gambaran apa yang bisa anda buat dengan JavaScript.

Apakah JavaScript yang Sebenarnya?

JavaScript adalah bahasa pemograman yang sangat matang dan dapat dikolaborasikan dengan dokumen HTML dan digunakan untuk membuat website yang interaktif. JavaScript diciptakan oleh Brendan Eich yang juga co-founder dari Mozilla project, Mozilla Foundation dan Mozilla Corporation.

Anda dapat melakukan banyak hal dengan JavaScript. Anda akan memulai dari fitur sederhana seperti menentukan layout, membuat respon ketika mengkil button, caousels, dan gallery gambar. Namun pada akhirnya ketika anda sudah mendapat banyak pengetahuan anda juga akan dapat membuat game, animasi 2D dan 3D, aplikasi yang berhubungan dengan database, dan masih banyak lagi.

JavaScript sendiri adalah bahasa yang cukup komplek namun sangat fleksibel, dan banyak Developer (Programmer) telah menyediakan tool yang berdiri diatas core JavaScript agar anda dapat menggunakan fungsi - fungsi ekstra, tool tersebut sebagai berikut :

  • Application Programming Interfaces (APIs) dibangun pada web browser agar memungkinkan anda melakukan apapun dari dinamik dokumen HTML dan set CSS yang anda buat, untuk menangkap dan memodifikasi video dari web cam, atau membuat animasi 3D dan sampel audio.
  • 3rd party APIs menyediakan akses bagi Developer untuk menghubungkan aplikasi mereka pada website atau aplikasi lain layaknya facebook dan twitter. Pernahkan anda login soundcloud dengan facebook ? itu 3rd party APIs.
  • 3rd party frameworks dan libraries dapat digabungkan pada HTML sehingga memungkinkan Developer membangun website atau aplikasi dengan cepat.

Contoh "Hello World"

Judul diatas terdengar menarik bukan ?. JavaScript adalah salah satu bahasa yang sangar menarik dari banyak teknologi web yang lain. dan jika anda mengikuti tutorial ini dengan baik, anda dapat menambahkan dimensi baru dan hal lain yang kreatif pada website anda. 

Namun, JavaScript sedikit lebih rumit dari pada HTML dan CSS, dan anda akan belajar sedikit demi sedikit, dan tetaplah belajar pada langkah-langkah kecil yang kami berikan. Untuk memulainya, kami akan menunjukkan bagaimana cara menambah beberapa skrip JavaScript yang sangat sederhana pada halaman Anda, yakni dengan contoh cara membuat "Hello, world!" (contoh standar pada dasar pemrograman.)

Penting: Jika anda belum mengikuti semua kursus kami, download contoh kode berikut dan gunakan untuk memulai.

Catatan: Alasan kita menepatkan elemen <script> di bawah file html adalah ketika HTML di muat oleh browser untuk ditampilkan pada sebuah file. Jika JavaScript dimuat pertama kali dan seharusnya mempengatuhi HTML di bawahnya, kemungkinan ini tidak bisa bekerja, oleh karena itu JavaScript dimuat sebelum HTML bekeja seperti seharusnya. Oleh karena itu, strategi yang terbaik biasanya adalah di bawah halaman.

  1. Pertama-tema, buka situs percobaan anda, dan buatlah sebuah file baru bernama main.js. Simpan di dalam folder scripts.
  2. Selanjutnya, buka file index.html Anda, dan masukkan elemen berikut pada sebuah baris bari sebelum tag penutup </body>:
    <script src="scripts/main.js"></script>
  3. Ini sama halnya dengan cara kerja elemen <link> untuk CSS — ini menempatkan JavaScript ke halaman, sehingga dapat memberikan pegaruh pada HTML (CSS, dan lainnya pada halaman).
  4. Sekarang tambahkan ode berikut pada file main.js:
    var myHeading = document.querySelector('h1');
    myHeading.innerHTML = 'Hello world!';
  5. Sekarang pastikan file HTML dan JavaScript disimpan, dan muat index.html di browser. Anda seharusnya mendapatkan hasil seperti berikut:

Apa yang Terjadi?

Jadi text heading anda telah diubah menjadi "Hello world!" mengunakan JavaScript. Kita melakukannya dengan menggunakan fungsi querySelector() untuk mendapatkan referensi untuk heading, dan menyimpannya di variabel myHeading. Ini sama halnya seperti yang kita lakukan saat menggunakan CSS selector — kita menginginkan untuk melakukan sesuatu ke sebuah elemen, maka kita perlu memilihnya terlebih dahulu.

Setelah itu, kita tambahkan nilai dari variabel myHeading  properti innerHTML  ( dimana mewakili konten heading) ke "Hello world!".

Language basics crash course

Let's explain just some of the basic features of the JavaScript language, to give you some more understand of how it all works.

Important: In this article, try entering the example code lines into your browser console to see what happens. For more details on browser consoles, see Discover browser developer tools.

Note: Such features are common to all programming languages. If you can understand these fundamentals, you should be able to make a start in programming just about anything.

Variables

Variables are containers that you can store values in. You start by declaring a variable with the var keyword, followed by any name you want to call it:

var myVariable;

Note: All lines in JS must end with a semi-colon, to indicate that this is where the line ends. If you don't include these, you can get unexpected results.

Note: You can call a variable nearly anything, but there are some name restrictions (see this article on variable naming rules.)

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 retrieve the value by just calling the variable by name:

myVariable;

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

var myVariable = 'Bob';

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 string of text. 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. true/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];
Call 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 wouldn't be able to do anything dynamic, like personalize a greeting message to the user visiting your site, or change the image displayed in an image gallery, etc.

Comments

You can put comments into JavaScript code, just like you can in CSS. In JavaScript, single line comments look like this:

// This is a comment

But you can also use CSS-style multi line comments:

/*
This is a multi line
comment
*/

Operators

An operator is basically a mathematical symbol that can act on two values (or variables) and produce a result. In the below table you can see some of the most simple operators, along with some examples to try out in the browser console.

Operator Explanation Symbol(s) Example
add/concatenation Used to add two numbers together, or glue two strings together. + 6 + 9;
"Hello " + "world!";
subtract, multiple, 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 Often used alongside the Equality operator, the negation operator is the JS equivalent of a logical NOT — it turns a true into a false, etc. !, !==

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 it IS equal to 3.

var myVariable = 3;
myVariable !== 3;

There are a lot more to explore, but this will do 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 expected. For example enter "35" + "25" into your console. Why do you not get the result you expected? Because the quote marks turn the numbers into strings — you've ended up with the strings concatenated together, and not numbers added. If you enter 35 + 25, you'll get the correct result.

Conditionals

Conditionals are code structures that allow you to test whether an expression returns true or not, and then run different code depending on the 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, run the first block of code. If not, skip that code and run the second block of code after the else statement.

Functions

Functions are a way of encapsulating functionality that you want to reuse, so you can call that function with a single function name, and not have to write the entire code out again and again each time you use it. You have already seen some functions above, for example:

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

These functions are built into the browser for you to use whenever you like.

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

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 it what message it is supposed to write in the pop-up box.

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

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

Try running the above function in the console, then try using your new function a few times, e.g.:

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

Events

To create real interactivity on a website, you have to use events — these are code structures that listen out for things happening to the browser, and then allow you to run code in response to those things happening. The most obvious example is the click event, which is fired by the browser when the mouse clicks on something. To demonstrate this, try entering the following into your console, then clicking on the current web page:

document.querySelector('html').onclick = function() {
    alert('Ouch! Stop poking me!');
}

There are many ways to attach an event to an element; here we are selecting the HTML element and making its onclick handler property equal to an anonymous function (a function without a name) that contains the code we want to run when the click event occurs.

Note that

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

is equivalent to

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

It's just a shorter way to write it.

Supercharging our example website

Now we've reviewed a few basics of JavaScript, let's add a couple of cool basic features to our example site to give you some first steps into what is possible.

Adding an image changer

In this section we'll add another image to our site, and add some simple JavaScript to change between the two when the image is clicked on.

  1. First of all, find another image that you'd like to feature on your site. Make sure it is the same size as your first image, or as close as possible.
  2. Save the image in your images folder.
  3. 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');
        }
    }
  4. Save all files and load index.html in the browser. Now when you click the image, it should change to the other one!

So here, we are storing a reference to our image element in the myImage variable. Next, we make this variable's onclick event handler property equal to an anonymous function. Now, every time this image element is clicked:

  1. We retrieve the value of the image's src attribute.
  2. We use a conditional to check whether the src value is equal to the path to the original image:
    1. If it is, we 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), we change the src value back to the original image path, to flip it back to what it was originally.

Adding a personalized welcome message

Next we will add another bit of code, to change the page's title to include a personalized welcome message when the user first navigates to the site. This welcome message will persist when the user leaves the site and then comes back. 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, add the following code at the bottom of the file, exactly as written — this grabs references to the new button we added and the heading, and stores them in 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 use it later on:
    function setUserName() {
      var myName = prompt('Please enter your name.');
      localStorage.setItem('name', myName);
      myHeading.innerHTML = 'Mozilla is cool, ' + myName;
    }
    This function contains a prompt() function, which brings up a dialog box a bit like alert() does; the difference is that prompt() asks the user to enter some data, and stores that data in a variable when the dialog OK button is pressed. 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 retrieve it later on. We use localStorage's setItem() function to create and store a data item called 'name', and set its value to the myName variable that contains the name the user entered. Finally, we set the innerHTML of the heading to a string, plus the user's name.
  4. Next, add this if ... else block — we could call this the initialization code, as it sets up the app when it first loads:
    if(!localStorage.getItem('name')) {
      setUserName();
    } else {
      var storedName = localStorage.getItem('name');
      myHeading.innerHTML = 'Mozilla is cool, ' + storedName;
    }
    This block first uses the negation operator (logical NOT) to check whether the name data item exists — if it doesn't exist, the setUserName() function is run to create it. If it already exists (i.e. the user set it when they previously visited the site), we retrieve the stored name using getItem() and set the innerHTML of the heading to a string, plus the user's name, the same as we did inside setUserName().
  5. Finally, put the below onclick event handler on the button, so that when clicked the setUserName() function is run. This allows the user to set a new name whenever they want by pressing the button:
    myButton.onclick = function() {
      setUserName();
    }

Now when you first visit the site, it'll ask you for your user name then give you a personalized message. You can then 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, so the personalized message will still be there when you open the site up again!

Conclusion

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 always compare your work with our finished example code on Github.

Here, we have only really scratched the surface of JavaScript. if you have enjoyed learning about it and and want to go deeper with your studies, go to our JavaScript Guide.

Tag Dokumen dan Kontributor

 Kontributor untuk laman ini: rmsubekti, miftahafina, adeyahya
 Terakhir diperbarui oleh: rmsubekti,