Programming

How to use JavaScript symbols to overwrite default iteration behavior

In JavaScript, there’s a really cool way to attach something called symbols to objects. These JavaScript symbols constructs are basically read from the lower-level JavaScript code.

Like, think that you have an object and you want to apply a for loop over all the keys or the values, and let’s say you wanted to customize that for some reason, then you can do that easily.

const obj = {};
obj[Symbol.iterator] = function* (){
    yield 'a';
    yield 'b';
    yield 'c';
}

First, let us make an object and I could say that Symbol.iterator and I can equal that to a generator function. And inside that function, I can go ahead and yield different things like a, b, c, or something else.

Read More: Crack Wi-Fi Password using Wifite

Now whenever someone tries to loop over this object, you’ll see that it actually prints out a b c or something else you had yielded.

const obj = {
    name : "Ayon", 
    age : 18
};

obj[Symbol.iterator] = function* () {
    yield 'a';
    yield 'b';
    yield 'c';
};

for (let key of obj){
    console.log(key);
}

Even though this object could have things on it like I can say that name : “Ayon” and age : 18 and after that, if tried to print out it again it’s always going to loop over the iterator that we created. Simply it’s going to do the custom logic I decided to do.

javascript symbols

Leave a reply

Your email address will not be published. Required fields are marked *