Getting started with JavaScript - Chapter 3 πŸš€

devlazar

devlazar

Posted on January 31, 2021

Getting started with JavaScript - Chapter 3 πŸš€

Table Of Contents
* πŸ€“INTRODUCTION
* πŸ‘©πŸ»β€πŸ”¬FUNCTIONS
* πŸ‘”BINDINGS AND SCOPES
* πŸ¦…NESTED SCOPES
* 🏹ARROW FUNCTIONS
* πŸ“šCALL STACK
* ❔OPTIONAL ARGUMENTS
* ➰RECURSION
* πŸ“SUMMARY
* πŸ™THANK YOU

πŸ€“ INTRODUCTION

**Welcome, my dear coders! I hope you are all having a codelicious weekend! Here we are, at our third chapter of the Getting started with javascript series. Today, we will tackle the functions, scopes, bindings, different types of function, the call stack and more. Stay with me, let's learn JavaScript and get you a first programming job! πŸš€

I am hyped!
hype

πŸ‘©πŸ»β€πŸ”¬ FUNCTIONS

The day before yesterday, I discussed a function, where we explained that the functions represent the concept of wrapping a piece of a program. It gives us a way to structure larger programs, assign subprograms a name, reduce repetition, and isolate these subprograms from each other.

FUNCTION DEFINITION

A function definition is a regular binding where the value of the binding is a function. Let's define a function that will produce the square of a given number:

const square = function(x){
   return x*x;
};
console.log(square(8)); //output: 64
Enter fullscreen mode Exit fullscreen mode

INGREDIENTS FOR MAKING FUNCTIONS

  • Expression that starts with the keyword function.
  • Set of parameters (in this case x)
  • Body of the function - contains statements that are to be executed when the function is called.

πŸ‘” BINDINGS AND SCOPES

Each binding has a scope, which is the part of the program in which the binding is visible. For binding defined outside of any function or block, the scope is the whole program - also known as global scope.

Bindings that are created for function parameters or declared inside a function can be referenced only in that function - also known as local scope.

Example:

let x = 3;
if (true){
  let y = 25;
  var z = 3;
  console.log(x + y + z); // output: 31
}
//y is not visible here 
//but z is visible, because it is declared as var not let
//if we declare a variable in local scope with the var keyword
//a variable will be visible outside the local scope
//does not apply to variables declared with let keyword
console.log(x + z); //output: 6
Enter fullscreen mode Exit fullscreen mode

If we were to access y outside local scope we would get something like this:

Uncaught ReferenceError: y is not defined

πŸ¦… NESTED SCOPES

JavaScript distinguishes not just global and local bindings. Blocks and functions can be created inside other blocks and functions, producing multiple degrees of the locality.

const pizza_dough = (factor) =>{
  const ingredient = function(amount, unit, name){
    let ingredientAmount = amount*factor;
    if (ingredientAmount > 1){  
      unit += "s";
    }
    console.log(`${ingredientAmount} ${unit} ${name}`);
  };
  ingredient(0.5, "cup", "warm water");
  ingredient(1, "package", "active dry yeast");
  ingredient(3, "cup", "bread flour");
  ingredient(2, "tablespoon", "extra virgin oil");
  ingredient(2, "teaspoon", "salt");
  ingredient(1, "teaspoon", "sugar");
}
pizza_dough(1);
Enter fullscreen mode Exit fullscreen mode

The code inside the ingredient function can see the factor binding from the outer function. But its local bindings, such as unit or ingredientAmount are not visible in the outer function;

🏹 ARROW FUNCTIONS

In the previous code section, I used what is called an arrow function. So, instead of the function keyword, it uses an arrow made up of an equal sign and a greater-than character (=>)

The arrow comes after the list of parameters and is followed by the function's body. It expresses something like this specific input, with specific parameters, will produce the following result;

Let's convert our square function into an arrow function:

const square = (x) => { return x*x; }; //an arrow function
const square = x => x*x; //remove paranthesees when only parameter
Enter fullscreen mode Exit fullscreen mode

These are the same arrow functions and will produce the same result as a regular function notation.

πŸ“š CALL STACK

A call stack is a stack data structure (that we will talk about very soon) that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or machine stack.

WHAT CALL STACK DOES?

The primary purpose of the call stack is to store the return addresses. When a subroutine is called, the location (address) of the instruction at which the calling routine can later resume needs to be saved somewhere.

In a call stack, each task can have its own stack, and thus the subroutine can be thread-safe, that is, can be active simultaneously for different tasks doing different things.

Depending on the language, operating system, and machine environment, a call stack may serve additional purposes, including:

  • Local data storage
  • Parameter passing
  • Evaluation stack
  • Pointer to the current instance
  • Enclosing subroutine context
  • Another returning state

CALL STACK STRUCTURE

The call stack is composed of Stack frames (activation records or activation frames). Visual representation of a stack is just that, a stack:

Alt Text

The stack frame at the top of the stack is for the currently executing routine. The stack frame usually includes at least the following items (in push order):

  • The arguments (parameter values) passed to the routine
  • The return address back to the routine's caller
  • Space for the local variables of the routine

Example of the stack operations:
Alt Text

  • push - adds element on the top of the stack (OverflowException)
  • pop - reads and removes an element from the top of the stack (UnderflowException)
  • getTop - reads an element from the top of the stack, but does not remove it
  • isEmpty - checks if the stack is empty
  • numberOfElements - gets the number of elements in the stack

❔ OPTIONAL ARGUMENTS

JavaScript is extremely broad-minded about the number of arguments you pass to a function. If you pass too many, the extra ones are ignored. If you pass to few, the missing parameters get assigned the value of undefined.
DOWNSIDE - it is possible - likely, even - that you'll accidentally pass the wrong number of arguments to
UPSIDE - Behaviour can be used to allow a function to be called with different numbers of arguments.

Example:

function minus(a, b){
  if (b === undefined) return -a;
  else return a-b;
};
console.log(minus(10)); //output: -10
console.log(minus(10, 5)); //output: 5

Enter fullscreen mode Exit fullscreen mode

➰ RECURSION

It is perfectly okay for a function to call itself, as long as it doesn't do it so often that it overflows the stack. A function that calls itself is called a recursive function.

function power(base, exponent){
  if (exponent === 0){
    return 1;
  } else{
    return base * power(base, exponent - 1);
  }
}
console.log(power(3, 2)); //output: 9
Enter fullscreen mode Exit fullscreen mode

This is very close to the way mathematicians define exponentiation and arguably describes the concept more clearly than the looping variant.

The problem with this implementation is that in typical JavaScript implementation it's about three times slower than the looping version.

πŸ“ SUMMARY

  • The functions represent the concept of wrapping a piece of a program. It gives us a way to structure larger programs, assign subprograms a name, reduce repetition, and isolate these subprograms from each other.
  • Binding defined outside of any function or block, the scope is the whole program - also known as global scope.
  • Bindings that are created for function parameters or declared inside a function can be referenced only in that function - also known as local scope.
  • Blocks and functions can be created inside other blocks and functions
  • The arrow comes after the list of parameters and is followed by the function's body. It expresses something like this specific input, with specific parameters, will produce the following result
  • A call stack is a stack data structure (that we will talk about very soon) that stores information about the active subroutines of a computer program.
  • The primary purpose of the call stack is to store the return addresses.
  • The call stack is composed of Stack frames (activation records or activation frames).
  • JavaScript is extremely broad-minded about the number of arguments you pass to a function. If you pass too many, the extra ones are ignored. If you pass to few, the missing parameters get assigned the value of undefined.
  • A function that calls itself is called a recursive function.

πŸ™ THANK YOU FOR READING!

References:
School notes...
School books...

Please leave the comment, tell me about you, about your work, comment your thoughts, connect with me!

β˜• SUPPORT ME AND KEEP ME FOCUSED!
Buy Me a Coffee at ko-fi.com

Have a nice time hacking! 😊

πŸ’– πŸ’ͺ πŸ™… 🚩
devlazar
devlazar

Posted on January 31, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related