Skip to content

JavaScript functions




A key concept in JavaScript and probably the most significant attribute which separates JavaScript from other conventional programming languages is how it treats functions and function argument patterns.

The way JavaScript implements and treats function often creates a lot of confusion as to whether JavaScript is an Object-Oriented Programming (OOP) or Functional Language.

The truth is JavaScript is both, A Functional Object Oriented Programming Language (FOOP).

Due

In JavaScript there is no function polymorphism.  Essentially what this means is that you can't write a function with the same name with a different parameter list and rely on the compiler/interpreter to choose the correct one depending on parameters defined at run time.

In fact in JavaScript has a number of different conventions and patterns for functions when compared against other conventional languages.

In this post I will explain some of the most discerning differences of JavaScript functions and function argument patterns. Essentially as an accompaniment to my JavaScript Functions and Variables, Types and Values.

 

Defining functions

Functions are defined using the function keyword, which can be used in a function definition expression or in a function declaration statement.

A function is a special type of object, with special properties such as constructor and call. You can also add addtional properties to a function object.

It is this capability that makes function a first class citizen, because they can be passed around as arguments into other functions.

// Function return undefined
function functionName(){
}

// A function which returns a value
function functionName(){
  return somevalue;
}

// A recursive function 
function functionName(){
     return functionName;
}

//function expression defines a function
var someFunction = function(){
    return someValue;
}
// function expressions can include names useful for recursion
var f = function someFunction(x){ if(x <= 1) return1;else return x*somefunction(x-1);}

// function expressions can also be used as arguments to other functions
array.sort(function(x,y){return x-y;})

//function expressions are sometimes defined and immediately invoked
var someFunc = (function(x){return x*x;}(10));

//Create a function and explore properties
const gaz = function(name) {};
gaz.name;  // "gaz"
gaz.length;  // 1

//Add some addtional properties
gaz.wife = "tash";

gaz.wife;  // "tash"

Constructor functions

A constructor function is no different from any other function. A function is used as a constructor function when it is used after the new keyword.

Any function can be a constructor function. If you have several objects which share the same implementation, then place that logic inside a constructor function, and then use the constructor function to create those objects.

const Human = function(){};
const man = new Human();
man;

man instanceof Human;  //true
man instanceof Object; //true

A constructor function will return an object. You can use this inside the function body to assign new properties to the object.

So if you want to make many objects with the property Human initialized to the value "Woman", then you can create a new constructor function Woman that encapsulates that logic.

const Human = function(g) {
	this.gender = g;
}

const woman = new Human(f);
woman; {gender : "f" }

woman = instanceof Human; //true
woman instanceof Object; //true

nested functions

Functions may be nested within other functions

function someFunc(x,y){
 function someOtherFunc(z){return z*z;}
 return Math.sqrt(someOtherFunc(x) + someOtherFunc(y));
}

 

In JavaScript, a function may be called with any number of arguments, no matter how many of them are listed, and arguments which are not provided become undefined.

 

The following code snippet will help to explain

function addParameters(a,b,c){
    return a + b + c;
}

console.log(addParameters(1,2,3));
console.log(addParameters(1,2));
console.log(addParameters(1,2,3,4));
console.log(addParameters());

 

The console will display

6
NaN
6
NaN

Eloquent JavaScript: A Modern Introduction to Programming

Dives deep into the JavaScript language to show you how to write beautiful, effective code.

[qodef_button size="medium" type="solid" text="Buy Now" custom_class="" icon_pack="font_awesome" fa_icon="fa-amazon" link="http://amzn.to/2qjuUoj" target="_self" color="" hover_color="" background_color="" hover_background_color="" border_color="" hover_border_color="" font_size="" font_weight="" margin=""]

function arguments and parameters

function definitions do not specify an expected type for parameters and function invocations do not do any type checking on the argument values.

function invocations do not even check the number of arguments being passed. If  a function is invoked with fewer arguments than the declared parameters the additional parameters are set to the JavaScript undefined value .

The Arguments object

In each function is invoked with a psuedo-array called arguments.  The arguments object enables arguments to passed to the function to be retrieved by number rather than name.

 
[qodef_blockquote text="Arguments is not a real array it is an Arguments object. " title_tag="h5" width="80"]

 
We could now rewrite our function above as

function addParameters(a,b,c){
    var result = 0;
    for(var i=0; i

Which will now output

6
3
10
0

 



callee and caller properties

The arguments object defines a callee and caller properties. The callee property refers to the currently running function . Caller refers to the function that called the currently executing function.  The caller property gives access to the call stack, and the callee property is useful to all unnamed functions to call themselves recursively.

In ECMAScript 5 strict mode these properties are guaranteed to raise a TypeError if you try to read or write them.

Immediately Invoked Function Expression (IIFE)

The immediate function pattern is a syntax that enables you to execute a function as soon as it is defined.

(function(){
    console.log("I've excuted myself");
}());

Essentially this is just a function expression that executed right after it's creation. The term immediate function is not defined in the ECMAScript standard, but is widely accepted by the JavaScript community as a means to describe this pattern.

There are 3 parts to this pattern

  • Define a function using a function expression
  • Add parenthesis at the end e.g. ()
  • Wrap the whole function in parenthesis

Wrapper Object

Wrapper Objects are a grey area in JavaScript!

functions like String, Number, Boolean , Function, when called with new create wrapper objects for the primitive types

String is a global function that creates a primitive string when passed in an argument; it will try to convert that argument into a string.

String(39); // "39"
String(true); // "true"
String(null); // "null"
String(undefined); // "undefined"
String(); // ""
String("man") === "man" // true
typeof String("man"); // "string"

 

You can also call String as a constructor function

const human = new String("man")
typeof human; // "object"
human === "man"; // false

Auto Boxing

The constructor of both the primitive strings and the object are both the String function. It's an interesting fact that you can call .constructor on the primitive string, when we've already covered that primitive types cannot have methods!

const human = new String("man")
human.constructor === String; // true
String("man").constructor === String; // true

This is a process called autoboxing. When you try to call a property or method on certain primitive types, JavaScript will first convert it into a temporary wrapper object, and access the property / method on it, without affecting the original.

const human = "man";
human.length; // 3
human === "man"; // true

JavaScript won't complain when you try assign a property to a primitive type, because the assignment is done on that temporary wrapper object, not the primitive type itself.

Summary

Everything in JavaScript can be treated as an object. However, caution should still be taken when dealing with wrapper objects.

Functions in JavaScript are special kind of object and have additional properties.



Gary Woodfine
Latest posts by Gary Woodfine (see all)