The basic toolkit needed to effectively develop javascript code consists of two elements

  • Previous
  • Overview: Getting started with the web
  • Next

JavaScript is a programming language that adds interactivity to your website. This happens in games, in the behavior of responses when buttons are pressed or with data entry on forms; with dynamic styling; with animation, etc. This article helps you get started with JavaScript and furthers your understanding of what is possible.

What is JavaScript?

JavaScript is a powerful programming language that can add interactivity to a website. It was invented by Brendan Eich.

JavaScript is versatile and beginner-friendly. With more experience, you'll be able to create games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more!

JavaScript itself is relatively compact, yet very flexible. Developers have written a variety of tools on top of the core JavaScript language, unlocking a vast amount of functionality with minimum effort. These include:

  • Browser Application Programming Interfaces (APIs) built into web browsers, providing functionality such as dynamically creating HTML and setting CSS styles; collecting and manipulating a video stream from a user's webcam, or generating 3D graphics and audio samples.
  • Third-party APIs that allow developers to incorporate functionality in sites from other content providers, such as Twitter or Facebook.
  • Third-party frameworks and libraries that you can apply to HTML to accelerate the work of building sites and applications.

It's outside the scope of this article—as a light introduction to JavaScript—to present the details of how the core JavaScript language is different from the tools listed above. You can learn more in MDN's JavaScript learning area, as well as in other parts of MDN.

The section below introduces some aspects of the core language and offers an opportunity to play with a few browser API features too. Have fun!

A Hello world! example

JavaScript is one of the most popular modern web technologies! As your JavaScript skills grow, your websites will enter a new dimension of power and creativity.

However, getting comfortable with JavaScript is more challenging than getting comfortable with HTML and CSS. You may have to start small, and progress gradually. To begin, let's examine how to add JavaScript to your page for creating a Hello world! example. (Hello world! is the standard for introductory programming examples.)

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

  1. Go to your test site and create a new folder named scripts. Within the scripts folder, create a new text document called main.js, and save it.
  2. In your index.html file, enter this code on a new line, just before the closing tag:

    <script src="scripts/main.js">script>
    

  3. This is doing the same job as the element for CSS. It applies the JavaScript to the page, so it can have an effect on the HTML (along with the CSS, and anything else on the page).
  4. Add this code to the main.js file:

    const myHeading = document.querySelector('h2');
    myHeading.textContent = 'Hello world!';
    

  5. Make sure the HTML and JavaScript files are saved. Then load index.html in your browser. You should see something like this:

The basic toolkit needed to effectively develop javascript code consists of two elements

Note: The reason the instructions (above) place the

Variables

Variables are containers that store values. You start by declaring a variable with the let keyword, followed by the name you give to the variable:

A semicolon at the end of a line indicates where a statement ends. It is only required when you need to separate statements on a single line. However, some people believe it's good practice to have semicolons at the end of each statement. There are other rules for when you should and shouldn't use semicolons. For more details, see Your Guide to Semicolons in JavaScript.

You can name a variable nearly anything, but there are some restrictions. (See this section about naming rules.) If you are unsure, you can check your variable name to see if it's valid.

JavaScript is case sensitive. This means myVariable is not the same as myvariable. If you have problems in your code, check the case!

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

Also, you can do both these operations on the same line:

You retrieve the value by calling the variable name:

After assigning a value to a variable, you can change it later in the code:

let myVariable = 'Bob';
myVariable = 'Steve';

Note that variables may hold values that have different data types:

So why do we need variables? Variables are necessary 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 an image displayed in an image gallery.

Comments are snippets of text that can be added along with code. The browser ignores text marked as comments. You can write comments in JavaScript just as you can in CSS:

/*
Everything in between is a comment.
*/

If your comment contains no line breaks, it's an option to put it behind two slashes like this:

Operators

An operator is a mathematical symbol that 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 in the JavaScript console.

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. 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 total of the two numbers.

Conditionals

Conditionals are code structures used to test if an expression returns true or not. A very common form of conditionals is the if...else statement. For example:

let 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 strict equality 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 runs. If the comparison is not true, the second block of code—after the else statement—runs instead.

Functions

Functions are a way of packaging functionality that you wish to reuse. It's possible to define a body of code as a function that executes when you call the function name in your code. This is a good alternative to repeatedly writing the same code. You have already seen some uses of functions. For example:

let myVariable = document.querySelector('h2');

These functions, document.querySelector and alert, are built into the browser.

If you see something which looks like a variable name, but it's followed by parentheses— () —it is likely a function. Functions often take arguments: bits of data they need to do their job. Arguments 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 message to display.

You can also define your own functions. In the next example, we create a simple function which takes two numbers as arguments and multiplies them:

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

Try running this 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 about variable scoping.)

Events

Real interactivity on a website requires event handlers. These are code structures that listen for activity in the browser, and run code in response. The most obvious example is handling 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').addEventListener('click', function () {
  alert('Ouch! Stop poking me!');
});

There are many ways to attach an event handler to an element. Here we select the element. We then call its addEventListener() function, passing in the name of the event to listen to ('click') and a function to run when the event happens.

Note that

document.querySelector('html').addEventListener('click', function () {
  alert('Ouch! Stop poking me!');
});

is equivalent to

let myHTML = document.querySelector('html');
myHTML.addEventListener('click', function () {
  alert('Ouch! Stop poking me!');
});

It's just shorter.

The functions we just passed to addEventListener() here are called anonymous functions, because they don't have a name. There's an alternative way of writing anonymous functions, which we call an arrow function. An arrow function uses () => instead of function ():

document.querySelector('html').addEventListener('click', () => {
  alert('Ouch! Stop poking me!');
});

Supercharging our example website

With this review of JavaScript basics completed (above), let's add some new features to our example site.

Before going any further, delete the current contents of your main.js file — the bit you added earlier during the "Hello world!" example — and save the empty file. If you don't, the existing code will clash with the new code you are about to add.

Adding an image changer

In this section, you will learn how to use JavaScript and DOM API features to alternate the display of one of two images. This change will happen as a user clicks the displayed image.

  1. Choose an image you want to feature on your example site. Ideally, the image will be the same size as the image you added previously, or as close as possible.
  2. Save this image in your images folder.
  3. Rename the image firefox2.png.
  4. Add the following JavaScript code to your main.js file.

    const myImage = document.querySelector('img');
    
    myImage.onclick = () => {
      const 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.

This is what happened. You stored a reference to your

The basic toolkit needed to effectively develop javascript code consists of two elements

If you get stuck, you can compare your work with our finished example code on GitHub.

We have just scratched the surface of JavaScript. If you enjoyed playing, and wish to go further, take advantage of the resources listed below.

See also

Dynamic client-side scripting with JavaScript

Dive into JavaScript in much more detail.

Learn JavaScript

This is an excellent resource for aspiring web developers! Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by an automated assessment. The first 40 lessons are free. The complete course is available for a small one-time payment.

  • Previous
  • Overview: Getting started with the web
  • Next

In this module

What are the tools used to write JavaScript code?

JS examples: jQuery, React, Socket.io, Bootstrap. Tool – a smaller assistant to make the development process easier, in terms of issues like performance, maintenance, etc. Things like compilers, image compressors, task runners, some JS examples are Browserify, JSLint, Mocha.

What are the basic requirements to learn JavaScript?

Prerequisites. To learn JavaScript, you must know the basics of HTML and CSS, both of which are extremely easy to learn. For a working knowledge of JavaScript and most web-based projects, this knowledge will be sufficient.

What are the most important parts of JavaScript?

Here are 10 things you definitely have to learn before you can call yourself a master in JavaScript..
Control Flow. Probably the most basic topic on the list. ... .
Error handling. This took a while for me. ... .
Data Models. ... .
Asynchronity. ... .
DOM Manipulation. ... .
Node. ... .
Functional Approach. ... .
Object Oriented Approach..

Which tool is best for JavaScript?

7 Best JavaScript Editor Choices.
Atom. Before diving straight into the features of Atom, let's first understand what Electron is. ... .
Visual Studio Code. ... .
Eclipse. ... .
Sublime Text. ... .
Brackets. ... .
NetBeans. ... .