Skip to main content

Declaring JS Functions in Two Ways : What's the Benefit? [Resolved]

I've come across JS code in which I see functions being declared in two different styles:

Method 1

function doSomething(){

   alert('This is one way of declaring a function');


Method 2

doSomething = function() {

    alert('And this is another way of declaring the same function');    


So what is the difference between the two and is there a case scenario where it would make sense to follow one method over the other?

PS: Sorry if the title seems vague. I didn't know the technical term used to describe the way the above two functions are declared.

Question Credit: asprin
Question Reference
Asked March 10, 2018
Posted Under: Programming
3 Answers

Method 1 is a type of function declaration, and Method 2 is a type of function expression. Knowing the names of the these two types of methods may help you in the future. There are several other stackExchanges and stackOverflows available if you still need help.


credit: Community
Answered March 10, 2018

From my experience, function expression is more found in functional programming:

const addOne = (x) => x + 1;
let array = map([1, 2, 3], addOne);

In contrast, function declaration is more common in procedural programming:

function printNames(names) {
    for (const name of names) {

function printName(name) {
    console.log(`Name: ${name}`);

or object-oriented programming:

class Wallet {
    constructor() {
        this.ballance = 0;
    deposit(x) {
        this.ballance += x;
    withdraw(x) {
        this.ballance -= x;

All valid use cases. Choice depends on your need.

credit: Franklin Yu
Answered March 10, 2018
Your Answer