JavaScript tutorial -4 Function

JavaScript has function. Remember in JavaScript everything is objects, so there is nothing wrong to say functions are object again.

Like Object literals there is something called Function literals, which helps in creating function or function object in a easier way.

Function Literals
Let see how to create how use function using function literals

var sum = function ( a , b ) {
	return a+b;
};		
// Create a variable and assign a function to it.

 

This kind of practice would really seem to different or weird for a programmer who comes from java , c , c ++ background. But what to say this is JavaScript, comparing JS with other language will not help you to understand the concepts. Just learn JS as how it should be.
Also remember function literals are not the only way to create the function.

Let’s say we have a function called sum

Let’s say we have a function called sum 
function sum(a , b) {
	print("I am in function called sum");
} 
sum( 10 , 14);

The about code snippet will output “I am in function called sum”

function sum(a , b) {
	print("I am in function called sum");
} 
sum();

Now what could be the output?
You might thing we will have error and we will not get the output. But the fact is we will get the output without any error or any abnormal termination of program.

function sum(a , b) {
	print("I am in function called sum");
	print(a);
} 
sum();

Now what could be the output.
You might thing , this time we have an error and we will not get the output. But the fact is even this time we will get the output.

What’s really happening when we invoke a function in JavaScript?
There will not be run time errors or exceptions if the no. of argument does not match with the actual function at the time of invocation. If there are too many arguments then extra arguments are ignored. If there is less no. of argument, then undefined will be substituted for the missing values. And there is no type checking on the arguments which mean below code snippet will also work without issues.

function sum(a , b) {
	print("I am in function called sum");
} 
sum("shakthydoss");

Difference between function and Method

A method is on an object. A function is independent of an object.
For Java, there is only methods. For C, there is only functions.
And JavaScript has both method and function.
Functions can be invoked directly. Methods can be invoked via Object.


Post a Comment

Your email is never published nor shared. Required fields are marked *