JavaScript Functions Syntax


JavaScript functions are capable of more than just merely enclosing a bunch of codes while waiting for the call to execute. Functions have evolved over time leading to new definitions, execution methods and syntaxes. This post will cover some of the present roles JavaScript functions have played so far.
Function Expressions
1
2
3
4
// Function declaration
function function_name() {};
// Function expression
var function_name = function() {};
All JavaScript declarations are moved up in the scope during evaluation
1
2
function_name();//function call[WORKS]
function function_name(){};
Methods
When a function is an object’s property, it is called method. a function inside another function is also a method. This is an example for a method inside object.
1
2
3
4
5
6
var calc = {
  add : function(a,b){return a+b},
  sub : function(a,b){return a-b} 
}
console.log(calc.add(1,2)); //3
console.log(calc.sub(80,2)); //78
The add and sub functions are methods of calc object.
Example for function inside a function :
1
2
3
4
function add(a){
  return function(b){return a+b;}
}
console.log(add(1)(2)); // Output is 3
Constructors
When you add new keyword before a function and call it, it becomes a constructor that creates instances. Below is an example where constructors are used to create instances of Fruit and values are added to each Fruit‘s properties.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Fruit(){  
  var name, family;
  this.getName = function(){return name;};
  this.setName = function(value){name=value};  
  this.getFamily = function(){return family;};
  this.setFamily = function(value){family=value};
}
var apple = new Fruit();
apple.setName("Apple");
apple.setFamily("Apple family");
var orange = new Fruit();
orange.setName ("Orange");
orange.setFamily ("Orange family");
console.log(orange.getName()); // "Orange"
console.log(apple.getName()); // "Apple"
console.log(orange.getFamily()); // "Orange family"



Share this

Random Posts

Previous
Next Post »