Functions

Function declaration

function greet_1(){
    console.log('Hello');
}
greet_1();

function greet_2(){
    return 'HELLO';
}
console.log(greet_2());

function greet_name(firstName, lastName){
    return 'Hello ' + firstName + ' ' + lastName;
}
console.log(greet_name('John', 'Connor'));

Define default values if there’s no parameter

ES5

function greet_name(firstName, lastName){
    if(typeof firstName === 'undefined'){firstName = 'John'};
    if(typeof lastName === 'undefined'){lastName = 'Connor'};
    return 'Hello ' + firstName + ' ' + lastName;
}
console.log(greet_name());

ES6

function greet_name_3(firstName = 'John', lastName = 'Connor'){
    return 'Hello ' + firstName + ' ' + lastName;
}
console.log(greet_name_3('James', 'Bond'));

Function Expression

const square = function(x = 3){
    return x*x;
}
console.log(square());

Immediately invokable function expressions – IIFEs

IIFEs is a function to declare and run in the same time

(function(){
    console.log('IIFE Ran...');
})();

(function(name){
    console.log('Hello ' + name);
})('Gabor');

Property methods

When a function is put inside of an object it’s called a method

const todo = {
    add: function(){
        console.log('Add todo ...');
    },
    edit: function(id){
        console.log(`Edit todo ${id}`)
    }
}

todo.delete = function(){
    console.log('Delete todo ...');
}

todo.add();
todo.edit(22);
todo.delete();
Was this page helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *