Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am curious why we use cache[n] in this code [duplicate]

Tags:

javascript

I am new to JS and came across this code:

let cache={};

function memoizedAddTo80(n) {
    if (n in cache) {
        return cache[n]
    } else {
        cache[n]= n+80;
        return cache[n]
    }
}

The question is what is cache[n]?, I mean, why do we use [n] after cache. Is cache[n] equal to cache.n Or???

like image 856
Dickens Avatar asked Dec 06 '25 08:12

Dickens


1 Answers

n is a variable. Consider:

var n = "foo";
return cache[n];

This would be equivalent to cache.foo

like image 199
SpoonMeiser Avatar answered Dec 08 '25 20:12

SpoonMeiser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!