Learning JavaScript: Functions and Flow

Making programs execute things depending on conditions.

Not so different from math functions.

Functions

Functions are what give life to programs. They are pieces of code with instructions to execute as many times as necessary. Function syntax isn’t complicated.

//Basic function structure
function name (argument) {
[body]
}
function hello () {
console.log("Hello!");
}
hello(); //Prints "Hello!"

The name is how you identify the function and call it. The parentheses hold the function’s parameters/arguments that will run in the body. Note not all functions need arguments. The code to run is inside the curly braces ({}) and is the function’s body.

Now, you can use the same function with different things to run using parameters. If you want a function to give anyone a specific greeting and say their name, you can use:|

function greetingTo (greeting, name) {
console.log(`${greeting}, ${name}!`);
}
greetingTo("Hello", "Sofia"); //Prints "Hello, Sofia!"
greetingTo("Sofia", "Hello"); //Prints "Sofia, Hello!"

Note in the second call how much the order of arguments is important. That can be troublesome depending on the function. You can also do it without interpolation, using concatenation instead.

function greetingTo (greeting, name) {
console.log(greeting + ", " + name + "!");
}
greetingTo("Hello", "Sofia"); //Prints "Hello, Sofia!"

It runs faster than interpolation but gets hard to type as you need to insert commas, spaces, etc.

Concatenation is like Zoom: faster, but not good.

Returning values

Then you have return. Not only it gives a value, but it also exits the function if it’s inside one.

function noHello () {
return;
console.log("Hello!"); //Won't print, but returns undefined
}

return and console.log seem to do the same besides return ignoring code after it. But console.log has its own return that gives undefined. This is the default value returned if you don’t specify something else.

console.log("Hey."); //Prints "Hey" and returns undefined
function number() {
return 5;
}
number(); //Returns 5

Controlling the program flow

After functions, it was time to make programs more fluid. Using the right resources, it’s possible to run code only in certain situations. This makes a program give different results according to the conditions established.

Comparing values

Comparisons are important because they help check the conditions. Most of them come straight from math.

5 > 4; //Checks if 5 is bigger than 4
3 < 2; //Checks if 3 is less than 2
10 <= 5+5; //Checks if 10 is less than or equal to 5+5
20 >= 2*10; //Checks if 20 is bigger than or equal to 2*10

Since JavaScript uses the equals sign (=) to assign variables, there’s another way to check if values are equal.

5 == 5; //Returns true
15 === 14; //Returns false
12 == 13; //Returns false
3 === 3; //Returns true
7 == "7"; //Returns true
7 === "7"; //Returns false

The difference between the signs is in the last two entries. The == only sees the same number, but === also checks the data type. 5 is a number and ”5” is a string, even if they represent the same thing.

JavaScript can also compare strings but in a quite strange way. Think of each letter as a number and their position in the string having higher or lower value.

"a" > "d"; //Returns false
"q" < "x"; //Returns true
"C" > "c"; //Returns false
"F" < "f"; //Returns true
"ca" < "c"; //Returns false because "a" is higher than no character
"caaa" === "caaa"; //Returns true
"cbaa" > "caab"; //Returns true

Combining comparisons

To make things more specific, it’s possible to combine comparisons using the logical operators && and ||. The first means “and”, while the second means “or”. && only returns true if both statements are valid, but || returns true even if just one is true.

5 > 4 && 3 > 2; //Returns true
10 > 2 && 5 <= 3; //Returns false
5 > 4 || 3 > 2; //Returns true
10 > 2 || 5 <= 3; //Returns true

Combining comparisons can get a bit complicated.

5 === 5 && 1; //This returns 1
My genuine reaction to that witchcraft.

This happens because JavaScript:

  • Reads from left to right.
  • Evaluates only the necessary.
  • Returns the last thing read.
5 === 5 && 1; //JavaScript evaluates the first statement
true && 1; //This is the same as the previous

Now there’s nothing to test on either side. So it returns the last thing read because the comparison wasn’t possible. Result: 1. Check this example:

5 === 4 && 0; //Returns false. The first statement is enough

It can perform enough to get a result. Because the first statement is false, whatever is to the right of && doesn’t matter. The result will be false anyway, so JavaScript just gives it right away.

Things can get just as weird with ||. Check this:

220 < 150 || "alphabet"; //Returns "alphabet"

The first statement is false, but the second can change the result in a comparison with ||. Then it realizes there’s nothing to do and just returns “alphabet”. Now, or this one:

155 > 73 || "treasure"; //Returns true

JavaScript has enough with just the first statement, so “treasure” is ignored.

Checking if conditions are true

Functions give life to programs and comparisons can give different results. But you need to check the conditions. That’s where conditional statements enter. Their syntax resembles functions:

if (condition) {         //If the condition is true, it executes the
[body] //body. If not, it ignores the code
}
if (condition) {         //If the condition is false, it executes
[body] //something else.
} else {
[body]
}
if (condition) {         //If the first condition is false, it
[body] //checks the second and so forth
} else if (condition) {
[body]
}

Matching values

When you have many possibilities, it’s better to use switch. It acts as a big if-else if-else chain.

switch(value) {
case value:
[body]
break;
case value2:
[body]
break;
default:
[body]
}

The code checks the value in switch(value) and compares to the value in case. If a match happens, the code runs and break ends the switch. If there are no matches, default takes action. If switch is part of a function, it’s possible to use return instead of break:

function mood(humor) {
switch(humor) {
case "happy":
return "Dance!";
case "sad":
return "Eat ice cream.";
default:
return "Humor unknown.";
}
}
mood("happy"); //Returns "Dance!"
mood("angry"); //Returns "Humor unknown."

If you want the same code to run for more than one case, it’s possible to do something like this:

function checkNumber(number) {
switch(number) {
case 1:
case 2:
case 3:
console.log("Less than four.");
break;
default:
console.log("Not supported.");
break;
}
}
checkNumber(2); //Prints "Less than four."

Upper and lower case

Then the lesson got into two methods (kind of functions): .toUpperCase() and .toLowerCase(). As the names imply, one makes all letters upper case and the other makes them lower case.

var bye = "Bye, Goku!";
var lowBye = bye.toLowerCase();
var highBye = bye.toUpperCase();
console.log(lowBye); //Prints "bye, goku!"
console.log(highBye); //Prints "BYE, GOKU!"
“Bye!”

Sorry if there’s something wrong or missing, but I write as I learn, so there will be gaps. I appreciate any sugestions! Tomorrow: scope!