Functions

Photo by Andrew Neel on Unsplash

Functions

As the code gets longer and inevitably, there will be a code that repeats the same number of steps. Instead of repeating the same steps multiple times, we can package up those processes into reusable chunks of code called functions. A function is given some data, performs operations on the data, and then returns the altered data.

Reverse Function Example

function reverseString(str){
var reversed="";
for(var i=str.length;i>=0;i--){
reversed+=str[i];
}
return reversed;
}
console.log(reverseString("Divya"));
Print- ayviD

How to declare a function

Functions allow you to package up lines of code that you can use (and often reuse) in your programs. The parameter is listed as a variable after the function name, inside the parentheses. And, if there were multiple parameters, you would just separate them with commas.

function doubleGreeting(name, otherName) {
  // code to greet two people!
}

You can also have functions that don't have any parameters. Instead, they just package up some code and perform some task. In this case, you would just leave the parentheses empty.

// accepts no parameters! parentheses are empty
function sayHello() {
  var message = "Hello!"
  console.log(message);
}

undefined is the default return value on the console when nothing is explicitly returned using the special return keyword.

Return statements

In the sayHello() function above, a value is printed to the console with console.log, but not explicitly returned with a return statement. You can write a return statement by using the return keyword followed by the expression or value that you want to return.

// declares the sayHello function
function sayHello() {
  var message = "Hello!"
  return message; // returns value instead of printing it
}

How to run a function

Now, to get your function to do something, you have to invoke or call the function using the function name, followed by parentheses with any arguments that are passed into it.

// declares the sayHello function
function sayHello() {
  var message = "Hello!"
  return message; // returns value instead of printing it
}

// function returns "Hello!" and console.log prints the return value
console.log(sayHello());
Prints: "Hello!"

Parameters vs. Arguments

A parameter is always going to be a variable name and appears in the function declaration.Parameters are variables that are used to store the data that's passed into a function for the function to use. An argument is always going to be a value (i.e. any of the JavaScript data types - a number, a string, a boolean, etc.) and will always appear in the code when the function is called or invoked.Arguments are the actual data that's passed into a function when it is invoked:

function findAverage(x, y) {
  var answer = (x + y) / 2;
  return answer;
}
var avg = findAverage(5, 9);
Are x and y parameters or arguments for this function?
Parameters
// x and y are parameters in this function declaration
function add(x, y) {
  // function body
  // Here, `sum` variable has a scope within the function. 
  // Such variables defined within a function are called Local variables
  // You can try giving it another name
  var sum = x + y;
  return sum; // return statement
}

// 1 and 2 are passed into the function as arguments, 
// and the result returned by the function is stored in a new variable `sum`
// Here, `sum` is another variable, different from the one used inside the function
var sum = add(1, 2);

Summarizing the above topics The function body is enclosed inside curly brackets:

function add(x, y) {
  // function body!
}

Return statements explicitly make your function return a value:

return sum;

You invoke or call a function to have it do something:

add(1, 2);
Returns: 3

Returning vs. Logging

So there's a couple of different ways to get your function to produce some sort of output

console.log()- Use to print value to the JavaScript console. To print out messages to the console which you can do inside the function or directly from the console. Printing a value to the JavaScript console only displays a value (that you can view for debugging purposes). console.log to test your code in the JavaScript console.

Ex-1
console.log("Divya");
//Prints in console
Divya
undefined
Ex-2
function sayHi(){
var msg="Hi";
console.log(msg);
}
Prints
"Hi"

undefined

A function is always going to return some value back to the caller. If a return value is not specified, then the function will just return back undefined

So the way to look at it is there's two different ways you can get your function to produce some sort of output

1)Printing messages using console.log

2)By using the return keyword and a value to return back some value to the caller.

Two important things to point out here is that the return keyword will be used to stop the execution of a function and return a value back to the caller. If nothing is defined as a value to be returned back, the undefined is going to be returned back automatically. It’s important to understand that return and console.log are not the same thing.

function isPrime(n){
for(var i=2; i<n;i++){
if(n%i===0){
console.log(n+ " is divisible by " + x);
return false;
}
}
return true;
}
isPrime(11);
//prints
true
isPrime(49);
//prints 
49 is divisible by 7
false

A function's return value can be stored in a variable or reused throughout your program as a function argument.

// returns the sum of two numbers
function add(x, y) {
  return x + y;
}


// returns the value of a number divided by 2
function divideByTwo(num) {
  return num / 2;
}


var sum = add(5, 7); // call the "add" function and store the returned value in the "sum" variable
var average = divideByTwo(sum); // call the "divideByTwo" function and store the returned value in the "average" variable