object as function javascript code example

Example 1: object methods in javascript

/// OBJECTS IN JAVASCRIPT
const testScore = {
  damon: 89,
  shawn: 91,
  keenan: 80,
  kim: 89,
};

Object.keys(testScore);  // gives all keys
Object.values(testScore); // gives all values
Object.entries(testScore); // gives nested arrays of key-value pairs

// YOU CAN USE ( FOR-IN )  LOOP FOR ITERATION OVER OBJECTS
for (let person in testScore) {...} 

// WE CAN'T DIRECTLY USE ( FOR-OF ) LOOP IN OBJECTS BUT WE CAN DO Like THIS:
for(let score of Object.values(testScore)){
  	console.log(score)  // 89 91 80 89 
}

Example 2: adding function to objects js

var myObj = {
	myFunc: function(param){
      //do stuff
    }
}

Example 3: Object as a Function

const profileUpdate = ({ name, age, nationality, location }) => {
  /* do something with these fields */
}

Example:

const stats = {
  max: 56.78,
  standard_deviation: 4.34,
  median: 34.54,
  mode: 23.87,
  min: -0.75,
  average: 35.85
};

const half = ({ max, min }) => (max + min) / 2.0;

console.log(half(stats)); //28.015

Tags:

Java Example