JavaScript Strings: Coercion and Equality Checks with Primitive vs Object

While revisiting JavaScript strings, I explored different ways to create then and how they behave with equality checks. let u = "23"; let v = new String(23); let w = v.toString(); let x = 23; a) console.log(u==x); // true (string "23" is coerced into number 23) b) console.log(v); // [String: '23'] c) console.log(typeof(v)); // object d) console.log(typeof(w)); // string e) console.log(w); // 23 f) console.log(u===x); // false  ( a string is not equal to number when using strick equality) What I learned: 1) "23" is a primitive string 2) new String( 23 ) creates a String object, not a primitive 3) Because of that: a) typeof v -> "object" b) Its wrapped in a box object 4) == performs type coercion 5) === checks both value and type Until absolutely necessary, avoid using new String( ). JavaScript works best with primitive strings, and strict equality (===) helps prevent subtle bugs and unexpected behavior. #JavaScript #LearningInPublic #Code #WebDevelopment

To view or add a comment, sign in

Explore content categories