DEV Community

mohandass
mohandass

Posted on

Constructor function and return statement in j.s

CONSTRUCTOR FUNCTION

  • A constructor function in JavaScript is a special function used as
    blueprint to create and initialize multiple objects of the same type.

  • It defines the structure (properties) and behavior (methods) that every instance created from it will possess.

  • To create a object type we can use the constructor function.

  • It is considered to the good practice to name constructor function with an using a upper-case letter in the first letter

  • Create the constructor you must be called with the new operator

const car1={
brand: "ford",
price: 6,00,000,
color: "blue",

}

const car2{
brand: "tata",
price: 6,70,000,
color: "red",
}

  • It is the normal object creating method for car details

  • This type of method to using for two or three car details.If you can write the all ford car details so this method is too difficult

  • we can use the constructor function lets you reuse code to create many objects to easily with single line code

EXAMPLE:

EXPLANATION:

  • Create a function with write the parameters (brand,price,color)

  • Then use this to assign properties

  • Write a single line code for
    const car1 = new Car ("ford",600000,"blue")

const car2 = new Car ("tata",670000,"red")

  • Use the new keyword,when use the "new" keyword for reason is you first create a function in "car" that is the new car

  • Then Print the full object like
    console.log(car1)//Car{ brand: 'ford', price: 600000, color: 'blue' }
    console.log(car2)//Car { brand: 'tata', price: 670000, color: 'red' }

  • If you want Print individual properties
    console.log(car1.brand); // ford
    console.log(car1.price); // 600000
    console.log(car1.color); // blue


RETURN STATEMENT

  • The return statement in javascript is used inside a function to do Two main things.It stop the function from running and sends a values Back to whoever it called.

  • If the caller don't return a value.the value not used for any variable

EXAMPLE:

function add (a, b){
    return a + b;
}
 const result = add(5,20);
 console.log(result)

Enter fullscreen mode Exit fullscreen mode

OUTPUT:
25

  • Creating a function named - add

  • It's take the two parameters a and b

  • return a + b; add the two values

  • Then sends back the result

  • If you call the function with values 5 and 20// a=5 , b=20 \it calculate 5 + 20=25

  • The return sends back "5"

  • The value is stored by variable "result"

  • Then print the result output is "25"

Top comments (0)