DEV Community

Cover image for Functions in Javascript
Mysterio
Mysterio

Posted on

Functions in Javascript

Hello Guys today i am going to discuss functions in javascript

Lets get started....

JavaScript Functions -

  • A JavaScript function is a block of code designed to perform a particular task.

  • A JavaScript function is executed when "something" invokes it (calls it).

Why Functions?

  • You can reuse code: Define the code once, and use it many times.

  • You can use the same code many times with different arguments, to produce different results.

JavaScript Function Syntax

  • A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

  • Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

  • The parentheses may include parameter names separated by commas:
    (parameter1, parameter2, ...)

  • The code to be executed, by the function, is placed inside curly brackets: {}

  • function name(parameter1, parameter2, parameter3) {
    // code to be executed
    }

  • Function parameters are listed inside the parentheses () in the function definition.

  • Function arguments are the values received by the function when it is invoked.

  • Inside the function, the arguments (the parameters) behave as local variables.

Normal Functions -

function message(){
  let greet = "hello Mysterio"; // greet variable can be used here
  return greet;
}

console.log(message());
Enter fullscreen mode Exit fullscreen mode

OUTPUT -

Hello Mysterio
Enter fullscreen mode Exit fullscreen mode

Parameterised functions -

  • Parameters are the names that are listed in the definition of the function. They are the mechanism of passing the values to functions.

  • The values of the parameters are passed to the function during invocation. Unless it is specified explicitly, the number of values passed to a function must match with the defined number of parameters.

Syntax

The syntax for defining a parameterized function is:

function function_name( parameter1,parameter2 ,…..parameterN) {

//body of the function

}

Example -

function myFunction(p1, p2) {
  return p1 * p2;   // The function returns the product of p1 and p2
}
console.log(myFunction(10,7));
Enter fullscreen mode Exit fullscreen mode

OUTPUT -

70
Enter fullscreen mode Exit fullscreen mode

Default Function Parameters -

  • In ES6, the function allows the initialization of parameters with default values if the parameter is undefined or no value is passed to it.
function message(name = "Mysterio"){
  let greet = "hello "+name; // greet variable can be used here
  return greet;
}

console.log(message());
console.log(message("Stark));
Enter fullscreen mode Exit fullscreen mode

OUTPUT -

hello Mysterio
hello Stark
Enter fullscreen mode Exit fullscreen mode

EXPLAINATION -

  • As you can see if you dont pass any argument to the function call then it will use the default parameter value and if you pass the argument with some value then it will use that value instead of default parameter value.

Function Return -

  • When JavaScript reaches a return statement, the function will stop executing.

  • If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

  • Functions often compute a return value. The return value is "returned" back to the "caller":

Example -

function mySum() {
  let array = [1,2,3,4,5,6,7,8,9,10];
  let sum = 0;
  for(i = 0;i<=array.length;i++){
    sum = sum + i;
  }
  return sum;
}
console.log(mySum())
Enter fullscreen mode Exit fullscreen mode

OUTPUT -

55
Enter fullscreen mode Exit fullscreen mode

EXPLAINATION -

  • We have created an array and it has 10 numbers from 1-10 inside it
  • Then we created a variable called sum and initialize it with value 0
  • Then we iterate over the array using for loop and sum up all the value of elements inside array.
  • finally we have return the sum using "return" keyword

Functions Used as Variable Values -

function message(){
  return "Hello ";
}

let x = message();
let greet = x + " Mysterio";
console.log(greet);
Enter fullscreen mode Exit fullscreen mode

OUTPUT -

Hello Mysterio
Enter fullscreen mode Exit fullscreen mode

Local Variables

  • Variables declared within a JavaScript function, become LOCAL to the function.

  • Local variables can only be accessed from within the function.

//greet variable cant be used here it is local and have scope inside the function only

function message(){
  let greet = "hello Mysterio"; // greet variable can be used here
  return greet;
}

// greet variable cant be used here it is local and have scope 
inside the function only
Enter fullscreen mode Exit fullscreen mode
  • Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

  • Local variables are created when a function starts, and deleted when the function is completed.

Rest Parameters -
Rest parameters do not restrict you to pass the number of values in a function, but all the passed values must be of the same type. We can also say that rest parameters act as the placeholders for multiple arguments of the same type.

For declaring the rest parameter, the name of the parameter should be prefixed with the spread operator that has three periods (not more than three or not less than three).

Example -

function heroes(...name){
  for (var i = 0; i < name.length; i++) {
    return name[i];
  }
}
const names = ["Stark","Captain","Thor","Hawkeye","Black Widow","Banner"];
console.log(heroes(names));
Enter fullscreen mode Exit fullscreen mode

OUTPUT -

[ 'Stark', 'Captain', 'Thor', 'Hawkeye', 'Black Widow', 'Banner' ]
Enter fullscreen mode Exit fullscreen mode

EXPLAINATION -

  • We created a function called heroes and passed a parameter name using spread operator then call the function with an array containing super heroes names and then displayed then names using for loop.

NOTE - There are more topics like Arrow function , Generators etc but they are little advance and are a part of ES6 So we wont cover those in this post.

THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE SUGGESTION PLEASE MENTION IT IN THE COMMENT SECTION.

Discussion (0)