JavaScript Functions – Methods in JavaScript

Functions (or methods) are the blocks of code that can perform operation independently according to the instructions provided. Quite technical. In layman’s term, a function can be defined as a machine which takes some input, process them according to the instructions provided and give desired output. Lets create a function

Syntax of Function in JavaScript

In javascript, a function is defined in following way:

function function_name(parameter1, parameter2, parameter3) {
function sum(num1,num2){
function diff(num1){

Lets recheck

  • Independently Working
  • Performs According to instrcution
  • Gives desired Output

In the examples above, both the functions are working as per the instructions.

sum function is taking 2 inputs (parameters as we call them technically) and adding them.
diff function takes only 1 parameter and substracts 10 from it.

Alright, we have your machines(functions) ready but how do we them them working? If you copy and paste the code in the console you wont be seeing anything. It only means that the function is ready to work. Time to add inputs and get the functions working.

Function Calling

To start the machime or ‘To call the function'(Technical term) we simple write the function name and in the brackets we enter the paramaters.


Did we talk about returning the output? Yes, but we have not done that yet. Lets work on returing the output and storing them in some variable. To make it easier to understand, we will use the previous examples only.

function sum(num1,num2){
	return (num1+num2);
function diff(num1){
	return (num1-10);

Instead of working in side the fucntion, we have returned the output from where the function was called. Now, we need to store this output in a new variable.

var total = sum(5,9);
console.log(total);		//or
var total = diff(43);
console.log(total);		//or

Why do we use functions?

Reusability. Once a function is defined it can be called multiple times with different parameters. This saves you time, and saves alot of lines. Thus, you can use samme functionality again and again.

Note – We will be working with alot of functions when we study the DOM.

Translate »