Functions
There are a couple of ways of defining a function in JavaScript. These are the most common:
function sum(a, b) {
return a + b;
}
var sum = function(a , b) {
return a + b;
}
Using ES6 arrow functions:
let sum = (a, b) => a + b;
Then you can call the function like:
let result = sum(40, 2);
// => 42
Constructors and Classes
There are a couple of ways you can obtain a class-like functionality in JavaScript.
Factory functions
Creating an object and returning it.
function Person(name) {
var self = {};
self.name = name;
self.getName = function() {
return this.name;
};
return self;
}
var p = Person('Alice');
console.log(p.getName());
// => "Alice"
Using prototypes
By adding a method in the prototype
object of a function, you're adding that method as a public method to all the instances of that class.
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
var p = new Person('Frank');
console.log(p.getName());
// => "Frank"
Using ES6 classes
class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
var p = new Person('Jim');
console.log(p.getName());
// => "Jim"
It's very easy to inherit classes in ES6:
class Musician extends Person {
constructor(name, instrument) {
// Call the base class
super(name);
this.instrument = instrument;
}
play () {
console.log(`${this.getName()} is playing ${this.instrument}`);
}
}
var me = new Musician('Johnny B.', 'piano');
// Get the name of the musician, who is also a person
console.log(me.getName());
// => "Johnny B."
me.play();
// => "Johnny B. is playing piano."
Async vs Sync
Sometimes you have to wait a little bit for things to be done: such as when making a cake, you have to work on it and you have to wait a while for it to be ready. Most familiar things in our lives are asynchronous.
Sync
Usually, synchronous operations send the response directly, using thereturn
keyword:
// Synchronous sum
function sum(a, b) {
return a + b;
}
var result = sum(40, 2);
// => 42
Async
To have an async function, you need a source of asynchronous "stuff." In this example, we will use the setTimeout
function. It accepts a function as first argument (which is a callback function) and a number as a second argument—representing the time delay after the function is called:
function asyncSum(a, b, cb) {
setTimeout(function() {
cb(a + b);──────────┐
}, 1000); │
} ⋁
asyncSum(40, 2, function(result) {
console.log(result);
// => 42
});
What are Callbacks?
Callbacks are functions which are sent as an argument to another function and are invoked when something happens.
function Cake(){/* Dummy class-like constructor */}
var busy = false;
function makeCake(callback) {
if(busy) {
return callback(new Error('Already busy with creating a cake. Please wait a bit and try again later.'));
}
busy = true;
setTimeout(function() {
callback(null, new Cake());
busy = false;
}, 1000);
}
makeCake(function (err, cake) {
if(err) {console.error(err);}
console.log('Made a cake.');
});
setTimeout(function() {
makeCake(function(err, cake) {
if(err) {console.error(err);}
console.log('Made a cake.');
});
}, 2000);