Type Conversion in JavaScript ---------------------------------------- JavaScript supports three main types of type conversion: > String Conversion > Number Conversion > Boolean Conversion > String Conversion Use the String(value) method to convert a value into a string. Examples: String(10) // "10" String(true) // "true" String(false) // "false" String(null) // "null" > Number Conversion Use the Number(value) method to convert a value into a number. If conversion fails, it returns NaN. Examples: Number("10") // 10 Number("sdfsd") // NaN Number(false) // 0 Number(true) // 1 Number("") // 0 > Boolean Conversion Use the Boolean(value) method to convert a value into a boolean. Examples: Boolean(1) // true Boolean(0) // false Boolean("true") // true Boolean("") // false Boolean(null) // false Boolean(undefined) // false #JavaScript #JavaScriptBasics #TypeConversion #WebDevelopment #FrontendDevelopment #Programming #Coding #SoftwareDevelopment #WebDevelopers #LearnJavaScript #DeveloperCommunity #TechLearning #CodingTips #ITCareers
JavaScript Type Conversion Methods
More Relevant Posts
-
Day 11: Callback Functions in JavaScript JavaScript is single-threaded… so how does it handle async tasks? 🤔 The answer starts with Callbacks. 🔹 What is a Callback? A callback function is a function that is: ✅ Passed as an argument to another function ✅ Executed later 🔹 Basic Example function greet(name) { console.log("Hello " + name); } function processUser(callback) { const name = "Shiv"; callback(name); } processUser(greet); Here, greet is a callback function. 🔹 Async Example setTimeout(function() { console.log("Executed after 2 seconds"); }, 2000); 👉 The function runs after a delay 👉 JavaScript does not block execution 🔥 Why Callbacks Are Important ✔️ Foundation of async JavaScript ✔️ Used in APIs, event listeners, timers ✔️ Core concept before learning Promises ⚠️ The Problem: Callback Hell When callbacks are nested too much: api1(function() { api2(function() { api3(function() { console.log("Done"); }); }); }); This leads to: ❌ Hard-to-read code ❌ Pyramid structure ❌ Difficult debugging This problem was later solved using Promises and Async/Await. #Javascript #CallBack #webdevelopment #LearnInPublic
To view or add a comment, sign in
-
🚀 Day 29/30 – Design ArrayWrapper Class in JavaScript 🧠 📌 Problem : Create a class ArrayWrapper that ✅ Feature 1 – Addition (+ operator) When two instances are added: obj1 + obj2 It should return the sum of all elements in both arrays. ✅ Feature 2 – String Conversion When calling: String(obj) It should return: "[1,2,3]" Exactly like a normal array string format. 🧠 Example const obj1 = new ArrayWrapper([1,2]); const obj2 = new ArrayWrapper([3,4]); obj1 + obj2; // 10 String(obj1); // "[1,2]" String(obj2); // "[3,4]" 💡 JavaScript Solution class ArrayWrapper { constructor(nums) { this.nums = nums; } valueOf() { return this.nums.reduce((sum, num) => sum + num, 0); } toString() { return `[${this.nums.join(",")}]`; } } 🔎 Why This Works : 🔹 valueOf() JavaScript calls valueOf() when using the + operator on objects. So: obj1 + obj2 Becomes : obj1.valueOf() + obj2.valueOf() Which returns the total sum. 🔹 toString() When String(obj) is called, JavaScript invokes: 🔹 obj.toString() So we return a formatted array string. 🧠 What This Teaches ✅ Object-to-primitive conversion ✅ Operator overloading behavior in JS ✅ valueOf() vs toString() ✅ How JavaScript handles coercion internally ✅ Custom class design ⚡ Real-World Insight Date objects behave with + Number objects convert to primitives Custom libraries control serialization Understanding this means you now understand JavaScript coercion rules deeply. #JavaScript #30DaysOfJavaScript #CodingChallenge #OOP #JavaScriptInternals #FrontendDevelopment #WebDevelopment #SoftwareEngineering #LearnToCode #Programming #InterviewPrep #JSDeveloper #CleanCode #100DaysOfCode JavaScript valueOf example Override toString JavaScript class Operator overloading JavaScript JavaScript object to primitive conversion Custom class JavaScript interview question JavaScript + operator with objects Implement ArrayWrapper JS JavaScript coercion explained
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
-
-
Day 15/365 – Advanced JavaScript Interview Questions 🔥 Part4 Q1. Explain the JavaScript event loop in detail. How do microtasks and macrotasks work? Q2. What are memory leaks in JavaScript? How do you detect and prevent them? Q3. How does garbage collection work in JavaScript? Q4. What is execution context? Explain call stack, heap, and scope chain. Q5. How does this behave in different scenarios (strict mode, arrow functions, callbacks, event handlers)? Q6. What are weak collections (WeakMap, WeakSet)? When would you use them? Q7. Explain immutability. Why is it important in large-scale applications? Q8. What are design patterns you’ve used in JavaScript? (Module, Singleton, Observer, Factory) Q9. How does prototype chaining work internally? Q10. What is the difference between Object.create() and constructor functions? Q11. How do you handle race conditions in async JavaScript? Q12. What are web workers? When should you use them? Q13. How does JavaScript handle concurrency despite being single-threaded? Q14. What are pure functions? Why are they important for scalability and testing? Q15. How does debouncing/throttling differ from requestAnimationFrame-based optimizations? Q16. Explain deep cloning strategies and their performance trade-offs. Q17. How does tree shaking work in JavaScript bundlers? Q18. What is code splitting and how does it improve performance? Q19. How do you design a reusable and scalable JavaScript utility library? Q20. What JavaScript performance issues have you faced in production and how did you fix them? #javascript #interview #jsinterview #interiewprepration #webdevelopment #js #performace #optimization #365daysofjs
To view or add a comment, sign in
-
JavaScript Array Methods — Explained Visually If JavaScript array methods ever felt confusing, this visual will make them click instantly Instead of memorizing definitions, focus on how data actually transforms step by step. 🔹 map() → transforms every element 🔹 filter() → selects matching elements 🔹 find() → returns the first match 🔹 findIndex() → gives the position 🔹 fill() → fills with a static value 🔹 some() → checks if any element matches 🔹 every() → checks if all elements match Why this matters: Understanding array methods is essential for: ✅ Writing clean JavaScript ✅ Cracking frontend interviews ✅ Working with React & modern JS Save this post for quick revision before coding 📌 #JavaScript #ArrayMethods #WebDevelopment #Frontend #Coding #DSA #LearnJavaScript #ProgrammingBasics
To view or add a comment, sign in
-
-
🚀 Understanding Hoisting in JavaScript Hoisting is one of the most commonly asked topics in JavaScript interviews — and also one of the most misunderstood. In JavaScript, variable and function declarations are moved to the top of their scope during the creation phase of execution. This process is called hoisting. Example: console.log(a); // undefined var a = 10; Behind the scenes, JavaScript treats it like this: var a; console.log(a); // undefined a = 10; 🔹 Key Points: • var is hoisted and initialized with undefined • let and const are hoisted but stay in the Temporal Dead Zone • Function declarations are fully hoisted • Function expressions are not fully hoisted Example: sayHello(); // Works function sayHello() { console.log("Hello!"); } But: sayHi(); // Error const sayHi = function() { console.log("Hi!"); }; 💡 Tip: Hoisting happens during the execution context creation phase, before the code runs. Understanding hoisting makes debugging easier and strengthens your JavaScript fundamentals. #JavaScript #WebDevelopment #Frontend #Programming #React #InterviewPrep
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
-
-
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
-
-
JavaScript has primitive and reference types. 🧩 ❓ Why do objects behave differently during assignment? In JavaScript, values are stored in two different ways: by value and by reference. 🔹 Primitive types (stored by value) Primitives like number, string, boolean, null, undefined, symbol, and bigint store the actual value. let a = 10; let b = a; b = 20; console.log(a); // 10 ✅ Here, b gets a copy of a. Changing b does not affect a. 🔹 Reference types (stored by reference) Objects, arrays, and functions store a reference (address in memory), not the actual value. let obj1 = { name: "Isnaan" }; let obj2 = obj1; obj2.name = "Ashraf"; console.log(obj1.name); // "Ashraf" 😮 Both variables point to the same object in memory. Changing one affects the other. ⚠️ Why this matters This behavior can cause unexpected bugs if you think you’re copying an object but actually sharing it. 💡 Best practice To avoid side effects, create a copy using: let newObj = { ...obj1 }; Takeaway: Primitives are copied. Objects are shared. Understanding this saves hours of debugging. #learnwithisnaan #mernstackdeveloper #fullstackdeveloper #javascript #freelancer
To view or add a comment, sign in
-
-
🚀 **JavaScript: var vs let vs const (Explained Clearly)** If you're learning JavaScript or preparing for interviews, this is a concept you MUST understand 👇 --- ## 🔹 var ```js var name = "Ali"; var name = "Ahmed"; // ✅ Allowed name = "John"; // ✅ Allowed ``` ✔ Function scoped ✔ Can be redeclared ✔ Can be updated ⚠ Problem: Can cause unexpected bugs due to scope issues. --- ## 🔹 let ```js let name = "Ali"; let name = "Ahmed"; // ❌ Error name = "John"; // ✅ Allowed ``` ✔ Block scoped ❌ Cannot be redeclared in same scope ✔ Can be updated ✅ Use when the value needs to change. --- ## 🔹 const ```js const name = "Ali"; name = "Ahmed"; // ❌ Error ``` ✔ Block scoped ❌ Cannot be redeclared ❌ Cannot be reassigned ✅ Use by default in modern JavaScript. --- ## 💡 Best Practice (Modern JS Rule) 👉 Use **const** by default 👉 Use **let** when value needs to change 👉 Avoid **var** --- ### 🎯 Interview Tip Most scope-related bugs happen because of `var`. Understanding block scope vs function scope makes you a stronger developer. --- https://lnkd.in/gzGAbU8A 💬 Quick question: Do you still use `var` in your projects? #JavaScript #FrontendDevelopment #WebDevelopment #Programming #CodingInterview #JSConcepts #SoftwareEngineering #FullStackDeveloper #LearnToCode #DeveloperTips #100DaysOfCode #TechCommunity
To view or add a comment, sign in
-
Explore related topics
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