JavaScript basics – extended tutorial

JavaScript Basics

JavaScript is dynamic, interpreted programming language and together with HTML and CSS is the core of the World Wide Web. You can do almost whatever you want with JavaScript. This tutorial covers the basics and some more advanced topics like objects, events, arrays. Also we will focus more on examples and how to do stuff as learning by example is the best way to master programming.

To add JavaScript code to HTML page you can add it within¬†the <script> …¬†</script> tag. Here is one very simple web page:

<html>
    <head>
        <title>JavaScript Tutorial</title>      
    </head>
    <body>
        <script>
            console.log('Hello JavaScript!');
        </script>
    </body>
</html>

This will show the following row at browser console:

Hello JavaScript!

F12 opens developer tools in most browsers and from there you can choose console.

Now writing to console is boring, so we can add this row to the page itself:

<html>
    <head>
        <title>JavaScript Tutorial</title>      
    </head>
    <body>
        <script>
            document.write("Hello JavaScript!");
        </script>
    </body>
</html>

Refresh your page and you will see this message in your browser window.

Also you can use alert:

<script>
   alert("Hello JavaScript!");
</script>

As you can see here I omit the html part, you need the same html page as above but I won’t add it on every example from now on.

JavaScript syntax

Variables

var x = 3;
var y = 0.5, z = "I am a string";

Keep in mind that JavaScript is case sensitive so there is a difference between myVar and MyVar for example.

Operators

The operators in JavaScript are similar in use to most of the other programming languages. You have arithmetic, comparison, logical, assignment, and conditional operators.

Statements

or lets do simple math now

<script>
    var x = 3;
    var y = 5;

    var sum = x + y;
    document.write(sum);          
</script>

Data types

The simplest way to explain them is through example

// number
var x = 3;          

// boolean
var b = true;

// Array
var ar = [1, 2, 3, 4, 5];

// String
var text="This is some string";

// Object
var myObject = { color: "blue", speed: 30 };

If, if … else, if .. . else if …

<script>
    var b = 3 + 5;

    if(b > 5) {
        console.log("Great!");
    }

    if(b < 3) {
        // b is 5 so (b < 3) is false and this will be omitted
        console.log("This won't appear in console");
    } else {
        // so it will continue here
        console.log("This will appear in console");
    }

    if(b < 1) {
        console.log("Too low");
    } else if(b < 3) {
        console.log("Not here");
    } else {
        console.log("This will appear too!");
    }
</script>

The output of this code:

Great!
This will appear in console
This will appear too!

Loops

while
We use while when we want to loop through something. Simple example with while:

<script>
    var i = 1;
    while(i < 10) {
        console.log(i);
        i = i + 1; // you can change this to i++;
    }
</script>

And the output in console will be:

1
2
3
4
5
6
7
8
9

do .. while

Lets do the same code with do while:

<script>
    var i = 1;
    do {
        console.log(i);
        i = i + 1;
    } while(i < 10);
</script>

The output now will be a bit different:

1
2
3
4
5
6
7
8
9
10

The reason is that the code is executed one more time before the check.

for loop

Here is the same example with for loop:

<script>
    for(var i = 1; i < 10; i++) {
        console.log(i);        
    }
</script>

Again the output will be the numbers from 1 to 9.

for … in

This is used to loop through object’s properties or array’s items. Here are examples with array and an object:

With array

<script>
    var arr = [1, 3, 5, 7, 9];
    for(var id in arr) {        
        console.log(arr[id]);        
    }
</script>

With object

<script>
    var obj = { color: "red", shape: "square", height: 9};
   
    for(var item in obj) {        
        console.log(item + " is " + obj[item]);        
    }
</script>

And the output:

color is red
shape is square
height is 9

break

The break statement is used to exit from loops early.

<script>
    for(var  i = 0; i < 10; i++) {
        console.log(i);        
        if(i > 1) {
            // we will exit from the loop
            break;
        }
    }
</script>

This will output:

0
1
2

continue

This statement is a bit more fun. It makes the interpreter to immediately start the next iteration of the loop and omit the execution of the code after it. Here is an example:

<script>
    for(var  i = 0; i < 10; i++) {
        if(i < 5)
            continue;
        console.log(i);        
    }
</script>

And the output:

5
6
7
8
9

Functions

Function is a block of code that can be called from anywhere in your code. Functions perform particular tasks and allow you to divide the logic into small chunks.

Function syntax

function fname(p1, p2, p3, ...) {
    // function body
}

P1, p2, p3 sa function parameters. Here is an example function that adds two numbers and returns the result:

function sum(a1, a2) {
    var result = a1 + a2;
    return result;
}

Anyway this code above won’t do anything for now. To run the code we need to call the function:

// ourVar will become 5
var ourVar = sum(2, 3);
console.log(ourVar);

Function parameters

In the above example a1 and a2 are function parameters. Functions can take multiple parameters separated by comma and use them in your body.

<html>
    <head>
        <title>JavaScript Tutorial</title>      
    </head>
    <body>
    <script>
        function hello(name) {
            document.write("Hello " + name);
        }
        hello("JavaScript");
    </script>
    </body>
</html>

Return statement

Return statement is used when function needs to return value. Example:

function multiply(a1, a2) {
    var result = a1 * a2;
    return result;
}
var n = multiply(5, 3);
var m = multiply(10, 20);

Arrays

An array is used to store multiple values in a single variable.

Syntax

Here are two ways to create an array:

var arr1 = new Array(1, 2, 3, 4, 5);

var arr2 = [1, 2, 3, 4, 5];

Add and remove elements from array

push adds one or more elements at the end of an array
pop removes the last element from an array and returns it

Example of adding and removing elements with push and pop:

var arr1 = new Array(1, 2, 3, 4, 5);

var arr2 = [1, 2, 3, 4, 5];

arr1.push(6); // Now arr1 will be [1, 2, 3, 4, 5, 6]

var last = arr2.pop(); // now arr2 will be [1, 2, 3, 4] and last will be 5

Accessing nth element in array:

arr[0]
arr[3]

Getting array length is easy with the array.length property

document.write(arr1.length);

Iterating array

Here is simple example of iterating through array elements in javascript.

var arr1 = new Array(1, 2, 3, 4, 5);

for(var i = 0; i < arr1.length; i++) {
    document.write(arr1[i]);
}

Sorting arrays

Sorting arrays in javascript is easy with the sort method. Here is how you use it.

var colors = ["red", "blue", "white", "yellow"];
// alphabetically
colors.sort();

Sort method sorts items alphabetically, so if you need to sort them according to something else you need to provide a function to it. This will be explained in another tutorial as this one is beginners level.

JavaScript Objects

In javascript an object is design as collection of properties and a property is a relation between a key and a value. When the value is a function its known as a method.

Objects basics

Example:

var cat = { name: "Tobby", age: 5, breed: "Balinese" };

var name = cat.name;

document.write(cat.breed);

Leave a Reply

Your email address will not be published. Required fields are marked *