Skip to main content

One post tagged with "JS"

JS tag description

View All Tags

Understanding the JavaScript

· 2 min read
Vikram
Software Architect

Overview

Every programming language has unique features. The better a developer knows these, the more enjoyable coding becomes. Often, developers who become experts in one language are hesitant to switch to another. This expertise not only makes coding fun but also makes you a pro in that language.

I've been coding in JavaScript for years and have found many useful examples. I always wanted to put them together for reference but never did. Now, I finally have the chance. I'll use this blog to share these examples, so this page will be updated often.

== vs ===

In JavaScript, we usually use === to compare two variables. In my experience interviewing developers or having casual conversations, I've noticed most know that === checks the variable type, whereas == does not. However, many don't understand what this truly means.

The main issue with == is that JavaScript tries to convert both variables to the same type before comparing them, which can affect performance. Here's an example to understand it better:

Live Editor
function Test(){
    let str1 = "1";
    let bol1 = true;
    let arr1 = [];
    let obj1 = {};
    return(<>
        <div>
            Compare str1 == 1 : 
            <b>
                {str1 == 1 ? "They are same": "They are different"}
            </b>
        </div>
        <div>
            Compare bol1 == 1 : 
            <b>
                {bol1 == 1 ? "They are same": "They are different"}
            </b>
        </div>
        <div>
            Compare arr1 == 1 : 
            <b>
                {arr1 == 1 ? "They are same": "They are different"}
            </b>
        </div>
        <div>
            Compare obj1 == 1 : 
            <b>
                {obj1 == 1 ? "They are same": "They are different"}
            </b>
        </div>

        <hr/>
        <div>
            Compare str1 === 1 : 
            <b>
                {str1 === 1 ? "They are same": "They are different"}
            </b>
        </div>
        <div>
            Compare bol1 === 1 : 
            <b>
                {bol1 === 1 ? "They are same": "They are different"}
            </b>
        </div>
        <div>
            Compare arr1 === 1 : 
            <b>
                {arr1 === 1 ? "They are same": "They are different"}
            </b>
        </div>
        <div>
            Compare obj1 === 1 : 
            <b>
                {obj1 === 1 ? "They are same": "They are different"}
            </b>
        </div>

    </>)
}
Result
Loading...

When comparing primary data types, JavaScript casts them to the same type. That's why String, Boolean, Number often return true when compared.