setter javascript code example

Example 1: set js

// Use to remove duplicate elements from the array 

const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]

//spreading numbers of the object into an array using the new operator
console.log([...new Set(numbers)]) 

// [2, 3, 4, 5, 6, 7, 32]

Example 2: getters and setters javascript

let obj = {
  log: ['a', 'b', 'c'],
  get latest() {
    if (this.log.length === 0) {
      return undefined;
    }
    return this.log[this.log.length - 1];
  }
};

obj.log.push('d');
console.log(obj.latest); //output: 'd'

Example 3: set in javascript

// set is used for storing unique values
const firstSet = new Set([1, 2, 3]);

firstSet.add('hi'); //adding value to set

firstSet.add(3); //this will not give any error and it will also not be added

firstSet.delete('hi');//removing value from set

console.log(firstSet.has('hi'));//checking 'hi' is in the set or not

// showing all values in the set
console.log(firstSet);
for (const entry of firstSet.values()) {
    console.log(entry);

Example 4: javascript getters and setters

/*Getter functions are meant to simply return (get) the value of an object's 
private variable to the user without the user directly accessing the private 
variable.*/
/*Setter functions are meant to modify (set) the value of an object's private 
variable based on the value passed into the setter function. This change could
involve calculations, or even overwriting the previous value completely.*/
class Book {
  constructor(author) {
    this._author = author;
  }
  // getter
  get writer() {
    return this._author;
  }
  // setter
  set writer(updatedAuthor) {
    this._author = updatedAuthor;
  }
}
const novel = new Book('anonymous');
console.log(novel.writer);  // anonymous
novel.writer = 'newAuthor';
console.log(novel.writer);  // newAuthor

Example 5: javascript class setter

const language = {
  set current(name) {
    this.log.push(name);
  },
  log: []
}

language.current = 'EN';
language.current = 'FA';

console.log(language.log);