JavaScript functions

functions

 
A function is seen as a wrapper to a block of code that is given a name. They can be executed from other areas of the program using the name.

We can define functions using the function keyword :

function hello(){
alert("Hello");
}

The above code creates a function named hello.
 
We can invoke this function as

hello();


 

JavaScript function arguments

 
When defining a function, we can provide names for arguments that are to be passed to it.

function hello(name) {
  alert("Hello " + name);
}

We can call the function hello() with parameter “John” as :

hello("John");

 

JavaScript functions do not check parameter types

There is no type checking involved with function parameters.

So, we can also call the hello() function with integer parameter as well :

hello(1);

 

JavaScript functions do not check number of parameters

Functions automatically have access to a variable called arguments. This is an array-like object that reflects every value passed to the function when the function is called.

So, the following function call is still valid :

hello("John","Doe");

Output:

Hello John
 

JavaScript functions can not have default parameters

In JavaScript, function parameters in JavaScript cannot be set with a default value.

If a function has an parameter that is not passed a value when the function is called, that parameter will have a value of undefined.

hello();

Output:

Hello undefined

 
To create default value-like functionality, add a default value assignment within the function:

function hello(name) {
  if (typeof name == 'undefined') {
    name = "Unknown";
  }
  return ("Hello " + name);
}

 

Returning values from a function

A function may return data to the statement that called it.

To get a function to return a value, we use the return keyword, followed by the value we want it to return:

For example,

function hello(name) {
  return ("Hello " + name);
}

A return statement is always the final act of a function; nothing else is processed
after a function has returned.

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags