info@themewerk.com

Javascript basics: variables, data types, functions

Javascript was once a small programming language – the old hands among programmers would now say: a small scripting language. Over time, Javascript has become extensive to better realize more complex applications. Nevertheless, Javascript is still easy to learn.

However, there is a catch: If you want to program Javascript, you have to know the basics of HTML and also CSS inside out.

Editors and browsers for the first steps with Javascript.

For the first attempts we need a HTML file and a simple program editor (e.g. Notepad on the PC or TextEdit on the Mac). If you prefer more support from the code editor: Brackets is a free open-soure editor for HTML, Javascript and CSS with an instant preview.

Which browser is best? Modern browsers are all state of the art. The annoying differences are water under the bridge until even small cuts in IE11.

The first javascript program

Just as the headline sits inside an h1 tag and text inside p tags, Javascript sits inside script tags. Like HTML, Javascript is plain text, does not need to be compiled (translated), but is executed directly by the browser step by step.

<!DOCTYPE html>
<html>
<head>
    <title>Javascript basics</title>
</head>
<body>
<h1>A very simple HTML file</h1>.
<p>A very simple HTML page.</p>
<p>Here there is a heading, text and an unordered list.</p>
<ul id="list">
    <li>Header in h1 tag</li>.
    <li>text in p tag</li>
    <li>An unordered list with three li elements.</li>
</ul>

<script>
    alert ("Hello world!");
</script>
</body>
</html>

There are many aspects to where a script call can be placed in the HTML file. For starters, it is easiest to place the script tag with the Javascript instructions at the end of the HTML file before the closing body tag.

At this point the HTML is loaded and Javascript can access all elements.

Javascript Hello World

The output of “Hello World” is the classic introduction to programming, whether Javascript, PHP, Java or C.

The HTML file is stored in a local directory and called in a browser: The browser executes the script and the alert statement plays a small dialog box. The dialog box shows the text enclosed in round brackets inside the quotation marks of the alert command.

Dialog boxes: alert, confirm, prompt

Javascript dialog boxes are small windows – message boxes that the browser superimposes on the page window when alert, confirm and prompt are called.

alert
plays a short text
confirm
plays a query that the user can confirm or reject (cancel).
prompt
also plays a prompt, and additionally a field for user input.

Modern web design hardly uses these dusty old dialog boxes anymore. There are more elegant methods today. But for the first steps with Javascript, dialog boxes or modal windows are intuitive, because they show a quick response.

<p id="conf">Confirm</p>

<script>                                 
let txt; // javascript variable
document.getElementById("conf").onclick = function () {
    let result = confirm ('Please confirm or cancel');
    if (result === true) {
        txt = 'Has been confirmed';
    } else {
        txt = "Was rejected";
    }
}
</script>

The most important concepts to get started:

A Javascript variable can take on different values depending on the situation.

document.getElementById(“conf”) almost explains itself: This is how Javascript gets elements of the web page.

alert(), confirm() and prompt() are ready-made Javascript functions.

innerHTML replaces everything inside an HTML element

The quotation marks must be, but both double and single quotation marks may be used – but always as a pair!

onclick notices when the user clicks on an element. The element in this example is the p element with “confirm”.

What is the purpose of the triple equals sign? A single equals times assigns a value to a variable. A double or triple equals sign tests whether the values on both sides are equal, and assigns nothing.

Instructions, commands

Javascript statements are commands that are usually written on one line and ended with a semicolon.

Javascript statements tell step by step what the script should do:


Set the heading h1 in color:

document.querySelector(“h1”).setAttribute(“style”, “color:firebrick”);

Hide the unordered list with id “list”:

let list = document.getElementById(“list”);
list.setAttribute(“style”, “display:none”);

Show a button with the text “Show list” instead of the list:

let button = document.createElement(‘button’);
button.innerHTML = “Show list”;
document.querySelector(‘body’).appendChild(button);

Show the list when the user clicks the button:

button.onclick = function () {
list.setAttribute(“style”, “display:block”);
button.setAttribute(“style”, “display:none”);
}

Even if the pseudo-code sounds simple: many of these statements are realized in Javascript by several commands, because Javascript needs hair detailed commands.

The prefix document is the entry point to the HTML document – see DOM: Document Object Model for more information.

querySelector finds the first tag of type “h1”.

let button defines a variable with the name “button”. Javascript uses variables to store values. With the name “button” the script can directly address the freshly created button element.

Functions and curly braces

Functions are a block of several statements that belong together – the curly braces mark the beginning and the end of a block.

function paintItGreen () {
let paint = document.getElementById(“paint”);
paint.innerHTML = “Now in green!”;
paint.setAttribute(“style”, “color: green”);
}

Functions are not executed immediately, but only when they are called.

window.addEventListener(“click”, paintItGreen);

When the web page is read, the browser skips all the function’s statements. Here, the instructions of the function should be executed only when the button is clicked.

Again and again, instructions are executed only under certain conditions. Even then, curly braces indicate a block of related statements.

Where to put the script?

In such a simple small HTML document, the script tag with the Javascript instructions can certainly be placed at the end of the document – before the closing body tag. The script tag could even be placed in the middle of the HTML document – the main thing is that it is called only after the h1 tag and the list have already been loaded by the browser.

With complex scripts, however, the HTML source code would become confusing, and debugging would be tedious.

Scripts can be swapped out to an external javascript file and will be loaded with the src attribute of the script tag.

The script statements in the external script file do not sit in a script tag.

Events – intercept user actions

The script – whether in script tags or in an external script file – can also be loaded in the head element of the HTML document. Then statements must not be executed until the browser has loaded the addressed elements.

An EventListener takes care of that – a javascript method that reports events like page loading to the script.

Just as there is a mechanism that intercepts the loading of the document in the browser window and reports it to the script, the script can be notified when the user clicks on a link, on a button, or on an image (or touches an element with a finger on a cell phone or tablet).

This mechanism is called event handling.

onclick registers an event – the event that the user clicks on the button. Javascript provides a long list of events: onclick, ondblclick (when the user double-clicks), ontouch (when the user touches an element with a finger on a touch device), onkeydown (when the user presses a key on the keyboard), onscroll, onload (when the element is loaded in the browser) and many more.

If nothing happens …

If the web page does not respond to the javascript, there is an error. Typed wrong? If a command is misspelled – e.g. alter instead of alert or Alert (Javascript is more case sensitive than any Teacher), there is a syntax error. Syntax errors are relatively easy to find.

The first help for javascript errors comes from the browser’s console. All modern browsers today have a Javascript console. It is called up slightly differently in each browser, but whether IE, Edge, Chrome, Safari, Opera or Firefox: the browser console helps with troubleshooting.

What is the next step?

There is no order to learn a programming language systematically. Someone who has already programmed and wants to write a program with a new programming language already has a way in mind and only needs the syntax for the data types and statements of the new programming language.

If you are learning programming and scripting for the first time, you may have an idea for an application and now need to figure out how to turn your idea into a program. To do this, the idea must be broken down into the smallest steps. Programming is like building a wall from small tesserae.

Most beginners look for a working script for their task and adapt it to their requirements – learning by doing or learning from practice.

Top