⊗jsSpSyOF 55 of 281 menu

Function in an object in JavaScript

Using symbols, functions can be added to objects and these functions will not participate in the looping. Let's try. Let's have an object:

let obj = {a: 1, b: 2, c: 3};

Let's create a symbol:

let sym = Symbol();

Write a function to an object with a key in the form of our symbol:

obj[sym] = function() { console.log('!!!'); };

When iterating over the object, our function will not be iterated:

for (let key in obj) { console.log(obj[key]); // 1, 2, 3 }

We get our function by passing our symbol (the same variable) as a key:

let func = obj[sym]; func();

We can shorten the code:

obj[sym]();

Add a function to the object that will display the current time. Call this function.

enru