Pass Object as an argument in Javascript

Last Updated: January 19, 2021

I have defined product as below

function Product(name){
    this.name=name,
    this.category="food",
    this.price=10,
    this.getDiscount=function(){
      return this.price*5/100
    }
}

Now I am going to create an object using above constructor function
var product= new Product("Burger")

Now I want to change that object to represent drink name Coca Cola
Lets define method to change its properties

function changeProduct(product){
    product.name="Coca Cola";
    product.category="Drink";
    product.price=12;

}

Here you are passing reference to the product object. So whatever changes inside the function will change the original object

Now we can call the changeProduct() method
>changeProduct(product)
Then you can call the getDiscount() method to see changes
>console.log("Discount is "+product.getDiscount())
>Discount is 0.6