Let’s talk about a surprisingly underused but powerful tool in JavaScript: the Nullish Coalescing Operator (??). If you haven’t been using this gem yet, it might just simplify your code and help you avoid some common bugs related to default values. Here’s the problem it solves: often, you want to provide a fallback or default value when a variable is undefined or null. Previously, many of us leaned heavily on the logical OR (||) operator, like this: ```javascript const userInput = ''; const displayName = userInput || 'Guest'; // displayName will be 'Guest' ``` Looks fine, right? But wait—what if the user deliberately entered an empty string, which is a valid input here? The || operator treats empty strings, 0, NaN, and false as falsy and will override those with the fallback value. That can lead to unexpected behavior. Enter the Nullish Coalescing Operator (??): ```javascript const userInput = ''; const displayName = userInput ?? 'Guest'; // displayName will be '' ``` With ??, only null or undefined triggers the fallback. Empty strings, zeros, and false remain untouched. This is a cleaner, more precise way of handling defaults. This operator is especially useful in real-world cases such as: - Config settings, where 0 or false can be valid options. - API responses, where some fields can be omitted (undefined) but others deliberately falsey. - Form inputs, where user data might legitimately be falsey but not null. Here’s a quick snippet comparing the two approaches: ```javascript function getTimeout(config) { // Using OR operator const timeoutOld = config.timeout || 3000; // Using Nullish Coalescing const timeoutNew = config.timeout ?? 3000; console.log('Old:', timeoutOld, 'New:', timeoutNew); } getTimeout({ timeout: 0 }); // Output: // Old: 3000 New: 0 ``` See how ?? correctly respects 0 as a valid value, while || doesn’t? Pro tip: avoid mixing ?? with || in the same expression, as it can cause syntax errors or produce confusing results. Use parentheses if you must combine them. So if you want to write clearer, less bug-prone JavaScript, start using the Nullish Coalescing Operator. It might be a tiny change for your code but a giant leap in clarity and correctness. Have you used ?? in your projects yet? What scenarios made you appreciate it? Let’s swap tips in the comments! #JavaScript #WebDevelopment #CodingTips #TechTrends #Frontend #Programming #DeveloperExperience
"Discover the Power of the Nullish Coalescing Operator in JavaScript"
More Relevant Posts
-
JavaScript’s Tricky Trio: call, apply, and bind — Demystified! If you’ve ever been puzzled by these three, you’re not alone. They all revolve around the mysterious this keyword — which sometimes points to the global object, and sometimes to the object that owns the method. Wouldn’t it be great if we could control what this points to? That’s exactly what these methods let us do 👇 🧠 The Big Three 1️⃣ .call() → Invokes the function immediately and lets you pass arguments one by one. 2️⃣ .apply() → Works like .call(), but accepts arguments as an array. 3️⃣ .bind() → Doesn’t execute right away; instead, it creates a new function with a fixed this and preset parameters. 🧩 Example const person = { firstName: "John", lastName: "Doe", getFullName() { return this.firstName + " " + this.lastName; } }; function greet(lang1, lang2) { console.log(`Hello, I am ${this.getFullName()} and I speak ${lang1}, ${lang2}`); } // call → run immediately greet.call(person, "English", "Spanish"); // apply → same, but arguments in an array greet.apply(person, ["French", "German"]); // bind → create a reusable version const greetPerson = greet.bind(person, "Hindi"); greetPerson("Punjabi"); ✅ Output: Hello, I am John Doe and I speak English, Spanish Hello, I am John Doe and I speak French, German Hello, I am John Doe and I speak Hindi, Punjabi ⚙️ Real-world Uses 🔹 Function Borrowing → Use methods from one object on another. 🔹 Function Currying → Create specialized versions of functions with preset parameters. Example: function multiply(a, b) { return a * b; } const multiplyByTwo = multiply.bind(this, 2); console.log(multiplyByTwo(4)); // 8 const multiplyByThree = multiply.bind(this, 3); console.log(multiplyByThree(4)); // 12 🎯 Key takeaway: 👉 .call() & .apply() → Execute now. 👉 .bind() → Save for later (with context pre-set). Once you understand how they work, they stop being scary — and become some of your most powerful tools for mastering function execution in JavaScript. #JavaScript #WebDevelopment #FrontendDevelopment #JS #CodingTips #TechLearning #WebDevCommunity
To view or add a comment, sign in
-
Today I revised some of the most essential JavaScript concepts that appear in real-world development. 1️⃣ Higher-Order Function (HOF) ✅ Question: Create a function that runs another function twice 📝 Code: function runTwice(fn) { fn(); fn(); } runTwice(() => console.log("hello")); 🔍 Short Explanation: A HOF is a function that takes another function as input or returns a function. Helps in reusable logic. 2️⃣ Pure Function 📝 Code: function pure(a, b) { console.log(a + b); } pure(2, 3); pure(2, 3); 🔍 Short Explanation: Always gives the same output for the same input. No side effects. 3️⃣ Impure Function 📝 Code: let global = 0; function imPure(a) { global++; console.log(a + global); } imPure(2); imPure(2); 🔍 Short Explanation: Depends on external data → output changes unexpectedly. 4️⃣ Destructuring in Function Parameters 📝 Code: const obj = { name: "Pratik", age: 21 }; function destructuring({ name, age }) { console.log(name, age); } destructuring(obj); 🔍 Short Explanation: Pulls values directly from objects → cleaner code. 5️⃣ Normal Function vs Arrow Function (this difference) 📝 Code: let objTwo = { name: "Pratik", fnc: function () { console.log(this); }, arrowFnc: () => { console.log(this); } }; objTwo.fnc(); objTwo.arrowFnc(); 🔍 Short Explanation: Normal function → owns its own this Arrow function → uses parent this (lexical) 6️⃣ map(): Square each number 📝 Code: let arr = [1, 2, 3, 4, 5]; let newArr = arr.map(e => e * e); console.log(newArr); 🔍 Short Explanation: Transforms each element → returns a new array. 7️⃣ filter(): Get even numbers 📝 Code: let filtered = arr.filter(e => e % 2 === 0); console.log(filtered); 🔍 Short Explanation: Keeps only the elements that match a condition. 8️⃣ reduce(): Total salary 📝 Code: let salary = [10000, 20000, 30000]; let total = salary.reduce((acc, v) => acc + v, 0); console.log(total); 🔍 Short Explanation: Reduces an array into one final value. 9️⃣ some() & every() 📝 Code: let names = ["pratik", "sun", "om", "krish", "vijay"]; let some = names.some(e => e.length > 3); let every = names.every(e => e.length > 3); console.log(some, every); 🔍 Short Explanation: some() → at least ONE matches every() → ALL must match 🔟 Object.freeze() 📝 Code: const users = { name: "Sunny", age: 21 }; Object.freeze(users); users.age = 22; users.city = "Surat"; delete users.name; console.log(users); 🔍 Short Explanation: No add, no delete, no modify → completely locked. 1️⃣1️⃣ Object.seal() 📝 Code: const test = { subject: "Maths", score: 50 }; Object.seal(test); test.score = 60; test.grade = "A"; delete test.subject; console.log(test); 🔍 Short Explanation: You can modify, but cannot add or delete keys. 1️⃣2️⃣ Optional Chaining (?.) 📝 Code: const user = { name: "Pratik", address: { city: "Surat" } }; console.log(user?.address?.city); 🔍 Short Explanation: Avoids errors when accessing nested properties.
To view or add a comment, sign in
-
Complete JavaScript Road Map🔥 A-Z JavaScript👇 1.Variables ↳ var ↳ let ↳ const 2. Data Types ↳ number ↳ string ↳ boolean ↳ null ↳ undefined ↳ symbol 3.Declaring variables ↳ var ↳ let ↳ const 4.Expressions Primary expressions ↳ this ↳ Literals ↳ [] ↳ {} ↳ function ↳ class ↳ function* ↳ async function ↳ async function* ↳ /ab+c/i ↳ string ↳ ( ) Left-hand-side expressions ↳ Property accessors ↳ ?. ↳ new ↳ new .target ↳ import.meta ↳ super ↳ import() 5.operators ↳ Arithmetic Operators: +, -, *, /, % ↳ Comparison Operators: ==, ===, !=, !==, <, >, <=, >= ↳ Logical Operators: &&, ||, ! 6.Control Structures ↳ if ↳ else if ↳ else ↳ switch ↳ case ↳ default 7.Iterations/Loop ↳ do...while ↳ for ↳ for...in ↳ for...of ↳ for await...of ↳ while 8.Functions ↳ Arrow Functions ↳ Default parameters ↳ Rest parameters ↳ arguments ↳ Method definitions ↳ getter ↳ setter 9.Objects and Arrays ↳ Object Literal: { key: value } ↳ Array Literal: [element1, element2, ...] ↳ Object Methods and Properties ↳ Array Methods: push(), pop(), shift(), unshift(), splice(), slice(), forEach(), map(), filter() 10.Classes and Prototypes ↳ Class Declaration ↳ Constructor Functions ↳ Prototypal Inheritance ↳ extends keyword ↳ super keyword ↳ Private class features ↳ Public class fields ↳ static ↳ Static initialization blocks 11.Error Handling ↳ try, ↳ catch, ↳ finally (exception handling) ADVANCED CONCEPTS -------------------------- 12.Closures ↳ Lexical Scope ↳ Function Scope ↳ Closure Use Cases 13.Asynchronous JavaScript ↳ Callback Functions ↳ Promises ↳ async/await Syntax ↳ Fetch API ↳ XMLHttpRequest 14.Modules ↳ import and export Statements (ES6 Modules) ↳ CommonJS Modules (require, module.exports) 15.Event Handling ↳ Event Listeners ↳ Event Object ↳ Bubbling and Capturing 16.DOM Manipulation ↳ Selecting DOM Elements ↳ Modifying Element Properties ↳ Creating and Appending Elements 17.Regular Expressions ↳ Pattern Matching ↳ RegExp Methods: test(), exec(), match(), replace() 18.Browser APIs ↳ localStorage and sessionStorage ↳ navigator Object ↳ Geolocation API ↳ Canvas API 19.Web APIs ↳ setTimeout(), setInterval() ↳ XMLHttpRequest ↳ Fetch API ↳ WebSockets 20.Functional Programming ↳ Higher-Order Functions ↳ map(), reduce(), filter() ↳ Pure Functions and Immutability 21.Promises and Asynchronous Patterns ↳ Promise Chaining ↳ Error Handling with Promises ↳ Async/Await 22.ES6+ Features ↳ Template Literals ↳ Destructuring Assignment ↳ Rest and Spread Operators ↳ Arrow Functions ↳ Classes and Inheritance ↳ Default Parameters ↳ let, const Block Scoping 23.Browser Object Model (BOM) ↳ window Object ↳ history Object ↳ location Object ↳ navigator Object 24.Node.js Specific Concepts ↳ require() ↳ Node.js Modules (module.exports) ↳ File System Module (fs) ↳ npm (Node Package Manager) 25.Testing Frameworks ↳ Jasmine ↳ Mocha ↳ Jest END
To view or add a comment, sign in
-
Complete JavaScript Road Map🔥 A-Z JavaScript👇 1.Variables ↳ var ↳ let ↳ const 2. Data Types ↳ number ↳ string ↳ boolean ↳ null ↳ undefined ↳ symbol 3.Declaring variables ↳ var ↳ let ↳ const 4.Expressions Primary expressions ↳ this ↳ Literals ↳ [] ↳ {} ↳ function ↳ class ↳ function* ↳ async function ↳ async function* ↳ /ab+c/i ↳ string ↳ ( ) Left-hand-side expressions ↳ Property accessors ↳ ?. ↳ new ↳ new .target ↳ import.meta ↳ super ↳ import() 5.operators ↳ Arithmetic Operators: +, -, *, /, % ↳ Comparison Operators: ==, ===, !=, !==, <, >, <=, >= ↳ Logical Operators: &&, ||, ! 6.Control Structures ↳ if ↳ else if ↳ else ↳ switch ↳ case ↳ default 7.Iterations/Loop ↳ do...while ↳ for ↳ for...in ↳ for...of ↳ for await...of ↳ while 8.Functions ↳ Arrow Functions ↳ Default parameters ↳ Rest parameters ↳ arguments ↳ Method definitions ↳ getter ↳ setter 9.Objects and Arrays ↳ Object Literal: { key: value } ↳ Array Literal: [element1, element2, ...] ↳ Object Methods and Properties ↳ Array Methods: push(), pop(), shift(), unshift(), splice(), slice(), forEach(), map(), filter() 10.Classes and Prototypes ↳ Class Declaration ↳ Constructor Functions ↳ Prototypal Inheritance ↳ extends keyword ↳ super keyword ↳ Private class features ↳ Public class fields ↳ static ↳ Static initialization blocks 11.Error Handling ↳ try, ↳ catch, ↳ finally (exception handling) ADVANCED CONCEPTS -------------------------- 12.Closures ↳ Lexical Scope ↳ Function Scope ↳ Closure Use Cases 13.Asynchronous JavaScript ↳ Callback Functions ↳ Promises ↳ async/await Syntax ↳ Fetch API ↳ XMLHttpRequest 14.Modules ↳ import and export Statements (ES6 Modules) ↳ CommonJS Modules (require, module.exports) 15.Event Handling ↳ Event Listeners ↳ Event Object ↳ Bubbling and Capturing 16.DOM Manipulation ↳ Selecting DOM Elements ↳ Modifying Element Properties ↳ Creating and Appending Elements 17.Regular Expressions ↳ Pattern Matching ↳ RegExp Methods: test(), exec(), match(), replace() 18.Browser APIs ↳ localStorage and sessionStorage ↳ navigator Object ↳ Geolocation API ↳ Canvas API 19.Web APIs ↳ setTimeout(), setInterval() ↳ XMLHttpRequest ↳ Fetch API ↳ WebSockets 20.Functional Programming ↳ Higher-Order Functions ↳ map(), reduce(), filter() ↳ Pure Functions and Immutability 21.Promises and Asynchronous Patterns ↳ Promise Chaining ↳ Error Handling with Promises ↳ Async/Await 22.ES6+ Features ↳ Template Literals ↳ Destructuring Assignment ↳ Rest and Spread Operators ↳ Arrow Functions ↳ Classes and Inheritance ↳ Default Parameters ↳ let, const Block Scoping 23.Browser Object Model (BOM) ↳ window Object ↳ history Object ↳ location Object ↳ navigator Object 24.Node.js Specific Concepts ↳ require() ↳ Node.js Modules (module.exports) ↳ File System Module (fs) ↳ npm (Node Package Manager) 25.Testing Frameworks ↳ Jasmine ↳ Mocha ↳ Jest END Hope it helps 😊🌱
To view or add a comment, sign in
-
Let's have a brief refresher on JavaScript data structures. I believe Maps and Sets are the most underrated data structures in JavaScript/TypeScript. In my opinion, they are massively useful in many cases and can reduce headaches. Let's go over the new Map() for this one: Based on the official MDN definition, which I bring here, the Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value. Map objects are collections of key-value pairs. A key in the Map may only occur once; it is unique in the Map's collection. A Map object is iterated by key-value pairs — a for...of loop returns a 2-member array of [key, value] for each iteration. Iteration happens in insertion order, which corresponds to the order in which each key-value pair was first inserted into the map by the set() method (that is, there wasn't a key with the same value already in the map when set() was called). The specification requires maps to be implemented "that, on average, provide access times that are sublinear on the number of elements in the collection". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N). Key equality: Value equality is based on the SameValueZero algorithm. (It used to use SameValue, which treated 0 and -0 as different. Check browser compatibility.) This means NaN is considered the same as NaN (even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator. Also, for object keys, equality is based on object identity. They are compared by reference, not by value. See Using the Map object for examples. Objects vs. Maps: Object is similar to Map—both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), Object has been used as Map historically. One of the common use cases of a Map can be to build an LRU data structure or cache mechanism. We have the inserted items in an ordered list, and we can have a size limit and store/read data from the cache. Official Mozilla MDN: https://lnkd.in/dyyc_cPP). Hackr io for more info: https://lnkd.in/dR-hfD8r #javascript #datastructure #algorithm #map #typescript #frontend #backend #nodejs #javascriptengineer #frontendengineer
To view or add a comment, sign in
-
-
Let’s talk about something that’s quietly changing how we write and debug JavaScript: The Power of Optional Chaining and Nullish Coalescing If you’ve ever battled nested objects in JavaScript and spent precious minutes guarding against null or undefined errors, optional chaining and nullish coalescing might just become your new best friends. Here’s the scenario: You’re working with data from APIs, user inputs, or third-party services. Sometimes, part of the data might be missing or undefined, and directly accessing deep properties can throw nasty runtime errors like “Cannot read property 'x' of undefined.” Enter optional chaining: a syntax that lets you safely access deeply nested properties without writing bulky checks. How does it look in code? Imagine you have user data that might or might not have an address object: ```javascript const user = { name: 'Jane', address: { city: 'Seattle', } }; // Traditional way const city = user && user.address && user.address.city; console.log(city); // Seattle // With optional chaining const cityOpt = user?.address?.city; console.log(cityOpt); // Seattle ``` Notice how much cleaner that is? If address is missing, cityOpt will gracefully be undefined instead of throwing an error. Now, what about default values when something is null or undefined? That’s where nullish coalescing (??) comes in. Unlike the OR operator (||), which treats many falsy values like 0 or '' as false, nullish coalescing only triggers when the value is null or undefined. Example: ```javascript const config = { timeout: 0, }; const timeout = config.timeout || 3000; // results in 3000 — not ideal if 0 is valid const timeoutFixed = config.timeout ?? 3000; // results in 0 — correct handling console.log(timeout, timeoutFixed); ``` Optional chaining + nullish coalescing together reduce boilerplate, make your code easier to read, and prevent subtle bugs. If you haven’t adopted these yet, I advise giving them a try in your next project. They’re supported in all modern browsers and Node.js versions, and once you get the hang of them, your JavaScript will feel smoother and safer. Ready to write cleaner, more robust JS? Start chaining safely today. #JavaScript #WebDevelopment #CodingTips #CleanCode #SoftwareEngineering #TechTrends #DevCommunity #Programming
To view or add a comment, sign in
-
🔥 𝐀𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 & 𝐄𝐕𝐄𝐍𝐓 𝐋𝐎𝐎𝐏 — 𝐄𝐱𝐩𝐥𝐚𝐢𝐧𝐞𝐝 𝐟𝐫𝐨𝐦 𝐒𝐜𝐫𝐚𝐭𝐜𝐡! ⚙️ 𝐓𝐡𝐞 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐧𝐠𝐢𝐧𝐞 𝐚𝐧𝐝 𝐂𝐚𝐥𝐥 𝐒𝐭𝐚𝐜𝐤 • JavaScript is a synchronous, single-threaded language, meaning it has one Call Stack where all code execution happens sequentially, one line at a time. • Execution starts with the Global Execution Context being pushed onto the Call Stack. • Function invocations also create their own execution contexts which are pushed onto and then popped off the Call Stack. -------- 🌐 𝐁𝐫𝐨𝐰𝐬𝐞𝐫 𝐒𝐮𝐩𝐞𝐫𝐩𝐨𝐰𝐞𝐫𝐬 (𝐖𝐞𝐛 𝐀𝐏𝐈𝐬) • The browser (or Node.js environment) provides extra capabilities beyond the JavaScript engine, known as Web APIs. • Examples of Web APIs include: setTimeout, the DOM (Document Object Model), fetch (for network requests), and localStorage. • These APIs allow JavaScript code to perform non-blocking (asynchronous) task. ------- 🔁 𝐓𝐡𝐞 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩, 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐐𝐮𝐞𝐮𝐞, 𝐚𝐧𝐝 𝐌𝐢𝐜𝐫𝐨𝐭𝐚𝐬𝐤 𝐐𝐮𝐞𝐮𝐞 • When an asynchronous function like 𝐬𝐞𝐭𝐓𝐢𝐦𝐞𝐨𝐮𝐭 or an 𝐞𝐯𝐞𝐧𝐭 𝐥𝐢𝐬𝐭𝐞𝐧𝐞𝐫 (𝐚𝐝𝐝𝐄𝐯𝐞𝐧𝐭𝐋𝐢𝐬𝐭𝐞𝐧𝐞𝐫) is encountered: 1. The function itself is handled by the browser's Web API environment. 2. The callback function (the code to be executed later) is registered. • Once the 𝐚𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐭𝐚𝐬𝐤is complete (e.g., the timer expires, or a button is clicked): The registered callback function is moved to the 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐐𝐮𝐞𝐮𝐞 (𝐚𝐥𝐬𝐨 𝐤𝐧𝐨𝐰𝐧 𝐚𝐬 𝐭𝐡𝐞 𝐓𝐚𝐬𝐤 𝐐𝐮𝐞𝐮𝐞 𝐨𝐫 𝐌𝐚𝐜𝐫𝐨𝐭𝐚𝐬𝐤 𝐐𝐮𝐞𝐮𝐞). • The 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 is a continuously running process that checks two main things: • Is the Call Stack empty? (i.e., is all synchronous code finished executing?) • If the Call Stack is empty, are there any functions waiting in the Callback Queue or Microtask Queue? • If the Call Stack is empty, the Event Loop picks a function from the queues and pushes it onto the Call Stack for execution. --------- ⚡ 𝐌𝐢𝐜𝐫𝐨𝐭𝐚𝐬𝐤𝐬 𝐯𝐬. 𝐌𝐚𝐜𝐫𝐨𝐭𝐚𝐬𝐤𝐬 • 𝐌𝐢𝐜𝐫𝐨𝐭𝐚𝐬𝐤 𝐐𝐮𝐞𝐮𝐞 (Higher Priority): Holds callbacks from Promises (like .then() and .catch()) and Mutation Observers. •𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐐𝐮𝐞𝐮𝐞 (Lower Priority): Holds callbacks from Web APIs like setTimeout, setInterval, and DOM event listeners. 1. 𝐌𝐢𝐜𝐫𝐨𝐭𝐚𝐬𝐤𝐬 𝐡𝐚𝐯𝐞 𝐚 𝐡𝐢𝐠𝐡𝐞𝐫 𝐩𝐫𝐢𝐨𝐫𝐢𝐭𝐲. The Event Loop will empty the entire Microtask Queue before it checks and pushes one single task from the Callback Queue onto the Call Stack. 2. If the Microtask Queue keeps adding new microtasks indefinitely, it can lead to 𝐒𝐭𝐚𝐫𝐯𝐚𝐭𝐢𝐨𝐧of the Callback Queue, preventing those tasks from ever running. -------- 🎥 Highly recommend this episode if you want to understand how JavaScript handles async code under the hood!⚡ https://lnkd.in/dpTTnJWx #JavaScript #NamasteJavaScript #EventLoop #WebDevelopment #AsyncJS #FrontendDevelopment #AkshaySaini #JavascriptMastery
To view or add a comment, sign in
-
-
💡JavaScript Array Methods — Simplified! 🧩 1️⃣ map() Definition: Creates a new array by applying a function to each element of the original array. const nums = [1, 2, 3]; const doubled = nums.map(n => n * 2); console.log(doubled); // [2, 4, 6] 🧩 2️⃣ filter() Definition: Creates a new array with elements that pass the given test condition. const nums = [1, 2, 3, 4]; const even = nums.filter(n => n % 2 === 0); console.log(even); // [2, 4] 🧩 3️⃣ find() Definition: Returns the first element that satisfies the given condition. const nums = [5, 10, 15]; const found = nums.find(n => n > 8); console.log(found); // 10 🧩 4️⃣ findIndex() Definition: Returns the index of the first element that satisfies the condition. const nums = [3, 6, 9]; const index = nums.findIndex(n => n === 6); console.log(index); // 1 🧩 5️⃣ reduce() Definition: Executes a reducer function on each element, resulting in a single output value. const nums = [1, 2, 3, 4]; const sum = nums.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 10 🧩 6️⃣ join() Definition: Joins all elements of an array into a string. const words = ['JavaScript', 'is', 'awesome']; console.log(words.join(' ')); // "JavaScript is awesome" 🧩 7️⃣ split() Definition: Splits a string into an array based on a separator. const sentence = "Hello World"; console.log(sentence.split(' ')); // ['Hello', 'World'] 💬Try combining these methods for powerful one-liners! const result = [1,2,3,4,5].filter(n=>n%2===0).map(n=>n*10); console.log(result); // [20, 40] 💡JavaScript Array Methods in Action! Ever wondered how to turn objects into readable strings, split them back, or calculate totals easily? Here’s a simple example combining map(), join(), split(), and reduce(): const users = [ { id: 1, name: "Emma", age: 22, price: 200 }, { id: 2, name: "Max", age: 32, price: 300 }, { id: 3, name: "Olivia", age: 27, price: 500 }, { id: 4, name: "John", age: 28, price: 300 } ]; // ❌ join() works on arrays of strings, not objects. // ✅ So first, map() to get only names: const nameString = users.map(user => user.name).join(", "); console.log(nameString); // Output: "Emma, Max, Olivia, John" // ✅ split() works on strings, not arrays of objects: const nameArray = nameString.split(", "); console.log(nameArray); // Output: ["Emma", "Max", "Olivia", "John"] // ✅ reduce() to calculate total price: const total = users.reduce((sum, user) => sum + user.price, 0); console.log(total); // Output: 1300 🧠 What’s happening here? map() → Extracts only the names join() → Combines them into a single string split() → Converts the string back into an array reduce() → Sums up all prices #JavaScript #WebDevelopment #Coding Ajay Suneja 🇮🇳 ( Technical Suneja )
To view or add a comment, sign in
-
Today, I explored one of the core topics in JavaScript — Operators. Understanding different types of operators like Arithmetic, Comparison, Logical, and Assignment helps in writing efficient and logical code. Every symbol in JavaScript has a purpose, and learning how they work gives more control over program logic and decision-making. Operators in JavaScript: Definition: Operators in JavaScript are special symbols or keywords that are used to perform operations on operands (values or variables). They help in performing various tasks like arithmetic calculations, comparisons, logical decisions, and assignments. Example: let x = 10 + 5; Here, + is an operator, and 10 and 5 are operands. ⚙️ Types of JavaScript Operators 1. Arithmetic Operators Arithmetic operators are used to perform mathematical calculations such as addition, subtraction, multiplication, and division. List of Arithmetic Operators: + (Addition): Adds two operands. - (Subtraction): Subtracts one operand from another. * (Multiplication): Multiplies two operands. / (Division): Divides one operand by another. % (Modulus): Returns the remainder after division. ** (Exponentiation): Raises a number to a power. ++ (Increment): Increases the value of a variable by 1. -- (Decrement): Decreases the value of a variable by 1. 2. Assignment Operators Assignment operators are used to assign values to variables. They can also perform operations and assign the result to the same variable. Examples: = → Assigns a value. += → Adds and assigns. -= → Subtracts and assigns. *= → Multiplies and assigns. /= → Divides and assigns. %= → Finds remainder and assigns. 3. Comparison Operators Comparison operators are used to compare two values. The result of a comparison operation is either true or false. Examples: == → Equal to (compares value only). === → Strict equal to (compares value and type). != → Not equal to. !== → Strict not equal to (value and type). > → Greater than. < → Less than. >= → Greater than or equal to. <= → Less than or equal to. let a = 10; let b = 5; console.log(a + b); // 15 (Addition) console.log(a - b); // 5 (Subtraction) console.log(a * b); // 50 (Multiplication) console.log(a / b); // 2 (Division) console.log(a % b); // 0 (Remainder) console.log(a ** 2); // 100 (Exponentiation) a++; // Increment console.log(a); // 11 b--; // Decrement console.log(b); // 4 let x = 10; x += 5; // x = x + 5 console.log(x); // 15 x -= 3; // x = x - 3 console.log(x); // 12 x *= 2; // x = x * 2 console.log(x); // 24 let a = 10; let b = "10"; console.log(a == b); // true (equal value) console.log(a === b); // false (equal value but different type) console.log(a != b); // false (same value) console.log(a !== b); // true (different type) console.log(a > 5); // true #javascript #webdevelopment #codingjourney #learning
To view or add a comment, sign in
-
Day 77 of 100DaysOfCode – Understanding Async/Await, JS Engine & Geolocation API 🌍 Let’s break down three key JavaScript concepts every developer should understand 👇 🔹 1. What Is Async/Await, and How Does It Work? JavaScript is asynchronous — meaning it doesn’t wait for long tasks like fetching data or file reading to finish before moving on. That’s where async/await shines. It makes async code look simple and readable, like synchronous code. async function delayedGreeting(name) { console.log("A Messenger entered the chat..."); await new Promise(resolve => setTimeout(resolve, 2000)); console.log(`Hello, ${name}!`); } delayedGreeting("Alice"); console.log("First Printed Message!"); Here, the function pauses for 2 seconds before greeting Alice — but the rest of the program keeps running! We can also handle errors neatly using try/catch: async function fetchUserData() { try { let response = await fetch(`https://lnkd.in/dWvHabH4); let userData = await response.json(); console.log(userData); } catch (error) { console.log("Error fetching user data:", error); } } Async/await = cleaner syntax + better error handling ✨ 🔹 2. How Does the JavaScript Engine Work (and What Is a Runtime)? Think of the JavaScript engine as the “brain” that reads, understands, and executes your code. For example, Google Chrome and Node.js use the V8 Engine. When you run: const greeting = "Hello, World!"; console.log(greeting); The engine: Parses the code (checks for errors) Compiles it into machine-readable bytecode Executes it to print “Hello, World!” But the JavaScript runtime is more than just the engine — it’s the whole environment your code runs in. In the browser → runtime includes the DOM, Fetch API, and timers. In Node.js → runtime includes file systems, HTTP, etc. So the engine executes, while the runtime provides tools to interact with the outside world 🌍 🔹 3. What Is the Geolocation API and How Does getCurrentPosition Work? The Geolocation API lets websites request your location — but only with your permission (for privacy reasons). Example: navigator.geolocation.getCurrentPosition( (position) => { console.log("Latitude: " + position.coords.latitude); console.log("Longitude: " + position.coords.longitude); }, (error) => { console.log("Error: " + error.message); } ); This uses your device’s GPS, Wi-Fi, or IP address to determine your location. You get a position object that contains details like: latitude longitude accuracy altitude, and more. Always explain why your app needs location data and how it’ll be used — user trust is key. 💡 Wrap-Up: Async/Await simplifies asynchronous programming. JavaScript Engine executes code; Runtime gives it superpowers. Geolocation API helps apps know “where” the user is — responsibly.
To view or add a comment, sign in
More from this author
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