Functions In Javascript With Code Snippets

Functions In Javascript With Code Snippets

Functions:

Functions are one of the important topic in every programming language. Functions prevent us from writing a block of code again and again, for example, we are working on a project and there is a block of code that is being repeatedly used in the project so instead of writing that block of code, again and again, we can create a function for that block of code and we can call that function whenever it is required.

Note: A function will only be executed when it is called.

Function Declaration:

We will use the function keyword and function name to declare a function.

Example for functions declaration

function displayDetails(){
  let name = "deepak kumar"
  let surname = "nayak"
  console.log(`full name is: ${name} ${surname}`)
}
displayDetails()

Output
------
full name is: deepak kumar nayak

In the above example, I am not using any parameter or any arguments. the parameter is something that is used during the function definition and arguments are something that is used during a function call.

Example Of Function Using Parameter and Arguments:

//parameter: used in a function definition
function display_name(first_name, last_name){
}
// arguments: used during function call
display_name('Deepak Kumar', 'Nayak')

here I am calling the function and passing to it two arguments

function displayDetails(firstname, lastname){
  console.log(`full name is: ${firstname} ${lastname}`)
}
displayDetails('Deepak Kumar','Nayak')

Output
------
full name is: Deepak Kumar Nayak

// display odd numbers
function displayoddNumbers(numbers){
  for(let i of numbers){
    if( i % 2 !== 0){
      console.log(i)
    }
  }
}

displayoddNumbers([2,5,9,8,12,15,17])

Output
------
5
9
15
17

Function with arguments:

Arguments mean here I am not talking about the arguments which are passed during function calling.. arguments mean the argument object inside the function we can access an object called argument object, it behaves like an array but it is not an array type.

example:

function displayNumbers(){
  console.log(arguments)
  console.log(typeof arguments)
}

displayNumbers(10,20,30,40)

Output
-------
[Arguments] { '0': 10, '1': 20, '2': 30, '3': 40 }
object

arguments are predefined. if during calling a function we are passing more than one value but during function definition if I am not using any parameter which can hold the values, then at that time all the values will get stored inside the argument object.

Examples of Function Expression:

The function expression is pretty much similar to the function declaration, The only difference between both the function declaration and the function expression is the name of the function which is omitted in the function expression let's get into an example to understand it well ...

Note: Functions which are stored inside a variable called function Expression

So look at both the example function expression and declaration, in function declaration I have used a function name called displayDetails( ) but in function expression, I haven't used any function name, it is omitted to create an anonymous function

In function expression, I have assigned the function to a variable called displayDetails which I am consoling it later. One important thing look at the example of Function Expression I am consoling it in two different ways

  • by saving it into a variable called result and the other way directly consoling it.

  • the 1st way is a good way of writing code so its better to follow that one

    const result = displayDetails('Deepak Kumar', 'Nayak')
    console.log(result)

How Functions Work In Javascript

var x = 1;
a()
b()
console.log('accessing it in the global scope:', x)

function a(){
    let x = 10
    console.log('accessing it inside the function a', x)
}
function b(){
    let x = 100;
    console.log('accessing it inside function b', x)
}

Note:

  • Both the function I have created with the help of function declaration, not by a function expression.

  • We can call those functions before initialization just because of hosting. but there is also one more reason if those functions were being created with the help of function expression we would not be able to call it.

as we know that whenever Javascript runs a program a global execution context is created which is divided into two components

  • Memory Component

  • Code Component

so now this is the first Phase and in this phase, the memory allocation will be done. so let's c how it is being done behind the scenes.

So as soon as the program starts executing it will get executed from top to bottom and 1st the memory allocation will be done to

  • variable x and it will store a special value inside it called undefined.

  • function a will be allocated memory and it will point toward the function code

  • function b will be allocated memory and it will also point towards its function code. both the functions won't be storing undefined.

when all this memory allocation is going on let's also look at how the Call-stack looks like as we know that when the program getting executed the global execution context is created and it will be pushed inside the call-stack

Note: Follow the image while reading this article for better understanding

Now let's c what will happen when the Code Execution Phase will start. When the control will come to 1st line var x= 1 then previously the value of x is stored as undefined, but now it will get replaced with 1:

now the control goes to line number 2 and here a function is invoked as soon as the function is invoked execution context is created which is independent it doesn't have any sort of connection with anyone over there why I am saying this because there is one more function also so both the functions are independent which is again divided into two parts memory part and a code part now let c in the image (guys please follow the image for better understanding) how its looks like.

Note: as soon as the execution context is created it will be pushed into the call -stack which mean function a() will be pushed inside the call stack

Now the control is in line number 6 and once we execute that line var x =10 now the value of x will get replaced with 10 where undefined was stored earlier.

okay after this the control will come into the 7th line where it is consoling the value of x so what it will do, it will find the value of x in its local scope what do you mean by local scope here it's mean inside the function a(). If the value is not there inside the function a() then it will find inside the global scope (global lexical environment) which is a different topic we will discuss later in scope Chaining. But here the value of x is inside the function a().

after printing the value of x in the console we have done with the execution of that function and as soon as the execution is over the whole, execution context gets deleted and the from stack also it is removed Follow the Image for More Clarity

The Function a() was removed from the stack and the execution context was also got deleted this is how it works after the execution got over it will get deleted

Now the control comes to line number 3 and again the function is getting invoked here due to which a new execution context got created which is again divided into two parts the memory part and the code part. and yes as soon as the function gets invoked it will get pushed into the call stack. now let's see how the image looks like

after the execution got over function b will also get removed from the stack as well as the execution context for function b will also get deleted at the end the call stack will also get deleted.

The call stack will also get deleted at the end. This is how the function works In Javascript:

Arrow Functions:

Example One

const findLength = (items) =>{
  for(let i of items){
    console.log('The length of:', i,":" ,i.length)
  }
}

findLength(['deepak','rahul','alygoni'])

Output
--------
The length of: deepak : 6 
The length of: rahul : 5  
The length of: alygoni : 7
  • Example Two

      let magicNumbers = (elements) => console.log(elements)
      magicNumbers([10,20,30,40])
    
      Output
      ------
      [ 10, 20, 30, 40 ]