Javascript basics

JavaScript is a programming language that allows you to add interactive content to a web page (for example: games, reactions by pressing buttons or input in forms, dynamic look, animations, etc.). This article will help you take your first steps with this exciting language and give you an idea of what is possible.

What is JavaScript really?

JavaScript (short "JS") is a full-featured and dynamic programming language which, when added to an HTML document, provides dynamism and interaction with the user. JS was invented by Brendan Eich, co-founder of the Mozilla Project, the Mozilla Foundation, and the Mozilla Corporation.

JavaScript is incredibly versatile. You just start with simple features, like z.B. Carousels, (image) galleries, variable layouts, and reactions to button clicks. Later, when you’re more experienced with the language, you can use it to create entire games, animated 2D and 3D graphics, database-based apps, and much more!

JavaScript in itself is very compact and yet flexible. Many developers have written even more tools/extensions for working with JavaScript to get even more efficiency out of JS with little effort. These functions are:

  • Application programming interfaces (APIs) implemented in browsers to extend them with JS functions, z.B. dynamically creating HTML or setting a CSS style, intercepting and manipulating video streams, creating 3D graphics/audio samples, and more.
  • Third-party APIs that allow developers to embed features from other sites into their own pages, z.B. from Twitter or Facebook.
  • Third-party frameworks and libraries that can be added to HTML, which allow web pages and apps to be created quickly.

Since this article is intended to give you a light introduction to the basics of JavaScript, we won’t talk here about the differences between the base of the JavaScript language and the extensions mentioned above. You can learn more about this in detail later in our JavaScript learning area.

Here we will show some basics of JavaScript and you will be able to experiment with some browser APIs. Have fun!

A "Hello World!" Example

The previous paragraph sounds very exciting and rightfully so. JavaScript is one of the most exciting internet technologies and if you start using it, your website will become much more powerful.

However JavaScript is a bit more complex than HTML and CSS. So you will need to start small, and move forward in short, regular steps. To start, we’ll show you how to add JavaScript code to a page to create a "hello world" message!" example (the default in elementary programming examples).

IMPORTANTIf you haven’t followed the previous course this far, download this code sample and use it as a starter.

  1. First, go to your test page and create a new file named main.js . Save this file in your scripts folder.
  2. Then go to the index.html file and add the following element in a new line before the closing</body>- Tag on:

Note : The<script> (en-US) element we have at the end of the<body>-Elements written as the HTML is loaded by the browser in the order it was written in the file. If the JavaScript code is loaded before the HTML page is built, it may not affect the HTML elements that are loaded later on. So it is usually best to include JavaScript code rather at the end of the HTML page.

What happened?

Your headline has been changed to "Hello world" by using JavaScript!" changed. We made this possible by first using a function called querySelector() to get a reference to our heading and storing it in a variable called myHeading. It’s similar to what we did in CSS with the selectors. If you want to do anything with an element, you have to select it first.

Then we set the value of the property textContent of the variable myHeading (which represents the content of the heading) to "Hello world!".

Hint: Both functions you used are parts of the Document Object Model (DOM) API

Programming crash course

The following is a description of some basic properties of the JavaScript language to give you a little more understanding of what’s involved. These features are common to other programming languages. If you understand these basics, you should be able to start programming.

ImportantTry pasting the lines of sample code from this article into the JavaScript console to see what happens. For more details on the JavaScript console, see Discover Browser Developer Tools.

Variables

Variables are containers in which values can be stored. First, a variable is declared with the keyword var, followed by some name under which this variable should be addressed:

NoteEvery command line in JavaScript must be terminated with a semicolon to mark the end of the command line. Do not do this, expect unexpected results.

NoteYou can name a variable almost any way you want, but there are some restrictions to keep in mind (see this article about the rules of naming variables).) If you are unsure, you can check the variable name to check validity.

Note: JavaScript respects upper/lower case – myVariable is different from the variable myvariable . If you run into problems in your code, check for case sensitivity first!

After a variable is declared, you can give it a value:

Both steps (declaring a variable and assigning a value to it) can be combined in one step:

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

After a value is given to the variable, it can be changed later:

Note that variables have different data types:

A structure that allows you to store multiple values in a single reference.

Basically anything. Everything in JavaScript is an object and can be stored in a variable. Keep this in mind as you learn.

Why are variables needed? Well, variables are needed to cover everything interesting in programming. If values couldn’t change, then nothing dynamic could be created, such as personalizing a welcome message or an image displayed in an image gallery.

Comments

You can insert comments in JavaScript code just as you can in CSS:

If the comment does not contain line breaks, then it is often easier to place it after two slashes:

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, followed by some examples you can try in the JavaScript console.

Checks two values for equality and returns true / false (Boolean) as result

Returns the logical opposite as a result; turns a true into a false, etc. In conjunction with the equality operator, it checks whether two values are unequal.

The base expression is true , but the comparison returns false because it was negated:

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

Here’s how to check if myVariable is not equal to 3. The return value is false because myVariable has the value 3.

var myVariable = 3;
myVariable !== 3;

There are many more operators to discover, but enough for now. A complete list can be found in Expressions and Operators.

NoteMixing data types can give unexpected results in calculations. Be sure to use the variables correctly and check that the expected result is returned. For example, type "35 + "25" in the console and look at the result. Did you expect this? Because of the quotes, the values are treated as strings and thus joined instead of added together. If you type 35 + 25, you get the expected result.

Conditions

Conditions are code structures that allow you to check whether an expression is true or false and execute different code depending on the result. The most common type of conditions are if . else. For example:

The expression inside the if ( . ) is the test – this uses the equality operator (as described above) to compare the variable eis with the string S chokolade to see if the values are identical. If this comparison returns true , the first block of code will be executed. If not, this code is skipped and the second block after the else command is executed.

Functions

Functions (en-US) is a way to pack together functionalities that should be reused. Whenever the functionality is needed, the function is called by its name instead of having to rewrite the same code over and over again. You’ve already seen some uses of functions, for example:

The functions document.querySelector and alert are embedded in the browser to be used whenever it fits.

If you see something that looks like a variable name, but is enclosed in round brackets – () – it might be a function. Functions often take arguments to ensure functionality. These arguments are placed inside the round brackets and separated by commas if more than one argument is passed in.

For example, the alert() function creates a pop-up box inside the browser window. This function must be passed a string as an argument to tell the function what to write in this pop-up box.

The good news is that you can define your own functions. In the next example, we write a simple function that takes two numbers as arguments and multiplies them:

Try running this function in the console, then try calling your new function several times:

Note: The return command tells the browser to return the result variable from the function. So it is possible to use it. This is necessary because variables used inside the function are only valid there. This behavior is called scoping. (Read more about the scope of variables.)

Events

To create real interactivity on a website, events are needed – these are code structures that listen for events happening in the browser and then allow you to execute code to react to these events. The most obvious example is the click event fired by the browser when you click the mouse pointer on something. To show this, type the following code into the console and click on the current web page:

There are many ways to associate an event with an element. Here we select the element HTML and set the property of the onclick handler equal to an anonymous (nameless) function containing the code we want to execute when the event happens.

Note that

is equivalent to

It’s just shorter.

Dynamic content for our example website

Now that we’ve learned some basics of JavaScript, let’s put some dynamic content into your first web page so you can see what’s possible with JavaScript.

Switch images

We will add another image to the web page. With some JavaScript code we will switch between the two images when clicked with the mouse.

  1. First pick a second image for your web page. It should preferably be the same size as the image you already have on the website.
  2. Save this image in your images folder.
  3. Change the name of the image to something you can easily remember, we have it ‘firefox2.called ‘png.
  4. Go to your main.js file and enter the following JavaScript code: (Delete the hello world-Example from above)

We create the variable myImage and store in it a reference to our image element( img ). Next we set the onclick -event of this variable equal to a function without name (aanonymous Function). This function says what should happen each time the image is clicked:

  1. We get the value of the src attribute from our image.
  2. We use an if -condition to check if the src -value is the same as the path of our original image:
  1. If the condition is true, we change the src value to the path of the second image, so that this image is now included in our<image> -element is loaded.
  2. If the condition is false (i.e. the image has already been clicked and changed), we change the src value back to the path of the first image, so that when the mouse is clicked again, the original image appears again.

A personal welcome

Next, we add a personal welcome to our website, which can be changed by the user when visiting the site for the first time. The change should be preserved even if the user leaves the page and comes back later. We will also have an option to change the user so that the greeting is changed accordingly.

    In the index.html -file and insert it directly before the<script> (en-US) element, enter the following line of code:

If you open your page in the browser now, the first time you visit, you will be asked for your name and the welcome will be personalized. You can change the name at any time by pressing the button. The personalized welcome is also displayed again when you leave the page and then return to it, because the name is stored in localStorage , in your browser!

Summary

If you followed the instructions in this article, you should now have a website that looks similar to this one (check out our version):

Javascript basics

If you don’t have the same result and can’t find a solution (try to get it working yourself first), then you can check out our code on Github.

Here we have shown only some basics and examples of JavaScript. If you’re interested, learn more about JavaScript in our JavaScript guide.

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: