Understanding Functions & Scope in JS
By: Sudesh Kumar Das
Tags: Programming, Functional Programming, JavaScript, Beginner, Learning To Code

Understanding Functions & Scope in JS

#teamtanayejschallenge- Part 4- Functions and Scope in JavaScript

Photo by James Harrison on Unsplash

Its said that we humans are becoming slaves to machines, being addicted to them. Partly, it is correct. In my opinion, it is the other way around, machines are our slaves. They only do what we make them do. But sometimes, they malfunction, i.e, they go haywire, acting in a manner we don’t desire.

“My phone is not functioning correctly”. Easy to understand. Function means a task. Whenever your phone doesn’t perform it right, we call it malfunctioning.

But, what actually is wrong in the machine is either hardware or software. Lets talk about the software part of the machines.

Functions

Functions are tasks, tasks are a set of intructions given to someone / something. In programming, how do we instruct the computer? “Code”.

So, we can say that a function is a set of code (instructions) given to computer. Great, no we have our function, but unless we tell the computer to perform it, it is useless, just like knowing how to paint and not painting.

When we command the computer to perform a function, we are essentially calling/invoking the function. Let me explain, all the codes are stored in the system. “So, technically, the set of instructions must be stored too? ” Absolutely correct. When we need a function to work, we call that function, saying, “Hey, can you please perform your tasks?” This is what is termed as Function Call or Function Invocation.

Parameters

Many a times, there are pre-requisites for performing a certain task, such as drinking coffee. Here, without coffee, the task of ‘drinking coffee’ is quite impossible.

But hey, aren’t there tasks which don’t have pre-requisites? Yes, that is why arguements in functions are completely optional.

function drink(liquid) {

console.log(liquid + ' is consumed')

} // when we provide coffee, and we call the function drink, the coffee is consumed. What if coffee is not given? //

Arguements

Arguements are the values passed to the function when they are called. In our example, if we do not give coffee, we can not drink coffee. An error will occur.

Also, note that arguements are passed (provided for) only when the function is called, not when declaring a function.

// let us call our drink function drink('coffee');

// output -> 'coffee is consumed'

// what if we pass something else?

drink('tea');

// output -> 'tea is consumed'

When multiple arguements are passed, JavaScipt will ignore the extra arguements, and when no arguement is passsed, a value of undefined will be passed.

drink('coffee', 'tea', 'cold-drink');

// output -> coffee is consumed drink();

// output -> undefined is consumed

Defining Functions

There are three ways of defining functions; namely-

Function Declaration

Function Expression

Arrow Function

Function Declaration

A function declaration is creating a function, in the code snippet below. It is not immediately called, rather it is kept in the storage until it is required to be performed. Think of it as ‘knowing how to cook’. Unless you are a cook or a chef, your cooking skills are needed only when you need food, if you are playing tennis, the knowledge exists only in the back of your mind.

function name(parameters) {

// do something

} // here is how you call this functions

name(arguements); /* the arguements will take place of parameters when function is executed */

Function Expression

Another way of creating function is through assigning it to a specific variable. Think of this as the skill of cooking pasta. It is different from whole cooking.

var cookPasta = function(pasta,spices){

// cook pasta

};

Arrow Functions

The ECMAScipt 2015 introduced a new way of creating functions. The reason behind was to type less, helping programmers to get more done is less time. It is essentially same as normal functions, only difference in syntax

const name = (parameters) => {//do something} // if there are no parameters, () is used.

// if the code returns a small code the curly braces can be removed

So, now we know what are functions & how to declare them. Another important concept is scope, which I will cover in the next section. Functions are essentially our slaves, which do what we tell them to do.

Scope

Scope in functions are the accesibility of variables around their environment. Consider this, you wanna take a shower. To perform this certain task, we have to go to the bathroom, where the shower actually exists.

There are scopes in JavaScript; global and local. The local variables are accessible only in the local block of code. For instance, you can not take a bath in your kitchen, because the shower doesn’t exist in the kitchen.

What is global scope? The root of the code, the house, is the global. There are some things which are accessible in all the rooms, such as electrical connection like light. Likewise, data stored in global scope is accessible in the local scope too, but not the other way round.

// this is the house consisting of different room

var electricity; function bathroom() {

// local scope

var shower;

use(electricity);

} function kitchen() {

// local scope

var stove;

use(electricity);

} /* if we try to access stove our shower outside of their local scope, i.e, their respective functions */ /* we can also see that electricity can be used inside of the local scope. why? because it is a global variable. */

Now, we know what variables can be accessed from where.

That is it, for details of the challenge. Click Here. This article was inspired by Eloquent JavaScript- Chapter 3 (Functions) by Marijn Haverbeke. Happy Coding! (: