Basic Syntax

In this article we will learn all syntax you need to write JS well.

Literals

The simplest data you can work with are numbers and strings. It works just as you might expect it to work.


console.log(2);                        //-> 2
console.log(2 + 2);                    //-> 4
console.log(2 + 3 * 1.5);              //-> 6.5
console.log("foo");                    //-> "foo"
console.log("foo" + "bar");            //-> "foobar"
console.log("foo bar".indexOf("o"));   //-> 1

You can store evaluation results in a variable and reuse it later.


let str = "foo bar";
let i1 = str.indexOf("o");
let i2 = 3;
let i3 = i1 + i2 + 2;

Functions

You often want to separate some piece of code to reuse later. This is what functions are for. It's mini program where you pass some input and expect some output.


let sum = (a, b) => {
    return a + b;
};

console.log(sum(2, 3)); //-> 5

Control structures

In all examples that we have before lines were executed one by one, but you might not always want that. Based on condition you might want alternate lines or repeat execution.


let counter = 1;
while (counter < 10) {
    if (counter % 3) {
        console.log("dividable by 3")
    } else {
        console.log("non dividable by 3")
    }
    counter = counter + 1;
}

Putting it all together

Let's say you need to do 10 studies and report how much measured temperature different from expected

//generates some random number from -20 to 20
let measureTemperature = () => {
    return Math.round(Math.random() * 40) - 20
};

let expectedTemperature = 2.3;
let totalStudies = 10;

let study = 0;
let difference = 0;

while (study < totalStudies) {
    difference = Math.abs(expectedTemperature - measureTemperature());
    study = study + 1;
}

console.log("Average difference:", difference / totalStudies);

Homework

A good exercise is printing out Multiplication table. You can practice all basic syntax with it without spending too much time.

const generate = () => {
    //TODO: you code goes here
    return "";
};

let expected = `
1  2  3  4  5  6  7  8  9 
2  4  6  8 10 12 14 16 18 
3  6  9 12 15 18 21 24 27 
4  8 12 16 20 24 28 32 36 
5 10 15 20 25 30 35 40 45 
6 12 18 24 30 36 42 48 54 
7 14 21 28 35 42 49 56 63 
8 16 24 32 40 48 56 64 72 
9 18 27 36 45 54 63 72 81 
`;

if (generate() == expected) {
    alert("Task done");
} else {
    alert("Not completed yet");
}

Content