Top image

WEB design and programming - HTML | CSS | Java Script | PHP

JavaScript

JavaScript: What are the Function, Conditional Statement and Loop?

In previous post, we’ve looked a general concept of JavaScript. This chapter is going to be more practical content and you can find out the crucial syntax which is the Functions, Conditional Statement and Loops.

Functions

Let’s observe more detail about the Functions.
Why are the functions quite important in all over programming? How do they work?

A function is like an instruction manual that has orders to a computer.
Do you remember that we’ve learned about Variables which can store the values in the previous post? Though they can maintain only values, the functions are the things which are grouped method of processing with putting a specific name and we can reuse it over and over whenever we want to perform the task again. Meaning, that makes code more organized and clear.
Let’s take a look how we write a syntax of the function.


//Function Declaration
function calc() {
  let num = 2 * 3; 
  console.log(num);
}

//Function Expression
let calc = function() {
  let num = 2 * 3; 
  console.log(num);
};

//Arrow Function
const calc = () => {
  let num = 2 * 3; 
  console.log(num);
};

I’ve written three of typical way to declare the function since there are a couple of syntax in JavaScript, but they represent a same content. You can use one whichever you want. However I’m going to use Arrow Function to explain because ES6 which is newer version of JavaScript prefer to use it. Let’s dissect it together.

Break down (Arrow Function)

・First of all, it is to need to declare a variable with const or let keyword.
・If there’s no parameter or more than two, the parentheses, (), are required.
・After the parentheses, or parameter name, it needs to be put the arrow, =>.
Line of 15 – 18, which is the function body, the block of statements inside of that required to perform a specific task, enclosed in the function’s curly brackets, { }.
・Also, there are important concept in the function, which are parameters, argument and return values. NEXT

To call the function, we need to put the function name followed by parentheses.


calc(); // output 6

Here is the point. Function won’t be executed till we order to computer.
Though you need to invoke the function name each single time once you want to use it, it’s up to figuring out to make a way work more efficient.

Also, as I’ve mentioned above, to use the functions more efficiently, it’s essential to manipulate those thing: which are parameters, argument and return values.
However, it would take a long line to figure them out, I’m going to introduce them the following article!

Conditional Statements

if…else


Do you notice we often get circumstances that we want to select more than 2 choices in daily life. In programming, that’s the time to appear If…else keyword which will be a statement that performs either of tasks based on conditions.

In the sample above case, the tasks are “I’ll make doughnuts!” or “I won’t make anything.”, and the condition is “the case of hungry” which is after the if keyword.
In the condition would be true, the first decision will be executed, and if it’d be false, the block of else code will run to perform the second task.

else if


If you had more conditionals, you could use else if keyword between if and else. You could make it as many else if keyword as you want, as long as you would like to make more complex condition and to have multiple outcomes.

So, let’s take a look what a code going to be like if we write an actual statement.


let hungry = 0;
let diet   = 1;
if(hungry){
 console.log("I'll make a doughnuts!");
} else if(diet) {
 console.log("I'll put up with carb ... ");
} else {
 console.log("I won't make anything.");
}

In this case, the output will be else one that say “I’ll put up with carb. Let’s make boiled eggs!“.

Break down

・The conditional statement is judged based on that a condition will be either true or false.
・If the condition would be judged to true, then its statement will execute.
・”0″ would be judged to false, so the next condition is to be checked.
・Once the condition evaluate to true, the statement which is belong that condition will run and the rest of the conditions are not evaluated.
If none of the conditions evaluated to true, then the code in the else statement would be executed.
・We can use comparison operators and logical operators as a condition to make a more complex conditional statement.NEXT

In programming, a concept of binary decision would be a basic thought. If you wanted to create something with program, it would be a good practice that you think all over the things based on the algorithm.
Algorithm is a way of thought to carry out with what kind of procedure so that derive the tasks to realize what you’d like to do.

Say, when you wanted to throw garbage of house away, you would need to separate kinds of them and then you might need the boxes for each of them. What would you do to get the boxes? You might ask the neighbors that they have some of it, or, you might pick a free box up on the street, whatever.
Like that, you can imagine your own if…else based on Algorithm in your head whenever!

For now, we’ll move to the next thing we’re going to learn.

Loop

When we want to iterate some block of code, we can use Syntax of loop.
for loop is the one of iterator object, that provide us to run repetitive tasks.

What if you want to prepare honey to each single of fruits like the image above? A simplified code would look this below.


let fruits = ['apple', 'orange', 'grape', 'peach'];
let honey  = 0;
for (let i = 0; i <= fruits.length; i++){
	honey = i;
}
console.log('I have ' + honey + ' honeys!'); // Output "'I have 4 honeys!"

Break down

Line of 2, I’ve put the variable named “fruits” as an Array.
Line of 3, I’ve put the variable named “honey” which it started by 0 as well.
Line of 4, the for keyword has written followed by parentheses, ().
・There are three expression inside of it and each them are separated by semicolon, ;.
・The inside of parenthesis, the part of let i = 0; is called Initialization which can be processing to initialize before each single iterator.
・The inside of parenthesis, the part of i <= fruits.length is called Stopping condition that is to stop the iterator once the condition evaluates to true.
・The inside of parenthesis, the last part, i++ is called as Iteration statement that iterate to its own. In this case, the value of i will be increased by 1 after each loop.
Line of 5, I’ve put that honey is equal to i. Meaning, a result will be 4 since i which is increased one by one was iterated the time as many as the Array’s length.

If you missed to use the comparison operator correctly, the output would be not what you want have. like this below:


let fruits = ['apple', 'orange', 'grape', 'peach'];
let honey  = 0;
for (let i = 0; i <= fruits.length; i++){
	honey += i;
}
console.log('I have ' + honey + ' honeys!'); // Output "'I have 10 honeys!"

As you can see, I’ve changed the comparison operator, from = to += it’s inside of curly brackets and it output the number of honey as 10! What’s going on?
Let’s take a closer look at the movement of the loop with the console logs.

movement of the loop

Between the inside of body of for loop, If we put the code like:


console.log(i);

We can see the detail of that movement on the console which is known as a developer tool that any browsers have, and it looks like:

Why does it output 10 eventually?

In this case, the action of honey += i will be like this.

x += y means x + y = z(result), so it repeats honey + i = 〇(result) as many time as stopping condition had.
・After the second time iteration, the figure of honey will be a total of them honey + i before one.
・In addition, it be added the number of i in the current loop has on it and it will be the next number of honey’s one.
We have 5 rounds to iterate since stopping condition evaluates by less than or equal to Array’s length, so we get number 10 as final result.

To get make sense for the image of the loop is a bit tough thing for beginners who have never learn to program. However, you will get used to it while creating the actual program.

Actually, there are more suitable method to iterate kind of that processing like forEach method or so on. I’ll tell you about a detail of it on the following article!

Review

Let’s take a review what you’ve learned in this article.

Function is a reuseable block of code to perform a specific task concisely and we can invoke them as many time as needed.

Conditinal Statements is to make a binary decisions and to execute the outcomes based on that the condition evaluate to “true(Truthy)” or “false(Falsy)” or otherwise.

Iterator is Loops that perform repetitive actions so that we won’t code same one over and over again.

There are way more method and objects in JavaScript which I haven’t introduce today. Keep in mind it till I’m going to post the next article.

▼ Check out the previous post
https://achiachi.sakura.ne.jp/awp/386/