variable in default constructor javascript code example
Example 1: javascript constructor default parameter
function greet(name, greeting, message = greeting + ' ' + name) {
return [name, greeting, message]
}
greet('David', 'Hi') // ["David", "Hi", "Hi David"]
greet('David', 'Hi', 'Happy Birthday!') // ["David", "Hi", "Happy Birthday!"]
Example 2: javascript class constructor
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person("John Doe", 23);
console.log(person.name); // expected output: "John Doe"
Example 3: constructor in js
A constructor is a function that creates an instance of a class
which is typically called an “object”. In JavaScript, a constructor gets
called when you declare an object using the new keyword.
The purpose of a constructor is to create an object and set values if
there are any object properties present.