DEV Community

Cover image for Functions
Edita Haroyan
Edita Haroyan

Posted on

Functions

Hello my naive friend who thought this was a safe place for people that dislike functions. Functions spread like covid so they got their way to the world of programming aswell. Let's take a look at them.

What is a function?
Well, think of it as a machine that will do a its thing when given a coin. Our machine is the function itself, the coin is "calling" it. Every time we call the function it will do some task we assigned it to. Those tasks are called arguments. They can be anything. We can make a function that will print "you're gay" each time we call it or a function that will calculate the product of two numbers.

Here are the examples

Image description

Image description

Now, what can we do with functions? Well, quite a lot.
Let's look at the easiest one

1 . Return

Image description

2 . Booleans

Image description

3 . If

Sometimes we need to let the function do more than one thing under certain conditions. Here's when we use IF

Image description

As you can see, we gave it two conditions, and for each one it did different things

4 . Equality Operations

With IF we can check equality of pieces of data

Image description

Here we were able to check when something is equal to 23 or not. We can also use this method to find if the value is greater or smaller than our number (">" strictly greater, "<" strictly smaller, ">=" greater or equal, "<=" smaller or equal)

5 . AND and OR operations

We can also command the function to do its task only when both conditions are met. That's AND operation

Image description

The OR operation, on the other hand, just needs to meet one condition to be true

Image description

6 . Else

Now when our conditions for IF are not met, we can tell the function to do something else

Image description

We can also have "else if" which will allow us to have more than two conditions

Image description

Also, when talking about functions we need to remember scopes.
Those are the domains of visibility of variables
1 . Global Scope

Just a variable that's declared outside of a function. Is seen everywhere

2 . Local Scope

A variable that's declared inside of a function, therefore is only seen there

That's all for today!!
Senk yuuuu!!'

Image description

Top comments (0)