JavaScript (3) Blocks, Conditionals, Loops and Functions

1. Blocks:

We often need to group a series of statements together, which we often call a block. In JavaScript, a block is defined by wrapping one or more statements inside a curly-brace pair {}.

var a = 10;
{
    console.log(a);
}

This kind of standalone general block is valid, but isn't as commonly seen in JS programs.


2. Conditionals:

var a = 10;

if (a > 5) {
    console.log("a is larger than 5");
} else {
    console.log("a less than or equal to 5");
}

The if and else statements defines two blocks which is corresponding to the different condition.


3. Loop:

for(var i=0; i<=10; ++i) {
    console.log(i);
}

The value of i keep increasing until the statement i<=10 return false.


4. Functions:

A function is generally a named section of code that can be "called" by name, and the code inside it will be run each time (e.g. console.log() is a built-in function).

var num = 10;

var AddOneandPtrint = function(num) {
        num = num+1
        console.log(num); 
}

AddOneandPtrint(num);
console.log(num);

The example shows that the function is pass by value which means modify "num" in the function does not change the value of "num" outside (we will need to discuss this concept more precisely).


Reference

[1] Kyle Simpson, You Don't Know JS Series, O'Reilly Media (2014)

留言

熱門文章