<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Greg Murray</title>
    <description>The latest articles on DEV Community by Greg Murray (@ggmurr24).</description>
    <link>https://dev.to/ggmurr24</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2395144%2Fe1e529a7-d7a1-4d72-8f2d-21cb36ba32aa.png</url>
      <title>DEV Community: Greg Murray</title>
      <link>https://dev.to/ggmurr24</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ggmurr24"/>
    <language>en</language>
    <item>
      <title>Managing Imports in Python: Prevent Breaking Your Program</title>
      <dc:creator>Greg Murray</dc:creator>
      <pubDate>Fri, 03 Jan 2025 13:44:41 +0000</pubDate>
      <link>https://dev.to/ggmurr24/managing-imports-in-python-prevent-breaking-your-program-18mb</link>
      <guid>https://dev.to/ggmurr24/managing-imports-in-python-prevent-breaking-your-program-18mb</guid>
      <description>&lt;p&gt;Imports are essential in Python. They allow the use of modules and libraries to extend functionality, and they simplify your code. But improper management of imports can lead to program failures or unexpected behavior in your program.   &lt;/p&gt;

&lt;p&gt;This post gives a general overview and covers some strategies to manage imports and avoid common issues.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Python Imports&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In Python, &lt;code&gt;import&lt;/code&gt;brings external code into your program often making your job easier or extending functionality. You can import entire modules or specific functions and classes.&lt;/p&gt;

&lt;p&gt;To import an entire module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import math
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To import specific functions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from math import sqrt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On top of this you can use aliases for modules:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import numpy as np
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Understanding how and when to use these options can improve readability and minimize namespace clutter.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Only What You Need&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;Importing an entire module can bring in unnecessary functions, so import only the specific parts that you need.  This reduces memory usage and makes your code easier to maintain.&lt;/p&gt;

&lt;p&gt;For example, rather than importing &lt;code&gt;*&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from math import sqrt, pi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Circular Imports&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Circular imports occur when two modules try to import each other. This leads to an infinite loop that prevents your program from running.  For example, module A imports module B, and vice versa.&lt;/p&gt;

&lt;p&gt;If you find you’ve created a circular import, try reorganizing your code. Move code shared in functionality to a new module that both modules can import. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Error Handling and Imports&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;You may run into a situation where a module may not be available or there are compatibility issues. You can use try-except to handle potential issues. Here you can ensure that your program doesn’t crash. You may need this if a dependency is not installed in your environment or optional features can be degraded if dependency is unavailable. &lt;/p&gt;

&lt;p&gt;You can provide an alternative if a module is missing. Basic syntax for this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    import module
except ImportError:
    print("some message")
#Code to execute if module unavailable

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Naming Conflicts&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Naming conflicts happen when your file name is the same as a built-in Python module. For example, if you name your file math.py, Python will try to import your file instead of the built-in math module which causes errors.&lt;/p&gt;

&lt;p&gt;Avoid this by not naming your files after standard libraries and choosing unique names for your modules. If it does come up, try renaming your scripts.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Virtual Environments&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A benefit of virtual environments is that they allow you to keep the libraries and packages your project needs isolated so that they won’t conflict with other projects. It also ensures that you have the right versions of libraries installed for your project which can prevent issues down the road. &lt;/p&gt;

&lt;p&gt;To quickly create a virtual environment, you can do so with &lt;code&gt;pipenv&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;First:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install pipenv
#install pipenv if not yet installed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pipenv install
#install required dependencies and create virtual environment
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or, if you just want to create the environment:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pipenv --python &amp;lt;version&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, to activate the environment run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pipenv shell
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Conclusion&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Managing imports in Python is crucial for keeping your projects organized, efficient, and bug-free. Only importing what you need, avoiding circular imports, handling errors gracefully, and following best practices ensures your code runs smoothly. Keep these tips in mind and your Python projects will be solid. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Further Reading&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://medium.com/@officialyrohanrokade/mastering-python-imports-and-module-management-a-deep-dive-into-import-keywords-folder-d92aa1daaaf5" rel="noopener noreferrer"&gt;https://medium.com/@officialyrohanrokade/mastering-python-imports-and-module-management-a-deep-dive-into-import-keywords-folder-d92aa1daaaf5&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://peps.python.org/pep-0008/#imports" rel="noopener noreferrer"&gt;https://peps.python.org/pep-0008/#imports&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://realpython.com/python-import/" rel="noopener noreferrer"&gt;https://realpython.com/python-import/&lt;/a&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
    </item>
    <item>
      <title>5 Common Refactors in Python for Beginners</title>
      <dc:creator>Greg Murray</dc:creator>
      <pubDate>Sun, 15 Dec 2024 13:02:50 +0000</pubDate>
      <link>https://dev.to/ggmurr24/5-common-refactors-in-python-for-beginners-4ol3</link>
      <guid>https://dev.to/ggmurr24/5-common-refactors-in-python-for-beginners-4ol3</guid>
      <description>&lt;p&gt;Refactoring helps make your code cleaner and more efficient. Here are five common refactors for beginners in Python.&lt;/p&gt;

&lt;p&gt;I. Simplifying Boolean Expressions&lt;/p&gt;

&lt;p&gt;A common pattern is using an if-else block just to return True or False. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if condition:
    return True
else:
    return False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Refactor it to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return condition

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The condition itself is already a Boolean expression, so the if-else block is unnecessary. By directly returning the condition, the code becomes shorter and more readable. This is a simple but effective way to improve clarity without changing the functionality.&lt;/p&gt;

&lt;p&gt;II. List Comprehensions Instead of for / if&lt;/p&gt;

&lt;p&gt;Beginners often use for loops with if statements to build lists. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = []
for item in items:
    if condition(item):
        result.append(item)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Refactor it to a list comprehension:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = [item for item in items if condition(item)]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;List comprehensions provide a more concise way to construct lists. They are also typically faster than equivalent for loops because they are optimized internally by Python. This approach is easier to read as well, especially for simple list creation tasks.&lt;/p&gt;

&lt;p&gt;III. Avoid Repeating Calculations&lt;/p&gt;

&lt;p&gt;If you call the same function multiple times in a loop, store the result in a variable. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for item in items:
    if len(item) &amp;gt; 5:
        result.append(item)
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Refactor it to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for item in items:
    len = len(item)
    if len &amp;gt; 5:
        result.append(item)
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Imagine if this condition held in multiple elif or nested if statements. Here, the len(item) is called twice for each iteration, which can be inefficient, especially for large lists. Storing the result of len(item) in a variable (len) eliminates the repeated calculation, improving performance and making the code cleaner. This is a basic example.&lt;/p&gt;

&lt;p&gt;IV. Lambda and Built-in Methods&lt;/p&gt;

&lt;p&gt;Instead of writing explicit loops, use Python’s built-in functions like map() and filter(), which can be more efficient and concise. For example, to double each item in a list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = []
for item in items:
    result.append(item * 2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Refactor it to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = list(map(lambda x: x * 2, items))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or to filter items greater than 5:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = []
for item in items:
    if item &amp;gt; 5:
        result.append(item)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Refactor it to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = list(filter(lambda x: x &amp;gt; 5, items))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both map() and filter() take functions as arguments, so we can use lambda to define small anonymous functions. The lambda function is a concise way to define simple operations. For example, lambda x: x * 2 creates a function that multiplies x by 2. The benefit of map() and filter() is that they are often more efficient than using a for loop and are typically more readable. One could also use list comprehensions (see above).&lt;/p&gt;

&lt;p&gt;V. Combine Multiple if Statements&lt;/p&gt;

&lt;p&gt;When checking multiple conditions, combining them with logical operators (and, or) can simplify your code. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if a &amp;gt; 0:
    if b &amp;gt; 0:
        result = a + b
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Refactor it to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if a &amp;gt; 0 and b &amp;gt; 0:
    result = a + b
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This reduces unnecessary nesting and makes the code easier to read and maintain. Combining conditions into one if statement makes the flow of logic clearer and eliminates redundancy.&lt;/p&gt;

&lt;p&gt;Give It a Shot&lt;/p&gt;

&lt;p&gt;How do you feel about refactoring control flow and utilizing built in methods? Take the following code and see if you can refactor:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;count = {}
sum = {}
    for team, items in dict().items():
        for player in items["players"]:
            brand = player["shoe_brand"]

            if brand not in count.keys():
                count[brand] = 1
            else:
                count[brand] += 1

            if brand not in sum.keys():
                sum[brand] = player["rebounds_per_game"]
            else:
                sum[brand] += player["rebounds_per_game"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we have two dictionaries where we need to set the initial values. Using the tactics in the article, you should see that both if statements can be combined using a logical operator. Go a step further and it might stand out that when one dictionary lacks an initial property, so does the other and neither is incremented (/aggregated) before the other is initialized. So we may refactor this code as follows since it would seem one condition is both sufficient and necessary for the other to obtain before any incrementing takes place, avoiding an error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        if brand not in count:
            count[brand] = 1
            sum[brand] = player["rebounds_per_game"]
        else:
            count[brand] += 1
            sum[brand] += player["rebounds_per_game"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Can we refactor further? Think about using a built-in method...&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        count[brand] = count.get(brand, 0) + 1
        sum[brand] = sum.get(brand, 0) + player["rebounds_per_game"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Conclusion&lt;/p&gt;

&lt;p&gt;Refactoring is about making your code shorter, clearer, and more efficient without changing what it does. By simplifying Boolean expressions, using list comprehensions, avoiding repeated calculations, leveraging built-in functions like map() and filter(), and merging conditions, you can make your code DRY. Using lambda allows you to define small functions in a single line, keeping the code neat and fast. These practices not only improve performance but also enhance readability, which is crucial for maintaining code in the long run.&lt;/p&gt;

&lt;p&gt;Further reading:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.w3schools.com/python/python_lambda.asp" rel="noopener noreferrer"&gt;https://www.w3schools.com/python/python_lambda.asp&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.w3schools.com/python/ref_func_filter.asp" rel="noopener noreferrer"&gt;https://www.w3schools.com/python/ref_func_filter.asp&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.w3schools.com/python/ref_func_map.asp" rel="noopener noreferrer"&gt;https://www.w3schools.com/python/ref_func_map.asp&lt;/a&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Mental Health for Devs</title>
      <dc:creator>Greg Murray</dc:creator>
      <pubDate>Mon, 25 Nov 2024 17:12:13 +0000</pubDate>
      <link>https://dev.to/ggmurr24/mental-health-for-devs-4715</link>
      <guid>https://dev.to/ggmurr24/mental-health-for-devs-4715</guid>
      <description>&lt;p&gt;Overview&lt;/p&gt;

&lt;p&gt;Mental health challenges are common in the programming field. Long hours, social isolation, sedentary lifestyles, and perfectionist tendencies can all contribute to increased stress and often burnout. Depression, anxiety, and burnout are particularly prevalent while other conditions such as Bipolar Disorder do affect the population. &lt;/p&gt;

&lt;p&gt;Programmers can often face unrealistic expectations, code crunches, pressure in staying up to date with technologies, and the stress of tight deadlines. Remote work or isolation in-office can harm an individual's sense of social belonging which is often a trigger for mental health issues. &lt;/p&gt;

&lt;p&gt;What else contributes to the mental health puzzle?&lt;/p&gt;

&lt;p&gt;Diet plays a crucial role in managing mental health in general, doubly so with high stress jobs like in programming. A balanced diet rich in healthy fats from sources like fish and nuts, complex carbohydrates, proteins, and micronutrients can improve both cognitive function and mood stability which is pivotal in managing the symptoms of conditions like depression and bipolar. Stay away from excess caffeine consumption to protect sleep habits and avoid pouring gasoline on the fire of anxiety.&lt;/p&gt;

&lt;p&gt;Exercise has been shown to improve symptoms of various mental health conditions, especially depression and anxiety. It helps boost endorphin levels and regulates mood. Even 20 minutes of low intensity exercise can have a measured effect on these. It should be incorporated in one's pursuit of more balanced mental health whether it be for a burnt out Dev or for more serious cases. The threshold to start an exercise routine may seem daunting when in the grips of mental health issues but it is well worth the reward.&lt;/p&gt;

&lt;p&gt;Alcohol is another negative mental health catalyst. Though it is tempting to use alcohol to soothe oneself from the stress of programming professions, the withdrawals, potential for alcoholism, and disruption of sleep all can be detrimental to the mind of the programmer. To maintain oneself in the cognitive demands of the job and promote a degree of personal happiness, limit alcohol intake. &lt;/p&gt;

&lt;p&gt;It is also of great importance that one adheres to the medication management of one's mental health provider if applicable. More serious mental health conditions are not often talked about in the community, but for those affected by conditions such as those on the schizophrenia spectrum or by bipolar disorder, it is crucial to take medications as prescribed and to maintain treatment as these disorders can cause episodes that can have a significant impact on employment.&lt;/p&gt;

&lt;p&gt;So when do you get help?&lt;/p&gt;

&lt;p&gt;Recognizing when mental health issues require professional intervention is essential in maintaining your career as a Dev. Signs that it may be time to seek help include persistent sadness or hopelessness, difficulty concentrating, extreme fatigue, feelings of worthlessness, and social withdrawal. Other symptoms may be recognizable to those around you such as symptoms of mania, delusions, or abuse of substances that affects interpersonal relationships. &lt;/p&gt;

&lt;p&gt;If work-related stress or symptoms of anxiety or depression are affecting your ability to perform daily tasks, it’s important to reach out to a mental health professional. Your insurance company can often provide resources under their blanket of coverage that are in your area. Aside from medication, there is also therapy and support groups that can provide relief and practical coping strategies. Check your area and online for these resources.&lt;/p&gt;

&lt;p&gt;Dealing with your employer in a mental health crisis&lt;/p&gt;

&lt;p&gt;When discussing mental health with an employer, it's important to know your rights and approach the conversation thoughtfully. Many companies have policies that protect workers from discrimination due to mental health conditions. Be honest but concise about your needs, whether that’s flexible work hours, a quieter work environment, or reduced workload. Framing the conversation in terms of how accommodations will help you perform better at work can make it easier for employers to understand. If you're uncomfortable talking directly with your manager, consider discussing the issue with HR or a mental health professional to get advice on how to approach the situation. Discrimination on the basis of mental health is against the law. &lt;/p&gt;

&lt;p&gt;Conclusion&lt;/p&gt;

&lt;p&gt;Mental health issues are more common than not in the field. Manage your mental health with proper diet, limit alcohol, and adhere to medication management if you are receiving psychiatric services. Get help when symptoms start impacting your quality of life or interfere with your professional performance. Reasonable accommodation can be provided by your employer if you so choose to disclose and discuss your condition with them. &lt;/p&gt;

</description>
      <category>mentalhealth</category>
    </item>
    <item>
      <title>The Global Object in JavaScript</title>
      <dc:creator>Greg Murray</dc:creator>
      <pubDate>Tue, 12 Nov 2024 21:59:17 +0000</pubDate>
      <link>https://dev.to/ggmurr24/the-global-object-in-javascript-5bhi</link>
      <guid>https://dev.to/ggmurr24/the-global-object-in-javascript-5bhi</guid>
      <description>&lt;p&gt;In JavaScript, the global object is a key concept for all developers. It contains all globally accessible variables, functions, and objects in your program. This post seeks to explain what exactly the global object is, how it behaves in different environments, and why managing it correctly is crucial for effective, clean, and maintainable code.&lt;/p&gt;

&lt;p&gt;What Is the Global Object?&lt;/p&gt;

&lt;p&gt;The global object can be understood as the environment where JavaScript runs. It is the container for all global variables and functions. In the browser, the global object is &lt;em&gt;window _while in Node.js it is _global&lt;/em&gt;. Any global variable or function declared outside of functions is accessible through the global object.&lt;/p&gt;

&lt;p&gt;Browser&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var a = 1;
console.log(window.a); // 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Node.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var a = 1;
console.log(global.a); // 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Global Scope and Variables&lt;/p&gt;

&lt;p&gt;Variables declared globally are attached to the global object. Conflicts can arise here if multiple scripts share the same global space. Declaring with &lt;em&gt;var&lt;/em&gt; globally it is accessible across different scripts on the same page. &lt;/p&gt;

&lt;p&gt;Imagine you have two different scripts that both declare a variable with the same name in the global scope using &lt;em&gt;var&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Script 1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var message = "Hello!";
console.log(message) // Hello!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Script 2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var message = "Goodbye!";
console.log(message); // Goodbye!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When both scripts run, they both declare a message variable in the global scope using &lt;em&gt;var&lt;/em&gt;. The second script overwrites the value of message that was set by script 1 because both variables are stored in the same global space(&lt;em&gt;window&lt;/em&gt; in browsers).  This results in the difference in output. &lt;/p&gt;

&lt;p&gt;It’s best to avoid this by limiting the use of global variables. Keep the scope as local as possible. Keep in mind that &lt;em&gt;let&lt;/em&gt; and &lt;em&gt;const&lt;/em&gt; declared in the global scope are not added to the global object.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;globalThis&lt;/em&gt; and &lt;em&gt;window&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Until recently, developers had to use window in the browser and global in Node.js to access the global object. However, ES2020 introduced &lt;em&gt;globalThis&lt;/em&gt;, a unified way to access the global object across environments. &lt;em&gt;globalThis&lt;/em&gt; standardizes access to the global object.&lt;/p&gt;

&lt;p&gt;Global Functions and Objects&lt;/p&gt;

&lt;p&gt;The global object also holds built-in objects and functions, such as: &lt;em&gt;console&lt;/em&gt;, &lt;em&gt;setTimeout _and _setInterval&lt;/em&gt;, &lt;em&gt;JSON&lt;/em&gt;, and &lt;em&gt;Math&lt;/em&gt;. You can access these globally without needing to reference the global object directly.&lt;/p&gt;

&lt;p&gt;So how do we maintain best practices while maintaining clean, effective code? The global object is useful but relying on it too much can lead to issues. Here is some advice: avoid using global variables (var) to reduce the risk of name conflicts and unintended side effects and instead use local variables within functions. Use let and const.&lt;/p&gt;

&lt;p&gt;Global Object in the Browser&lt;/p&gt;

&lt;p&gt;In the browser, the window object is more than just a global container. It also holds the DOM (&lt;em&gt;document&lt;/em&gt;), browser APIs (&lt;em&gt;fetch&lt;/em&gt;), and other web-specific objects. This makes window central to any browser-based JavaScript execution.&lt;/p&gt;

&lt;p&gt;Global Object in Node.js&lt;/p&gt;

&lt;p&gt;In Node.js, the global object is &lt;em&gt;global&lt;/em&gt;, but it doesn’t automatically add variables to it the way window does in the browser. Node.js encourages the use of modules to keep the global namespace clean and structured.&lt;/p&gt;

&lt;p&gt;Conclusion&lt;/p&gt;

&lt;p&gt;The global object is central to how JavaScript handles global variables, functions, and objects. Understanding how it works in different environments, using it sparingly, and following best practices will help you write clean, maintainable code. By minimizing global variables, using &lt;em&gt;let&lt;/em&gt; or &lt;em&gt;const&lt;/em&gt;, you can avoid problems and improve your JavaScript skills. &lt;/p&gt;

&lt;p&gt;Sources:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects" rel="noopener noreferrer"&gt;Global_Objects&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://javascript.info/global-object" rel="noopener noreferrer"&gt;global-object&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
