Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected equality comparison difference between == and === #83

Closed
uncenter opened this issue Nov 19, 2024 · 4 comments
Closed

Unexpected equality comparison difference between == and === #83

uncenter opened this issue Nov 19, 2024 · 4 comments

Comments

@uncenter
Copy link
Contributor

I'm struggling to understand why this equality check is different between the == and === in the following snippet:

<ul>
  {{ set items = ['A', 'B', 'C'] }}
  {{ for index, item of items }}
    <li>{{ item }}</li>
    {{ set isLast = index == (items.length - 1) }}
    {{ index }} == {{ items.length - 1 }} = {{ isLast }}
    {{# But using triple equals... #}}
    {{ set isLast = index === (items.length - 1) }}
    {{ index }} === {{ items.length - 1 }} = {{ isLast }}
  {{ /for }}
</ul>

🔗 Playground

The output of the above is:

A
0 == 2 = false 0 === 2 = false
B
1 == 2 = false 1 === 2 = false
C
2 == 2 = true 2 === 2 = false

As you can see on the last line for C, the double equals (==) compares 2 and 2 and evaluates to true, wheres the triple equals (===) compares the same 2 and 2 and evaluates to false.

@oscarotero
Copy link
Collaborator

Internally, the function to convert a value to iterator (that will be used then in the for) use Object.entries to get the key and value of an array: https://github.com/ventojs/vento/blob/main/plugins/for.ts#L61-L63

The keys are always returned as strings. For example:

Object.entries([1, 2, 3])
// [ "0", 1 ], [ "1", 2 ], [ "2", 3 ] ]

This is not what most people would expect, so I'm going to fix it.

@oscarotero
Copy link
Collaborator

fixed in v1.12.12

@uncenter
Copy link
Contributor Author

Instead of Object.entries(item).map(([key, value]) => [parseInt(key, 10), value]) you should just be able to do item.map((value, index) => [index, value]).

@oscarotero
Copy link
Collaborator

@uncenter You're absolutely right. I can't belive I missed that 🤦

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants