JavaScript Basics: Understanding Conditionals, Loops, and Functions.

Aliyah SoliahAliyah Soliah
7 min read

On my learning journey in Backend web development, today's article will be on my knowledge about some of the fundamentals of JavaScript.

Join me as we step into the world of coding and understand the basic concepts.

What are conditionals?

Like we as humans make decisions daily, matters like what to eat, what to wear, and what to do is decided upon. Computers also perform different tasks based on different conditions.

Conditionals control behavior in your code and conditional make decisions ns in your code.

Conditional statements are used to carry out different tasks based on conditions.

There are two primary conditionals in JavaScript, we have:

  • If…else statement

In JavaScript, a conditional if…else statement could be written as:

If (condition) {

The task is to be performed if the condition is true.

} else {

The task is to be performed if the condition is false.

}

  • Switch statement

A switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.

switch (expression) {

case value1:

// code block break;

case value2:

// code block break;

default:

// code block

}

For example, below is a switch statement code that uses a weekday number to calculate the weekday name. By giving each day index of 0-6

switch (new Date().getDay()) {

case 0:

day = "Sunday";

break;

case 1:

day = "Monday";

break;

case 2:

day = "Tuesday";

break;

case 3:

day = "Wednesday";

break;

case 4:

day = "Thursday";

break;

case 5:

day = "Friday";

break;

case 6:

day = "Saturday";

}

UNDERSTANDING LOOPS.

Having to write the same lines of code multiple times gets tiring and boring. Let’s say I want to print, "I love Techy Jaunt" 10 times. Writing the command code for print might not be a hard task. But what if I have to write it a hundred times? That would be a difficult one.

Loop makes these tasks easier. Loops are statements that repeat an action for a specified number of times. They are used when a sequence of instructions is to be executed multiple times.

Looping is repeating a sequence of instructions until a condition is satisfied. For the example above where I have to print "I love Techy Jaunt" 10 times, there is a maximum limit of 10, which is the sequence of instructions.

There are different examples of loops like: for, do…while, for…in, while, and for…of. The two most common loops in JavaScript are:

  • for loop

This consists of three main parts:

  • Giving initial value to the variable.

  • Condition (e.g. i<10 )

  • Counter statements: used to increase or decrease the variable value so that the conditions are satisfied.

Once these parts are put in place, the task can be executed until the condition is satisfied.

To code the example of printing “I love Techy Jaunt” ten times, we will have:

var i ;

for(i = 1; i < 10; i++){

document.write(“I love Techy Jaunt”);

}

  • Do...while loop

This loop consists of two main parts:

  • Do: the code to be executed is written here until the condition is satisfied (it's written inside a curly bracket).

  • While: the condition to be satisfied is written here (in a round bracket)

i.e

do{

block of code to be executed

}while(condition);

Applying the above to our example we will have:

var i = 1;

do{

document.write(“I love Techy Jaunt”);

i = i + 1;

}

while(i<=10);

Without the ‘while’ condition, this code would continue to run until the system is out of memory. The computer would continue to perform the task repeatedly since there is no instruction telling it to stop, an infinite loop.

What is a function?

A function is a block of reusable code that can be used anywhere in the program. It eliminates the need to write the same code again and again. A function can only be used when it is called. Until then, the function will sit ideally. So first, we define a function i.e. to create a function. Then we call and use the function.

DECLARATION OF A FUNCTION

A JavaScript function is defined with the function keyword, followed by a name, followed by round brackets ().

Function funtionname(){

Code

}

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The function name of a named function should suggest/hint what the function does.

The reusable code to be executed, by the function, is placed inside curly brackets: {}

Calling a function is as easy as writing the name of the function followed by opening and closing round brackets.

Parameters are used to put in different values in the function so that it will print the result. They are passed while calling the functions and later those passed parameters can be manipulated inside the functions.

In JavaScript, objects and functions are considered variables. The limit till the JavaScript variable and functions are accessible in a program is the scope of the variable and function.

Local JavaScript Variables:

Variables that are declared within a function become local to the function and hence its scope is limited within the function. It means that the variable will be accessible only within the function. A lifetime of this variable begins when a function starts and ends when the function ends.

Syntax :

function myFunction()

{

var firstName = "Many";

// firstName accessible

}

// firstName not accessible

// function arguments are local to the function.

function greet(a,b)

{

//scope of variables a & b within the curly braces of the function

}

Global JavaScript Variables:

Global variables are the variables that are declared outside any function. Such variables can be accessed anywhere in the program.

var personName;

function myFunc()

{

//personName accessible

}

//personName accessible

In the example above, you can see that the variable personName is declared outside a function. Thus its scope is the entire program and can be accessed anywhere in the program. If you assign a value to a variable that has not been previously declared, its scope automatically becomes global.

Example :

function hello()

{

personName = "Mary";

}

In the above example, a value is assigned to personName without it being declared. In such a scenario, the variable personName becomes global. Thus the scope of a global variable is the entire application. The lifetime of a global variable is as long as the application is running.

JavaScript Nested Functions:

In JavaScript, we can write nested functions. It means we can have functions within a function. In such a scenario nested functions have access to global variables. Also, the functions declared inside a function have access to the variables of the parent functions.

For example, suppose if a function a() has a nested function b() and var x is declared in function a(), then var x is also accessible in function b().

Example :

function add()

{

var counter = 0;

function plus() {counter += 1; document.write(counter+"

");}

plus();

return counter;

}

add();

In the above example, counter=0; is executed every time we call add(), thus the value of the variable always resets to zero. This will not prove helpful if we need to implement a counter in our application. Closures provide a solution to this problem.

Example :

<!DOCTYPE html>

<html>

<body>

<p>Closures Example</p>

<button type="button" onclick="myFunc()">Counter </button>

<p id="closuredemo">0</p>

<script>

var increase= (function () {

var counter = 0;

return function () {return counter += 1;}

})();

function myFunc(){

document.getElementById("closuredemo").innerHTML = increase();

}

</script>

</body>

</html>

Closures use the concept of self-invoking functions. In the example above you can see the variable increase has a self-invoking function. This function runs only once. It initializes the counter variable to zero and returns an expression.

Hoisting

Hoisting is JavaScript's default behavior of moving declarations to the top.

JavaScript declarations are hoisted.

There are many more cool stuff to learn under JavaScript and backend development as a whole, and I can't wait to discuss them with you as I learn them.

Share your thoughts on conditionals, loops, and functions. Let's continue to grow and learn together in this dynamic landscape.

References:

Wikipedia

Programming hub

W3schools

1
Subscribe to my newsletter

Read articles from Aliyah Soliah directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aliyah Soliah
Aliyah Soliah