Do you know how the JavaScript Array sort method works? There are two things you need to keep in mind when using the array sort method. ✅ The array sort method does not return a new sorted array but it changes the original array ✅ The array sort method by default sorts numbers array as strings Take a look at the below code: const numbers = [20, 55, 45, 30, 95 ]; const sorted = numbers.sort(); console.log(sorted); // [20, 30, 45, 55, 95] console.log(numbers); // [20, 30, 45, 55, 95] As you can see, the sort method changes the original array and returns a reference of the sorted array which we're storing in the 𝘀𝗼𝗿𝘁𝗲𝗱 variable. so numbers and sorted will print the same result. Now, take a look at the below code: const numbers = [100, 25, 1, 5 ]; numbers.sort(); console.log(numbers); what do you think the output of the above code will be? it's not [1, 5, 25, 100] but it's [1, 100, 25, 5] This is because when sorting numbers, each number is converted to a string. The sort method compares character by character, so the "1" in "100" is smaller than the "2" in "25" so while sorting in ascending order, 100 comes before 25. Sorting an array of objects is also a popular interview question. 𝗖𝗵𝗲𝗰𝗸 𝗼𝘂𝘁 𝘁𝗵𝗲 𝗮𝗿𝘁𝗶𝗰𝗹𝗲 𝗹𝗶𝗻𝗸 𝗶𝗻 𝘁𝗵𝗲 𝗰𝗼𝗺𝗺𝗲𝗻𝘁 𝘁𝗼 𝗹𝗲𝗮𝗿𝗻 𝗵𝗼𝘄 𝘁𝗼 𝗳𝗶𝘅 𝘁𝗵𝗲 𝗮𝗯𝗼𝘃𝗲 𝗶𝘀𝘀𝘂𝗲𝘀 𝗮𝗻𝗱 𝗮𝗹𝘀𝗼 𝗲𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴 𝗮𝗯𝗼𝘂𝘁 𝘀𝗼𝗿𝘁𝗶𝗻𝗴 𝗻𝘂𝗺𝗯𝗲𝗿𝘀, 𝗮𝗿𝗿𝗮𝘆𝘀, 𝗮𝗿𝗿𝗮𝘆 𝗼𝗳 𝗼𝗯𝗷𝗲𝗰𝘁𝘀 𝗲𝘁𝗰. 𝘍𝘰𝘳 𝘮𝘰𝘳𝘦 𝘴𝘶𝘤𝘩 𝘶𝘴𝘦𝘧𝘶𝘭 𝘤𝘰𝘯𝘵𝘦𝘯𝘵, 𝘥𝘰𝘯'𝘵 𝘧𝘰𝘳𝘨𝘦𝘵 𝘵𝘰 𝘧𝘰𝘭𝘭𝘰𝘸 𝘮𝘦. #javascript #reactjs #nextjs #webdevelopment
JavaScript Array sort method basics
More Relevant Posts
-
🔍 JavaScript Quirk: == vs === (this will surprise you) Most devs say: 👉 “Always use ===” But do you know WHY? 👇 console.log(0 == false); console.log("" == false); console.log(null == undefined); 💥 Output: true true true Wait… WHAT? 😳 Why this happens? Because == does type coercion 👉 It converts values before comparing Step by step: ✔ false → 0 ✔ "" → 0 So internally: 0 == 0 // true 👉 Special case: null == undefined → true (but NOT equal to anything else) Now compare with === 👇 console.log(0 === false); console.log("" === false); 💥 Output: false false Because === checks: ✔ Value ✔ Type No conversion. No surprises. Now the WEIRDEST one 🤯 console.log([] == false); 💥 Output: true Why? [] → "" → 0 false → 0 👉 0 == 0 Yes… JavaScript really did that 😅 💡 Takeaway: ✔ == tries to be “smart” (and fails) ✔ === is strict and predictable ✔ Use === by default 👉 "Always use ===" is not a rule… It’s survival advice. 🔁 Save this (you’ll forget this later) 💬 Comment "===" if this clicked ❤️ Like for more JS quirks #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Bug You Might Have Seen (setTimeout + loop) You write this code: for (var i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } You expect: 1 2 3 But you get: 4 4 4 This happens because of closure 📌 What is a Closure? 👉 A closure is a function along with its lexical environment. Not clear? No problem. Here’s a simpler version: 👉 A closure is a function along with the variables it remembers from where it was created. In this case: The function inside setTimeout 👉 remembers the SAME i variable And when it executes: 👉 Loop has already finished → i = 4 So all logs print: 4, 4, 4 How to fix it? ✔ Use let (creates a new variable per iteration) for (let i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔ Or create a new scope manually for (var i = 1; i <= 3; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } 💡 Takeaway: ✔ Closures remember variables, not values ✔ var shares the same scope → leads to bugs ✔ let creates a new scope per iteration 👉 If you understand closures, you’ll avoid some very tricky bugs. 🔁 Save this for later 💬 Comment “closure” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🤯 One of the most confusing concepts in JavaScript — 'this' keyword If you've worked with JavaScript, you’ve probably asked: 👉 “What exactly does ‘this’ refer to?” Here’s the simple rule: 👉 “this = Who called me?” Let’s understand with examples 👇 📌 1. Object Method const user = { name: "Vinay", greet() { console.log(this.name); } }; user.greet(); // Vinay 👉 Here, 'this' refers to the user object 📌 2. Normal Function function show() { console.log(this); } show(); // window (in browser) 👉 Here, 'this' refers to the global object 📌 3. Arrow Function const obj = { name: "Vinay", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Arrow functions don’t have their own 'this' 👉 They inherit it from the parent scope 📌 4. Event Listener button.addEventListener("click", function () { console.log(this); }); 👉 Here, 'this' refers to the clicked element 💥 Final Tip: 👉 “'this' is not about where it’s written, it’s about how it’s called.” Master this concept, and your JavaScript skills will level up 🚀 #JavaScript #WebDevelopment #Coding #DeveloperLife #Frontend #Programming #JSConcepts
To view or add a comment, sign in
-
-
🔍 JavaScript Behavior You Might Have Seen (Function Declaration vs Expression) You write this: sayHi(); function sayHi() { console.log("Hello"); } 👉 Works perfectly ✅ Now try this: sayHello(); const sayHello = function () { console.log("Hello"); }; 👉 ReferenceError ❌ Same idea… same function… Why different behavior? This happens because of Hoisting 📌 What’s happening here? 👉 Function Declarations are fully hoisted So internally: function sayHi() { console.log("Hello"); } sayHi(); 👉 That’s why it works even before definition But for Function Expressions: const sayHello = function () {} 👉 This is treated like a variable (const) So internally: const sayHello; // not initialized (TDZ) sayHello(); // ❌ error 📌 Key Difference: ✔ Function Declaration 👉 Hoisted completely (can call before definition) ✔ Function Expression 👉 Not hoisted like function 👉 Behaves like variable 📌 Bonus case 👇 var sayHello = function () { console.log("Hello"); }; sayHello(); 👉 Works (because var is hoisted) BUT: sayHello(); // before assignment 👉 TypeError ❌ (not a function yet) 💡 Takeaway: ✔ Function declarations → fully hoisted ✔ Function expressions → behave like variables ✔ let/const → TDZ error ✔ var → undefined (then TypeError if called) 👉 Same function… different behavior based on how you write it 🔁 Save this before it confuses you again 💬 Comment “function” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
#Day21 JavaScript just got a whole lot more interesting. Up until now, everything I wrote lived in the browser. Today I started working with Node.js and the fs module and for the first time, my code started talking to my computer directly. Three things clicked today: => Reading a file: "fs.readFile" opens a file sitting on your computer and prints its contents. That's it. No browser, no UI, just my code and my file system having a conversation. => Writing a file: "fs.writeFile" creates a brand new file and puts text inside it. If the file doesn't exist yet, Node creates it for you. One line of code does what used to feel like a whole process. => Appending to a file: "fs.appendFile" adds new content to an existing file without deleting what's already there. It runs after the file is created because in Node, async operations happen in sequence through callbacks. => process.on('uncaughtException'): Ending today with "process.on", this is a safety net. Instead of your program crashing with no explanation, it catches the error, tells you what went wrong, and shuts down cleanly. JavaScript isn't just a browser language. With Node.js, you can read files, write files, manage your system, and build backends all with the same language you already know. Same language. Bigger world. #NodeJS #JavaScript #M4ACELearningChallenge #BackendDevelopment #LearningToCode #WebDevelopment
To view or add a comment, sign in
-
-
The Strategy: "The 5 JS Concepts You Must Master" 📝 JavaScript isn’t hard. Your approach is. 🧠 Most beginners get stuck in "Tutorial Hell" because they try to memorize everything. In reality, you only need to master 5 core concepts to build 80% of modern web apps. If you understand these, React and Vue will feel like a breeze. 👇 ✅ 1. The DOM (Document Object Model) Stop thinking of HTML as text. It’s a tree. Learn how to grab an element, change its color, and add a click event. ✅ 2. Array Methods (.map, .filter, .reduce) Modern web dev is just manipulating lists of data. If you can’t transform an array of "Products" into "Shopping Cart" items, you'll struggle. ✅ 3. Asynchronous JS (Promises & Async/Await) The web doesn't wait for anyone. Learn how to fetch data from an API without freezing the user’s screen. ✅ 4. Scope & Hoisting Where does your variable live? Understanding let, const, and var will save you hours of debugging "Undefined" errors. ✅ 5. ES6+ Syntax Arrow functions, destructuring, and template literals. This is the "modern" way to write clean, professional code. 💡 The Golden Rule: Don't just read about these. Open VS Code, create a script.js file, and break things until they work. What was the hardest JS concept for you to wrap your head around? Let’s help each other in the comments! 💬 #WebDevelopment #JavaScript #CodingTips #LearnToCode #Frontend
To view or add a comment, sign in
-
-
The JavaScript module pattern — properly explained. Not just "use export and import." But: → Why global scope is a battlefield → How closures create privacy → What the browser does before running a single line of your module → Why modules never block your page → And where even ES Modules fall short Deep-dive guide is live. Link below. #JavaScript #WebDevelopment #Frontend
To view or add a comment, sign in
-
JavaScript Pro-Tips for Cleaner Code 👇 Save this 📌 ✅ Dynamic Object Keys const key = "status"; const obj = { [key]: "active" }; ✅ Array to Object Conversion const obj = { ...['a', 'b', 'c'] }; // { 0: 'a', 1: 'b', 2: 'c' } ✅ Deep Clone (Native) const copy = structuredClone(originalObj); ✅ Quick Integer Conversion const num = +"42"; // Faster than Number() or parseInt() ✅ Flatten Nested Arrays const flat = nestedArr.flat(Infinity); 💡 Modern JS = Less Boilerplate + Better Performance Which of these do you find most useful? Let's discuss below! 🚀 #JavaScript #CodingTips #SoftwareEngineering #Frontend #TypeScript #Developers #WebDevelopment #Coding
To view or add a comment, sign in
-
-
💡 JavaScript Essentials: Closures & Hoisting Explained Simply If you're working with JavaScript, especially in frameworks like Angular or React, understanding closures and hoisting is a must. Here’s a quick breakdown 👇 🔹 Closures A closure is created when a function remembers its outer scope even after that outer function has finished execution. 👉 Why it matters? Helps in data encapsulation Used in callbacks, event handlers, and async code Powers concepts like private variables Example: function outer() { let count = 0; return function inner() { count++; console.log(count); } } const counter = outer(); counter(); // 1 counter(); // 2 🔹 Hoisting Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 👉 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 Example: console.log(a); // undefined var a = 10; console.log(b); // ReferenceError let b = 20; 🚀 Takeaway Closures help you retain state, while hoisting explains how JavaScript reads your code before execution. Mastering these will level up your debugging skills and help you write cleaner, predictable code. #JavaScript #WebDevelopment #Frontend #Angular #React #Coding #Developers
To view or add a comment, sign in
-
One of the most underrated JavaScript features: Destructuring. Not because it's complex,but because once you truly get it, your code never looks the same again. Here's the shift it creates: BEFORE: const a = arr[0]; const b = arr[1]; const name = user.name; const age = user.age; AFTER: const [a, b] = arr; const { name, age } = user; Same logic.But destructuring goes deeper than just shorthand: ✦ Skip indexes in arrays using commas ✦ Rename variables on extraction ✦ Set default values for missing properties ✦ Use ...rest to capture everything remaining ✦ Destructure directly inside function parameters These patterns come up daily, in React, in Node.js, in any codebase that handles real data. I just published a full blog post breaking all of this down with visuals, before/after comparisons, and practical examples. Blog-link: https://lnkd.in/giGUXq7C #JavaScript #JS #WebDev #ProgrammingTips #CleanCode #SoftwareDevelopment
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