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
JavaScript Strings: Coercion and Equality Checks with Primitive vs Object
More Relevant Posts
-
This JavaScript array question surprises many developers 👀 🧩 JavaScript Output-Based Question (Array length + delete) ❓ What will be the output? 👉 Comment your answer below (Don’t run the code ❌) Correct Output : 11 Why this output comes? (Step-by-Step) 1️⃣ Initial array ['a','b','c','d','e'] Length = 5 2️⃣ Assigning value at index 10 array[10] = 'f'; • JavaScript creates empty slots between index 5–9 • Array becomes sparse • Length becomes highest index + 1 ➡️ Length = 11 3️⃣ Deleting the element delete array[10]; • delete removes the value • ❌ It does NOT reindex the array • ❌ It does NOT reduce length So the slot becomes empty, but length stays the same. ➡️ Final length = 11 🔑 Key Takeaways : ✔️ Array length depends on highest index ✔️ delete removes value, not index ✔️ delete does NOT change array length ✔️ Sparse arrays are common sources of bugs delete is usually a bad choice for arrays. #JavaScript #Arrays #InterviewQuestions #FrontendDeveloper #MERNStack #WebDevelopment
To view or add a comment, sign in
-
-
This JavaScript array question surprises many developers 👀 🧩 JavaScript Output-Based Question (Array length + delete) ❓ What will be the output? 👉 Comment your answer below (Don’t run the code ❌) Correct Output : 11 Why this output comes? (Step-by-Step) 1️⃣ Initial array ['a','b','c','d','e'] Length = 5 2️⃣ Assigning value at index 10 array[10] = 'f'; • JavaScript creates empty slots between index 5–9 • Array becomes sparse • Length becomes highest index + 1 ➡️ Length = 11 3️⃣ Deleting the element delete array[10]; • delete removes the value • ❌ It does NOT reindex the array • ❌ It does NOT reduce length So the slot becomes empty, but length stays the same. ➡️ Final length = 11 🔑 Key Takeaways : ✔️ Array length depends on highest index ✔️ delete removes value, not index ✔️ delete does NOT change array length ✔️ Sparse arrays are common sources of bugs delete is usually a bad choice for arrays. #JavaScript #Arrays #InterviewQuestions #FrontendDeveloper #MERNStack #WebDevelopment
To view or add a comment, sign in
-
-
A Practical Look at Type Coercion and Operator Precedence in JavaScript. console.log("3" + 2 + 5) ❌ Output: 37 ❌ Output: 10 The output is 325. Here's why: If we take a look at operator precedence and associativity in JavaScript, the + operator works left to right. Step by step 👇 1. "3" + 2 Since one operand is a string, JavaScript performs implicit type coercion(automatic, without explicit instruction) , and the + operator converts the other operand to a string , resulting in string 2 is converted into a string Result → "32" 2. "32" + 5 Again, string + number 5 becomes a string Result → "325" Now look at this 👇 console.log("3" - 2 + 5) Output: 6 Why this time? The - operator forces numeric conversion "3" becomes 3 - and + have the same precedence Both operators have the same precedence and are evaluated left to right due to associativity, So internally it becomes: console.log((3 - 2) + 5) 3 - 2 = 1 1 + 5 = 6 🧠 Key Takeaway + with a string → string coercion - always → number coercion When operators have the same precedence, they are evaluated based on associativity. For a detailed operator precedence chart, check the GeeksforGeeks (GFG) resource (link in comments). #JavaScript #TypeCoercion #OperatorPrecedence #GFG
To view or add a comment, sign in
-
#coder #javascript 🧩 JavaScript Function — easy description A JavaScript function is a block of reusable code that performs a specific task. You write it once, and you can use (call) it many times whenever you need. 📌 Why we use functions ♻️ Reuse code (no repetition) 🧹 Keep code clean & organized 🧠 Make programs easier to understand 🔧 Fix or update logic in one place 🧱 Basic structure of a function function functionName() { // code to run } ▶️ Example function sayHello() { console.log("Hello, JavaScript!"); } sayHello(); // calling the function 🟢 Output: Hello, JavaScript! 📥 Function with parameters function add(a, b) { return a + b; } add(5, 3); // 8 a and b → parameters return → sends result back 🧠 Types of functions in JavaScript Normal Function Arrow Function const greet = () => { console.log("Hi!"); }; Function with return Anonymous Function
To view or add a comment, sign in
-
-
𝗛𝗼𝘄 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗪𝗼𝗿𝗸𝘀 𝗜𝗻𝘁𝗲𝗿𝗻𝗮𝗹𝗹𝘆 You want to know how hoisting works in JavaScript. Hoisting is when JavaScript moves declarations to the top of their scope. This happens before the code is executed. JavaScript runs in two phases: - Memory Creation Phase: JavaScript parses the code and allocates memory for variables and functions. - Execution Phase: The code runs line by line. There are different types of hoisting in JavaScript: - var hoisting: Variables declared with var are fully hoisted. - let and const hoisting: Variables declared with let and const are hoisted but not initialized. - Function declaration hoisting: Function declarations are fully hoisted. - Function expression hoisting: Function expressions are not fully hoisted. When you run your code, JavaScript creates an execution context. This context has two main things: - Memory: Where variables and functions are stored. - Code: Where the code is executed line by line. Source: https://lnkd.in/d9Zen2Dc
To view or add a comment, sign in
-
✅ Why JavaScript Sorted These Numbers WRONG (But Correctly 😄) This morning’s code was: const nums = [1, 10, 2, 21]; nums.sort(); console.log(nums); 💡 Correct Output [1, 10, 2, 21] Yes — not numerically sorted 👀 Let’s understand why. 🧠 Deep but Simple Explanation 🔹 How sort() works by default 👉 JavaScript converts elements to strings first 👉 Then sorts them lexicographically (dictionary order) So the numbers become strings internally: ["1", "10", "2", "21"] Now JS sorts them like words: "1" "10" "2" "21" Which gives: [1, 10, 2, 21] 🔹 Why this is dangerous Developers expect numeric sorting: [1, 2, 10, 21] But JavaScript does string comparison by default. That’s why this bug appears in: scores prices rankings pagination 🔹 Correct way to sort numbers nums.sort((a, b) => a - b); Now JavaScript compares numbers, not strings. 🎯 Key Takeaways : sort() mutates the original array Default sort() = string comparison Numbers must use a compare function This is one of the most common JS bugs 📌 If you remember only one thing: Never trust sort() without a comparator. 💬 Your Turn Did this ever break your code? 😄 Comment “Yes 😅” or “Learned today 🤯” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
Day 8: Higher Order Functions in JavaScript If you understand Higher Order Functions, you understand real JavaScript. 💡 Because in JavaScript, functions are first-class citizens. 🔹 What is a Higher Order Function? A function that: ✅ Takes another function as an argument OR ✅ Returns another function 🔹 Example 1: Function as Argument function greet(name) { return "Hello " + name; } function processUserInput(callback) { const name = "Shiv"; console.log(callback(name)); } processUserInput(greet); Here, processUserInput is a Higher Order Function because it accepts another function as a parameter. 🔹 Example 2: Function Returning Function function multiplier(x) { return function(y) { return x * y; }; } const double = multiplier(2); console.log(double(5)); // 10 This is the foundation of: ✔️ Closures ✔️ Currying ✔️ Functional programming 🔥 Real-Life Examples in JavaScript You already use Higher Order Functions daily: array.map() array.filter() array.reduce() All of them take a function as input. #Javascript #HigherOrderFunction #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
🔄 Revising a Core JavaScript Concept: Type Coercion JavaScript has a unique behavior called type coercion — it automatically converts one data type into another during operations. Understanding this can save you from many hidden bugs. 👉 Quick examples: ✅ Number + String 1 + "2" → "12" (JavaScript converts the number to a string) ✅ String with math operator "5" - 2 → 3 (JavaScript converts the string to a number) ✅ Boolean conversion true + 1 → 2 false + 1 → 1 (true → 1, false → 0) ⚠ Equality surprise: 0 == false → true 0 === false → false 👉 “==” allows coercion 👉 “===” checks value + type (best practice) 💡 Pro tip: Prefer explicit conversion to avoid confusion: Number("5") → 5 String(10) → "10" Boolean(1) → true #JavaScript #TypeCoercion #WebDevelopment #Coding #Frontend #LearnToCode
To view or add a comment, sign in
-
Day 7: First-Class Functions, Function Statement, Function Expression & Anonymous Functions (JavaScript) JavaScript treats functions as first-class citizens. But what does that actually mean? 🔹 1️⃣ First-Class Functions In JavaScript, functions can: ✅ Be assigned to a variable ✅ Be passed as arguments ✅ Be returned from another function function greet() { return "Hello"; } function execute(fn) { console.log(fn()); } execute(greet); 👉 This ability makes concepts like callbacks, closures, and higher-order functions possible. 🔹 2️⃣ Function Statement (Function Declaration) function add(a, b) { return a + b; } ✔️ Hoisted completely ✔️ Can be called before definition 🔹 3️⃣ Function Expression const add = function(a, b) { return a + b; }; ✔️ Treated like a variable ❌ Not fully hoisted (lives in Temporal Dead Zone if let/const) 🔹 4️⃣ Anonymous Function A function without a name. setTimeout(function() { console.log("Hello"); }, 1000); 👉 Usually used in function expressions or callbacks. 🧠 Mental model to remember 🔥 Key Difference (Interview Favorite) Function Statement → Hoisted with definition Function Expression → Hoisted as variable (undefined / TDZ) Anonymous → No function name First-Class Function → Ability, not a type #Javascript #FirstClassFunction #FunctionExpression #FunctionStatement #AnonymousFunction #WebDevelopment #LearningInPublic
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development