Functions in JavaScript

Functions in JavaScript

Functions in JavaScript

In JavaScript, a function is a group of statements that does a certain action or computes a value.

Why We need Functions
To avoid repeating the same code all over places, you can use a function to wrap that code and reuse it.  

Function Declaration
The term "function" is used to define, declare, or otherwise make a statement about a function.
— The function's name.
— A list of the function's parameters, separated by commas and enclosed in parentheses.
— A group of curly-braced JavaScript statements that specify the real logic, "...
— The value that function returns is specified by a return statement.

function square(number) {  
    return number * number;

1.  Primitive parameters (such as a number, boolean, float) are passed to functions by value; 
Any changes done in the value of such parameter inside the function, remain local to that function. this change never reflected globally or in the calling function 
2. Non-primitive parameters , such as Array or a user-defined object are passed to the function as a reference i.e. pointer to that types. Any changes done in value of properties, or element of such types inside the function is visible outside the function.

function Models(vehicleObject) {
    vehicleObject.make = 'Hundai';

var mycar = {make: 'Honda', model: 'I10', year: 1990};
var x, y;

x = mycar.make; // x gets the value ""Honda""
y = mycar.make; // y gets the value ""Hundai""

Function expressions / Anonymous function
Also call Anonymous function, without any Name.

const square = function(number) { return number * number }
var x = square(2) // x gets the value 4

We can provide a name even to Anonymous function or Function expressions, Name makes easier to identify the function in a debuggers stack traces.

const square = function sqr(n) { return number * number }

Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.