Stop Using Window in Your JavaScript Code, There’s a Better Way! Have you ever wondered what changed in ECMAScript 2020? One of the most impactful additions is **globalThis** so what Is globalThis? globalThis is the standardized, universal way to reference the global object in JavaScript, no matter where your code runs. Before ES2020, developers had to rely on different globals depending on the environment: window ➝ Browsers global ➝ Node.js self ➝ Web Workers This meant writing portable JS was harder than it needed to be. Move your code to another environment? Boom 💥 runtime errors ✅ Why globalThis Is Better Introduced in ES2020, globalThis provides one consistent global reference across all JavaScript environments: Browser Node.js Web Workers Any JS runtime This means: No more environment checks No more conditional globals Cleaner, more maintainable, more future-proof code ⚠️ What’s the Impact? Because relying on environment-specific globals: 1- Reduces portability 2- Causes unexpected runtime errors 3- Makes testing and cross-platform development harder Using globalThis eliminates these issues and ensures your code behaves consistently everywhere. If you’re still using window, self, or global, it’s time to future-proof your JavaScript code with globalThis.
Upgrade to globalThis for Portable JavaScript
More Relevant Posts
-
The JavaScript Memory Model — How Variables Actually Live & Die Many JavaScript bugs don’t come from logic errors, but from memory that stays alive longer than expected. To understand why, you need a basic mental model of how JavaScript manages memory. The stack stores execution contexts, function calls, and local variables, and it’s cleared when a function finishes. The heap stores objects, arrays, and functions, and it lives independently of function execution. Data in the heap is only removed when nothing references it. Closures change this behavior. They don’t capture values; they capture references. When an inner function references a variable, that variable is moved to the heap and kept alive even after the outer function finishes. This is why stale closures and memory leaks happen. Garbage collection in JavaScript is based on reachability. Event listeners, timers, async callbacks, and closures often keep references alive longer than intended, causing memory to grow silently while the app still works. The takeaway is simple: JavaScript doesn’t leak memory on its own. We leak memory by holding references longer than necessary. Once you understand this, async bugs and performance issues become much easier to reason about. For example - In this code, when outer() finishes, its stack frame is cleared and message would normally be removed. But since inner() still references message, JavaScript keeps it in the heap. Because the reference exists, garbage collection can’t remove it, so the memory stays alive as long as fn exists.
To view or add a comment, sign in
-
-
Vanilla JavaScript is far from dead. It's thriving, actually. So, what's with all the tweets saying it's a relic of the past? Not. The language has come a long way - and browser APIs have become ridiculously powerful. It's simple: frameworks aren't a replacement for Vanilla JavaScript, they're just a tool to automate certain tasks. Think of it like a chef's kitchen - you can use all sorts of gadgets to make cooking easier, but at the end of the day, you still need to know how to chop an onion. Here's the thing: modern Vanilla JavaScript is incredibly powerful and expressive. It's the foundation of every web application, and every framework compiles down to it. So, understanding Vanilla JavaScript makes you a better developer, regardless of the tools you use - it's like having a superpower. When to use it? Well, for small, focused enhancements to static sites, it's perfect. Same with progressive enhancement of server-rendered HTML. And if performance is critical, or you're working with severely constrained bundle sizes, Vanilla JavaScript is the way to go. But, of course, there are times when frameworks make more sense - like with complex, stateful applications, or large teams that need structure and conventions. And if you're building an application that requires sophisticated routing, code splitting, and performance optimizations, a framework might be the better choice. So, the key is to understand both Vanilla JavaScript and frameworks, and make thoughtful choices about which tool to use when. Don't believe the hype - Vanilla JavaScript is stronger, more capable, and more relevant than ever. Check it out: https://lnkd.in/gPiHFfXB #VanillaJavaScript #JavaScript #WebDevelopment
To view or add a comment, sign in
-
Despite AI and the push for simplification in web development, JavaScript frameworks aren’t quite ready to yield their hold on the frontend. By Loraine Lawson
To view or add a comment, sign in
-
So, JavaScript is kinda like the backbone of modern web development. It's crazy to think about how far it's come since 1995. That's a long time. And now, parsing and interpreting its code is a crucial part of the process. You gotta know how to break it down, right? I mean, take Abstract Syntax Trees (ASTs) for example - they're like a map of the code's structure. And they're used everywhere, from code analysis tools to integrated development environments (IDEs). Libraries like acorn, esprima, and babel-parser make it possible to parse JavaScript code into ASTs, which is pretty cool. It's powerful. But, let's get into the nitty-gritty - when you're parsing JavaScript code, you're essentially interpreting its structure through these ASTs. And that's where things can get interesting. You can use the Babel parser to parse JavaScript code and generate an AST, like this: ```javascript const parser = require("@babel/parser"); const code = `const add = (a, b) => a + b;`; const ast = parser.parse(code); ``` And then, you can traverse and manipulate these ASTs using libraries like rebabel or estraverse. It's like navigating a tree, where each branch represents a different part of the code. It's complex. Now, when it comes to parsing JavaScript, there are some edge cases to consider - like strict mode and prohibited syntax. And, you can use source maps to map transformed code back to the original source, which is super useful. It's a game-changer. Companies like Facebook and Airbnb are already using AST manipulation for code analysis, transpilation, and bundle optimization. And, to optimize parsing performance, it's all about avoiding unnecessary traversals, leveraging caching, and using parallel processing. It's a strategy. So, if you're looking to take your JavaScript skills to the next level, you gotta understand the power of parsing and interpreting its code. It's all about innovation, creativity, and strategy. Check it out: https://lnkd.in/gJm8smSs #JavaScript #WebDevelopment #CodeOptimization
To view or add a comment, sign in
-
🧠 JavaScript – Scope, Hoisting & this Understanding How JavaScript Works Internally To write better JavaScript, it’s not enough to know what to write we must understand how JavaScript executes code behind the scenes. This is where scope, hoisting, and this become important. 🔹 Scope in JavaScript Scope defines where a variable can be accessed. 🌍 Global Scope Variables declared outside functions or blocks. let appName = "MyApp"; function showName() { console.log(appName); } 👉 Accessible everywhere in the program. 🏠 Local (Function) Scope Variables declared inside a function. function greet() { let message = "Hello"; console.log(message); } 👉 Cannot be accessed outside the function. 📦 Block Scope Variables declared using let and const inside {}. if (true) { let count = 5; } 👉 count is not accessible outside the block. 🔹 Hoisting (Important Concept) Hoisting means JavaScript moves declarations to the top before execution. console.log(a); var a = 10; 👉 Output: undefined (The declaration is hoisted, not the value.) let and const with Hoisting console.log(b); let b = 5; 👉 This causes an error. Why? let and const are hoisted But not initialized (Temporal Dead Zone) 🔹 The this Keyword this refers to the object that is currently using the function. In a Regular Function console.log(this); 👉 Refers to the global object (window in browsers). Inside an Object let user = { name: "Alex", greet() { console.log(this.name); } }; 👉 this refers to the user object. Arrow Functions & this let user = { name: "Alex", greet: () => { console.log(this.name); } }; 👉 Arrow functions do not have their own this. 🧠 Simple Way to Remember Scope → where variables live Hoisting → how JS reads code this → who owns the function Understanding these prevents confusing bugs. ✅ Why This Matters Helps write predictable code Avoids scope-related errors Makes frameworks easier to understand Often asked in interviews If you understand this, you’re thinking like a real JavaScript developer. . . #JavaScript #WebDevelopment #ProgrammingBasics #LearningInPublic #FrontendDevelopment #FullStackJourney
To view or add a comment, sign in
-
-
JavaScript Hoisting: The Concept That Separates “I use JS” from “I understand JS” Hoisting is one of those JavaScript behaviors that silently explains why some code works, and why some bugs are so hard to catch. In JavaScript, code runs in two phases: 1️⃣ Compilation (creation) phase 2️⃣ Execution phase During compilation, JavaScript sets up memory for variables and functions. This is where hoisting happens. 🔹 var hoisting Only the declaration is hoisted, not the initialization. ex: console.log(x); // undefined var x = 5; Behind the scenes, JavaScript treats it like: var x; console.log(x); x = 5; No error, but also no value yet. This behavior has caused countless subtle bugs in real-world apps. 🔹 Function declarations Function declarations are fully hoisted, name and body. sayHello(); // works function sayHello() { console.log("Hello"); } This is why function declarations behave differently from function expressions. 🔹 let & const (ES6) They are hoisted, but not initialized. Accessing them before declaration throws a ReferenceError. console.log(y); // ReferenceError let y = 10; This period is known as the Temporal Dead Zone (TDZ), a design choice to make code safer and more predictable. 💡 Why this matters in real projects - Explains unexpected undefined - Helps debug scope-related issues - Shows you understand how JS actually works under the hood 📌 Best practice Don’t rely on hoisting. Write code that’s clear, intentional, and predictable, your future self (and your team) will thank you. #JavaScript #Frontend #WebDevelopment #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
" Everything in JavaScript happens inside an Execution Context". Execution Context in JavaScript which can be assumed as a box or a container in which whole javascript code is executed. During the context runtime, the parser parses the source code and allocates memory for the variables and functions. The source code is generated and gets executed. There are two types of execution contexts: global and function. 1. The global execution context is created when a JavaScript script first starts to run, and it represents the global scope in JavaScript. 2. A function execution context is created whenever a function is called, representing the function's local scope. It is a fundamental concept in Javascript and is really necessary if you want to understand. If you want to go more in depth do check at the following: Namaste JavaScript series on YouTube or namastedev.com by Akshay Saini 🚀 https://lnkd.in/dqxMxFKM
To view or add a comment, sign in
-
How scope works in JavaScript : Save for later Think of scope like rooms in a house. Global scope This is the sitting room. Everyone in the house can enter it. Anything you put here can be used anywhere. If you keep your TV in the sitting room, anyone in the house can watch it. In JavaScript, a variable created outside a function can be used anywhere in the file. Now let’s move inside. Function scope This is a bedroom. Only people inside that room can use what is there. If you keep your phone in your bedroom, people in the sitting room cannot use it. In JavaScript, a variable created inside a function can only be used inside that function. Now let’s talk about blocks. Block scope This is like a cupboard inside a room. If you put something inside a cupboard, only that cupboard can access it. Variables created with let and const inside if statements, loops, or brackets only work inside those brackets. Once you step outside, they disappear. Very important rule: JavaScript always looks for a variable from the closest place first. If it doesn’t find it, it moves outside step by step until it reaches the global scope. Simple way to remember: Global = everyone can see it Function = only inside the function Block = only inside the braces
To view or add a comment, sign in
-
-
Most websites ship far more JavaScript than they need. And it’s slowing everything down. More JS = heavier pages Heavier pages = more energy More energy = more carbon And slower performance for every user. Half the scripts running on a typical site aren’t even used. But they still load, still execute and still burn through speed and sustainability. I break down what’s causing the bloat and how to cut it in today’s article.
To view or add a comment, sign in
-
JavaScript can be pretty confusing. It's pass-by-value, but what does that even mean? So, let's dive in. In a nutshell: everything in JavaScript is passed by value - it's that simple. But, the type of data you're working with changes everything. Primitives, like numbers or strings, are passed by value - no surprises there. Objects, on the other hand, are passed by value too, but the value is a reference to the object, which is where things get tricky. When you pass a primitive, JavaScript makes a copy of the data, and the original and the copy are independent - easy peasy. But with objects, it's like sharing a secret: if you change the object, everyone who has a reference to it sees the change. You can use the spread operator or structuredClone() to create copies of objects, but be careful - objects and arrays can share references, which can lead to some weird behavior. It's like trying to have a conversation in a crowded room: you think you're talking to one person, but really, everyone is listening. So, to write clean code, use immutability - never change the original data, just return a new version. It's like taking a snapshot: you capture the moment, and then you can move on. And, yeah, it's worth repeating: JavaScript is always pass-by-value. Primitives are safe from external changes, but objects and arrays share references, so be careful. Use the spread operator or structuredClone() to create copies, and always, always embrace immutability for predictable code. Check out this article for more info: https://lnkd.in/g-Nj9Rh6 #JavaScript #Immutability #CleanCode #PassByValue #ProgrammingBestPractices
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