Stellar Code

Full-stack Web Development with JavaScript (MERN stack)

JavaScript First Principles: #2. Functions, Methods & Objects

General

As I have mentioned in previous posts, computers require very detailed instructions (a.k.a Scripts) about what we want them to do) every single time we want it, as if it were their first time. These scripts can become very complex and run to thousands of lines but Functions, Methods and Objects help developers organize their code.

 

Functions

Functions let you group a series of statements together into a block of code that performs a specific end-goal/task. For instance if I wanted to make coffee, I would write specific actions I need to take as statements/scripts that will result in a coffee being made at the end. I could name this function as makeCoffee (tip: you could name it whatever) and declare it this way:

function makeCoffee() {
// here goes the instructions. Note the use of closed brackets,  and curly brackets.
}

Functions also allow for re-usability. Still the coffee analogy, imagine if I had to program a human robot to behave as humans do for every day of the week & this robot has to take coffee every morning, I would simply call the function I have already defined once before to help achieve me make this happen. I would call it for everyday of the week.

They are simply called by writing the name of the function, followed by closed brackets and a semi-colon. How that’s done:

makeCoffee();

Remember that statements are usually ended with semi-colons. Furthermore, some functions need to be provided with information in order to achieve a given task. The pieces of information passed in to a function are called Parameters. Say I want to calculate the area of a box, I need the function to know that it needs a width & height to do so I would pass them in as parameters. I will write that code this way:

function findArea(width, height) {
	var area = width * height;
	return area; 
}

The return word is used in functions that must output a needed value (I our case, it’s the value of area). The parameters passed into the above function are variables that could change, but you’ll need the function to behave the same i.e finding an area. So if I called

findArea(5,2);

  // 5 wil be used as width & 2 will be used as height & the returned value will be 10. OR

 findArea(3, 10);

 // width of 3 & height of 10, the returned value will be 30 

 

So far, we’ve dealt with the default way of getting function declaration. For use cases like the area-of-a-box example where we expect a value, we could also use Function expressions a.k.a Anonymous functions.
Anonymous functions allow us to declare a function as a JavaScript expression & without a name as opposed to the default function declaration. It is expressed as:

var area = function(width, height) {
return width * height;
}

This can further allow us to do something like this:

var size = area(3, 4);

There are also functions called Immediately Invoked Function Expressions (IIFE). There are used in situations where there are many scripts and we don’t want certain variables in a script to conflict with variables from other scripts. When we define IIFEs, we allow a JavaScript interpreter to execute them immediately they encounter. These are defined as

var area = (function() {
var width = 3;
var height = 2;
return width * height;
}());

The closed brackets highlighted in green tell the JavaScript interpreter to call the function immediately. The red brackets covering the entire function tells the interpreter to treat it as an expression.


Objects

Objects are simply collection of name: value pairs i.e Variables or Functions that have a name and a value. They are separated by a colon. But the names are referred to as keys. Note that:

In an Object, Variables become known as Properties and Functions become known as Methods.

 

Objects and their data are used in computers to model real world objects. This helps computers have an idea of what a real world objects is. Take for example a Hotel called Garden, its object would look like this:

var hotel = {
	name: 'Garden',
	rooms: 40,
	booked: 25,
	gym: true,
	roomTypes: ['twin', 'double', 'suite'],
	checkAvailability: function() {
		return this.rooms - this.booked;
	}
}

If a hotel website had to hold data for different hotels, the above object would be created for all other hotels. e.g

var hotel = {
	name: 'Hilton',
	rooms: 1400,
	booked: 900,
	gym: true,
	roomTypes: ['twin', 'double', 'suite'],
	checkAvailability: function() {
		return this.rooms - this.booked;
	}
}

The way we created the objects above is using the Literal Notation. However there is another way called the Constructor Notation.

The Constructor Notation uses the new keyword and something called object constructor, Object() to create a blank object. Note that JavaScript is case-sensitive, hence object() is not the same as Object(). Use capital ‘O’. We use constructor this way

var hotel = new Object();
hotel.name = 'Sheraton';
hotel.rooms = 100;
hotel.booked = 30;
hotel.checkAvailability = function() {
	return this.rooms - this.booked;
	};

Having created the object, we went further to add properties and methods to it using the dot notation. The Dot notation is simply a way to access the properties or methods of a JavaScript object using .. For instance, to access the number of booked rooms in a hotel, I use:

hotel.booked;

which will return the number for the concerned hotel (25, 30 or 900).
We can also update the value by accessing where the value is we want to change:

hotel.booked = 30;

 


Also published on Medium.


Emmanuel Yusufu

Web Developer. Learning enthusiast.