JavaScript

JavaScript functions

Everything about functions

Photo by T S on Unsplash

The definition of functions👀

We define functions everywhere in our projects all the time. At first, a function can be assigned to a variable, and we called it Function Expression or if we start the definition from the built-in word function, we call this Function Declaration. Nothing interesting, saying you. And why we have two methods to do the same thing? The reason is they are slightly different.

function myFuncDeclaration() {} (1)const myFuncExpression = function() {} (2)
myFuncDeclaration(); // 'myFuncDeclaration called'
function myFuncDeclaration() {
console.log('myFuncDeclaration called');
}
// Uncaught ReferenceError: Cannot access 'myFuncExpression' before // initialization
myFuncExpression();
const myFuncExpression = function() {
console.log('myFuncExpression called');
}
const arrowFnExpression = () => {};

Let it work!

Let’s go ahead 🐾, we’ve already defined function with all staff inside. How can we make the function’s code work and how it can influence the other functions? There are several methods for doing this. Here they are:

(function immediatelyCalledFn(a, b, c) {
console.log(a + b + c);
})(1,2,3); // 6
const immediatelyCalledExpr = (function(a, b, c){
console.log(a + b + c);
})(1, 2, 3); //
console.log(immediatelyCalledExpr); // undefined
console.log(immediatelyCalledFn); // error immediatelyCalledFn is not defined
const myFn(a, b, c) {
return a + b + c;
}
myFn(1, 2, 3); // 6
const myCreatorFn = function(a, b, c) {
this.calculateCurrentSum = () => {
console.log(a + b + c);
};
this.updateFirst = (num) => {
a *= num;
};
}
const obj1 = new myCreatorFn(1, 2, 3);
const obj2 = new myCreatorFn(4, 5, 6);
obj1.calculateCurrentSum(); // 6
obj2.calculateCurrentSum(); // 15
obj1.updateFirst(3);
obj1.calculateCurrentSum(); // 8
obj2.calculateCurrentSum(); // 15
class myCreatorFn {
constructor(a, b, c) {
this.a = a;
this.b = b;
this.c = c;
}
calculateCurrentSum() {
console.log(this.a + this.b + this.c);
}
updateFirst(num) {
this.a *= num;
}
}
const obj1 = new myCreatorFn(1, 2, 3);
const obj2 = new myCreatorFn(4, 5, 6);
obj1.calculateCurrentSum(); // 6
obj2.calculateCurrentSum(); // 15
obj1.updateFirst(3);
obj1.calculateCurrentSum(); // 8
obj2.calculateCurrentSum(); // 15

Function like an object. Static properties.

Function Declaration and Function Expression are the most commonly used methods of a function definition, but despite them, we have the Function constructor, so we can define function this way also:

const argumentsStr = "test";
const functionDefStr = 'console.log(argumentsStr);';
const myFuncObject = new Function(argumentsStr, functionDefStr);
myFuncObject(); // test
function showUpdate(data) {
console.log(data );
}
getData.previousData = [];// invoke function every 5 minutes
const interval = setInterval(getData, 300000);
function getData() {// mock random data, integers from 1 to 15
const newDataFromDb = Math.floor(Math.random() * 15) + 1;
// check how many differen pices of data we have
// stop invokations when it's equal to 10
if (getData.previousData.length === 10) {
getData.previousData = [];
clearInterval(interval);
}
// check if current new data
// show them if they're really new
if (!getData.previousData.includes(newDataFromDb)){
getData.previousData.push(newDataFromDb);
showUpdate(newDataFromDb);
}
}
class myClass {
static staticVariable = 'static variable';
static staticFn(data) {
return 'Method called with ' + data;
}
}
console.log(myClass.staticFn('readers')); // Method called with readers
console.log(myClass.staticVariable); // static variable

What hides between curly brackets?

So, while we are implementing a function definition we also have a list of parameters between curly brackets — local variables and a list of arguments between the round brackets. Also inside the function’s body, we often use two magic keywords return and this. So let’s lay it out in order.

function showReturned() {
const data = 'any data';
return data;
console.log(data); // it won't be called
}
console.log(showReturned()); // 'any data'
console.log(data); // error: data isn't defined

Note: If you’re writing ES6 compatible code, then rest parameters should be preferred.

The code below shows the difference:

// args - variable, which contain all rest arguments after num
function restFromDevisionSpread(num, ...args) {
console.log(...args);
const filteredData = [...args].filter((arg) => (arg%num === 0));
return filteredData;
}
restFromDevisionSpread(3, 8, 12, 6, 7); // [12, 6]
function restFromDevisionArguments(num) {
const removed = arguments.shift();
const filteredData = arguments.filter((arg) => arg%num === 0);
return filteredData;
}
restFromDevisionArguments(3, 8, 12, 6, 7); // error: shift is not a function
const myFn1 = function(n) {
console.log('some data was received: ' + n);
}
const myFn2 = function(callback) {
let someData = null;
setTimeout(() => {
someData = 'data from parent function';
callback(someData);
}, 2000);
console.log(someData);
}
myFn2(myFn1);
// we will se in console
// null
// some data was received: data from parent function
'use strict';
console.log(this, ' - Global scope');
function myFn() {
console.log(this, ' - Local scope');
}
const myArrowFn = () => {
console.log(this, ' - Arrow function, so Global scope');
}
myFn();
myArrowFn();
/** We will see in console:
Window - Global scope
undefined - Local scope
Window - Arrow function, so Global scope
**/
let person = {
name: 'Sezar',
sayName: function() {
console.log(this.name, '- Local scope contained properties of object - person');
},
sayArrowName: () => {
console.log((this.name || 'empty'), '- Arrow function, so Global scope doesn\'t have property name');
}
};
person.sayName();
person.sayArrowName();
/** We will see in console:
Sezar - Local scope contained properties of object - person
empty - Arrow function, so Global scope doesn't have property name
**/
class Student { 
constructor(name, specialization) {
this.name = name;
this.specialization = specialization;
}
}
const studentFunction = function(grade, gender) {
console.log('Name: ', this.name, '\n');
console.log('Specialization: ', this.specialization, '\n');
console.log('Grade: ', grade, ', Gender: ', gender);
}
const student1 = new Student('Sezar', 'Artist');
const student2 = new Student('John', 'Data scientist');
const showInfo1 = studentFunction.bind(student1, 3, 'M');
const showInfo2 = studentFunction.bind(student2, 3, 'M');
// Name: Sezar
// Specialization: Artist
// Grade: 3 , Gender: M
showInfo1();
// Name: John
// Specialization: Data scientist
// Grade: 3 , Gender: M
showInfo2();
// Name:
// Specialization: undefined
// Grade: 3 , Gender: M
studentFunction(3, 'M');
console.log('----call----');
studentFunction.call(student1, 4, 'M');
studentFunction.call(student2, 5, 'F');
console.log('----apply----');
studentFunction.apply(student1, [2, 'F']);
studentFunction.apply(student2, [5, 'M']);

Interaction between functions (closure)

We’ve already spoken about the connection between functions when mentioned Callback Functions. But we haven’t thought about the situation when a function defined inside the other function.

function Counter() {
let _num = null; // encapsulated variable
return {
set number(num) {
_num = num;
},
get number() {
return _num;
},
increase() {
if (_num === null) {
console.error("Set initial value to increase it!");
} else {
_num++;
}
} // increase
}
}
const counter1 = new Counter();
const counter2 = new Counter();
counter1.increase(); // Set initial value to increase it!
counter1.number = 5;
console.log(counter1.number); // 5
counter1.increase();
console.log(counter1.number); // 6
counter1.increase();
console.log(counter1.number); // 7
console.log(counter2.number); // null

Conclusion

Functions in JavaScript played the main role and have a lot of abilities to make the life of programmers easier or bring a lot of headaches. I wish you to use them smartly. Keep your code clean, maintainable, and readable. Thank you for reading! ❤️

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store