Skip to content

JavaScript class vs function

  • by

In JavaScript, both classes and functions are used to define reusable code blocks, but they have different syntax and purposes. Let’s explore the differences between JavaScript classes and functions.

1. Syntax:

Functions can be defined using function declarations or function expressions.

// Function declaration
function myFunction() {
  // function body
}

// Function expression
const myFunction = function() {
  // function body
};

Classes were introduced in ECMAScript 2015 (ES6) and provided a more structured way of defining reusable code. They use the class keyword.

class MyClass {
  constructor() {
    // constructor body
  }
  
  myMethod() {
    // method body
  }
}

2. Object Creation:

Functions in JavaScript can be used to create objects using constructor functions or factory functions. Constructor functions are invoked using the new keyword to create instances.

function Person(name) {
  this.name = name;
}

const john = new Person("John");

Classes are primarily used to create objects using the new keyword. The constructor method is used to initialize object properties.

class Person {
  constructor(name) {
    this.name = name;
  }
}

const john = new Person("John");

3. Inheritance

JavaScript functions can be used to achieve inheritance using prototypes and the prototype chain. By attaching methods to the prototype of a function, those methods can be inherited by objects created from that function.

function Animal(name) {
  this.name = name;
}

Animal.prototype.sayName = function() {
  console.log(this.name);
};

function Dog(name, breed) {
  Animal.call(this, name);
  this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype);

const myDog = new Dog("Max", "Labrador");
myDog.sayName(); // Outputs: Max

Classes provide a more intuitive way to implement inheritance using the extends keyword. Subclasses can inherit properties and methods from parent classes.

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  sayName() {
    console.log(this.name);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
}

const myDog = new Dog("Max", "Labrador");
myDog.sayName(); // Outputs: Max

4. Usage and Features:

  • Functions are versatile and can be used for a wide range of purposes. They can be used as regular functions, callbacks, event handlers, and more. Functions can also be assigned to variables, passed as arguments, or returned from other functions.
  • Classes provide a more structured and intuitive way to define object-oriented code. They promote code organization and encapsulation by grouping related properties and methods together. Classes support constructor methods, instance methods, static methods, and getters/setters.

Here’s a tabular comparison of JavaScript classes and functions:

#FunctionsClasses
SyntaxFunction declarations or function expressionsIntroduced in ES6, use the class keyword
Object CreationConstructor functions or factory functionsInvoked using the new keyword
InheritancePrototypes and the prototype chainextends keyword for subclassing and inheritance
UsageVersatile, used for various purposesPromote structured, object-oriented code with encapsulation and grouping
FeaturesRegular functions, callbacks, event handlers, etc.Constructor methods, instance methods, static methods, getters/setters

JavaScript class vs function example

Simple example code that demonstrates the difference between a JavaScript class and a function:

// Using a class
class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  calculateArea() {
    return this.width * this.height;
  }
}

const rectangle1 = new Rectangle(5, 10);
console.log(rectangle1.calculateArea()); // Output: 50

// Using a function
function calculateRectangleArea(width, height) {
  return width * height;
}

const area = calculateRectangleArea(5, 10);
console.log(area); // Output: 50

Output:

JavaScript class vs function

In this example, we define a class called Rectangle using the class keyword. The class has a constructor that initializes the width and height properties, and a calculateArea method that returns the area of the rectangle.

We create an instance of the Rectangle class called rectangle1 and invoke the calculateArea method on it to calculate and log the area.

On the other hand, we define a function called calculateRectangleArea that takes the width and height as parameters and directly calculates the area using the formula. We call the function with the values 5 and 10 to calculate the area and log it.

Both approaches achieve the same result of calculating the area of a rectangle, but they differ in syntax and how the code is structured. Classes provide a more organized and object-oriented approach, while functions offer flexibility for a wide range of use cases.

Comment if you have any doubts or suggestions on this JS basic topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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