Wednesday, February 19, 2025

JavaScript, Duck typing













What is Duck Typing in programming language like JavaScript


Duck typing is a concept in programming where an object's suitability is determined by the presence of certain methods or properties, rather than its actual type or class. The name comes from the saying, "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck."

In languages like JavaScript, duck typing means that you don't need to explicitly check or enforce the type of an object. Instead, you check if it has the required behavior (methods or properties) to perform the desired action.

For example, if you want to call a method quack() on an object, you don't care if the object is specifically a "Duck" class. As long as the object has a quack() method, it can be treated like a duck:



function makeSound(animal) {
  animal.quack(); // if the object has a 'quack' method, this works
}

let duck = {
  quack: function() { console.log("Quack!"); }
};

let person = {
  quack: function() { console.log("I am not a duck, but I can quack!"); }
};

makeSound(duck); // Output: Quack!
makeSound(person); // Output: I am not a duck, but I can quack!
In this case, both the duck and person objects can be passed to makeSound() because they both implement the quack() method, even though they are of different types. The focus is on what the object can do rather than what it "is".

No comments:

Post a Comment

Hot Topics