Functions in Javascript

In this tutorial, we are going to have a look at functions in JavaScript; its Declaration and example.

WHAT ARE THE FUNCTIONS IN JAVASCRIPT?

Functions in javascript are fully typed object, that you can pass as data to another function also.

  • It can also be Extended and Manipulated.

FUNCTION DECLARATION IN JAVASCRIPT

/*codeatglance sample of function declaration in javascript*/
function functionName() {

   // body of the function

   // return statement(optional);
}

EXAMPLE OF FUNCTION IN JAVASCRIPT

/*codeatglance example of functions in javascript*/
function demo(name)
{
console.log("Name: "+name);//printing the outpt on screen
}
demo("John");

OUTPUT

Name: John

Each function in JavaScript returns a value, if there is no return statement then the function returns undefined.

EXAMPLE OF A FUNCTION RETURNS UNDEFINED

/*codeatglance example of a function returns undefined*/
function withReturn(){
return 100;
}
console.log(withReturn());
function withoutReturn(){
}
console.log(withoutReturn());

OUTPUT

100
undefined

HOW TO PASS A VALUE TO THE FUNCTION IN JAVASCRIPT?

/*codeatglance example how to pass a value to the function in Node.js*/
function demo(name) {
console.log("My name :"+ name);
}
demo();
demo("Lary","John","Zed",4);

OUTPUT

My name :undefined
My name :Lary

Undefined in Javascript: If there is no parameter passed in the javascript function then the returning variable which is assigned the value will return undefined.
Unused in Javascript: If there are many parameters passed in the function then the extras will remain unused.
Anonymous function in javascript: Name of the function in Node.js is optional and such functions are known as an anonymous function.

EXAMPLE OF AN ANONYMOUS FUNCTION IN JAVASCRIPT

var sum=function(num1,num2){
return num1+num2;
}
console.log(sum(10,15));

THE OUTPUT OF THE CODE

25

 

Leave a Reply

Shopping cart