Welcome!

Blog Feed Post

Node.js ABC’s - G is for Globals

variableGlobalA variable is a storage location paired with an associated name, which contains the information known as a value.  Nearly every programming language under the sun supports variables in some form or another.

Within the context of a single piece of code, the use of variables are straight forward: Store a value, retrieve a value, use the value.

var sum = 1 + 2;
console.log("The sum is " + sum);

The concept is nice and tidy within the context of a single code segment.  But not many software programs are a limited to a single instance.  With object oriented and modular programming where code logic is broken into smaller segments to enable code reuse and inheritance, sharing variables can be cumbersome.

Variable Scope

The concept of where variables are available and accessible is referred to as the variables context, or scope.  When you declare a variable, the section of code it is included in is referred to as local scope.  If you want to share a variable with different contexts (local scopes), you will need to use a global variable that lives within global scope.  Different languages use different constructs to get at global variables. 

Javascript will first look for a local scoped variable and if not found look for a global scoped one and use that.  The following example shows a global "sum" with various functions taking in as parameters,

var sum = 3;
console.log("SUM 1: " + sum);
function printSum2() {
  var sum = 5;
  console.log("SUM 2: " + sum);
}
printSum2();
console.log("SUM 2.5: " + sum);
function printSum3(sum) {
  sum = 6;
  console.log("SUM 3: " + sum);
}
printSum3(sum);
console.log("SUM 3.5: " + sum);
function printSum4(sum) {
  var sum = 7;
  console.log("SUM 4: " + sum);
}
printSum4(sum);
console.log("SUM 4.5: " + sum);

function printSum5() {
  sum = 9;
  console.log("SUM 5: " + sum);
}
printSum5();
console.log("SUM 5.5: " + sum);

Will result in the following output:

SUM 1  : 3
SUM 2  : 5
SUM 2.5: 3
SUM 3  : 6
SUM 3.5: 3
SUM 4  : 7
SUM 4.5: 3
SUM 5  : 9
SUM 5.5: 9

A problem arises when you have a local variable and a global variable with the same name and you wish to control which variable you are accessing.  Node.js has a solution for this with the "global" object.

The Global Object

Just as JavaScript in web browsers has the "window" object that is accessible to all code contexts as a global object, Node has a similar global-level object but is aptly named "global". 

global.sum = 3;
function printSum() {
  var sum = 5;
  console.log("Local Sum: " + sum);
  console.log("Global Sum: " + global.sum);
}

 

Local Sum: 5
Global Sum: 3

With the global object, you can initialize the variable in one context (function) and access it in another like the following:

function printSum() {
  global.sum = 3;
  console.log("Global Sum 1: " + global.sum);
}
function printSum2() {
  console.log("Global Sum 2: " + global.sum);
}
printSum();
printSum2();

 

Global Sum 1: 3
Global Sum 2: 3

There are semi-religious wars going on as to whether the global variables should never be used or are a necessary evil.  I fall in the later camp but do make sure you use them wisely and understand the context from which your variables are run to avoid debugging headaches later down the road.

Read the original blog entry...

More Stories By Joe Pruitt

Joe Pruitt is a Principal Strategic Architect at F5 Networks working with Network and Software Architects to allow them to build network intelligence into their applications.

Latest Stories
Interested in leveling up on your Cloud Foundry skills? Join IBM for Cloud Foundry Days on June 7 at Cloud Expo New York at the Javits Center in New York City. Cloud Foundry Days is a free half day educational conference and networking event. Come find out why Cloud Foundry is the industry's fastest-growing and most adopted cloud application platform.
For financial firms, the cloud is going to increasingly become a crucial part of dealing with customers over the next five years and beyond, particularly with the growing use and acceptance of virtual currencies. There are new data storage paradigms on the horizon that will deliver secure solutions for storing and moving sensitive financial data around the world without touching terrestrial networks. In his session at 20th Cloud Expo, Cliff Beek, President of Cloud Constellation Corporation, w...
As enterprise cloud becomes the norm, businesses and government programs must address compounded regulatory compliance related to data privacy and information protection. The most recent, Controlled Unclassified Information and the EU’s GDPR have board level implications and companies still struggle with demonstrating due diligence. Developers and DevOps leaders, as part of the pre-planning process and the associated supply chain, could benefit from updating their code libraries and design by in...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm. In his Day 3 Keynote at 20th Cloud Expo, Chris Brown, a Solutions Marketing Manager at Nutanix, will explore t...
Regardless of what business you’re in, it’s increasingly a software-driven business. Consumers’ rising expectations for connected digital and physical experiences are driving what some are calling the "Customer Experience Challenge.” In his session at @DevOpsSummit at 20th Cloud Expo, Marco Morales, Director of Global Solutions at CollabNet, will discuss how organizations are increasingly adopting a discipline of Value Stream Mapping to ensure that the software they are producing is poised to o...
You know you need the cloud, but you’re hesitant to simply dump everything at Amazon since you know that not all workloads are suitable for cloud. You know that you want the kind of ease of use and scalability that you get with public cloud, but your applications are architected in a way that makes the public cloud a non-starter. You’re looking at private cloud solutions based on hyperconverged infrastructure, but you’re concerned with the limits inherent in those technologies.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
In order to meet the rapidly changing demands of today’s customers, companies are continually forced to redefine their business strategies in order to meet these needs, stay relevant and continue to see profitable growth. IoT deployment and development is integral in this transformation, and today businesses are increasingly seeing the value of investing their resources into IoT deployments. These technologies are able increase ROI through projects such as connecting supply chains or enabling sm...
Cloud applications are seeing a deluge of requests to support the exploding advanced analytics market. “Open analytics” is the emerging strategy to deliver that data through an open data access layer, in the cloud, to be directly consumed by external analytics tools and popular programming languages. An increasing number of data engineers and data scientists use a variety of platforms and advanced analytics languages such as SAS, R, Python and Java, as well as frameworks such as Hadoop and Spark...
IBM helps FinTechs and financial services companies build and monetize cognitive-enabled financial services apps quickly and at scale. Hosted on IBM Bluemix, IBM’s platform builds in customer insights, regulatory compliance analytics and security to help reduce development time and testing. In his session at 20th Cloud Expo, Tom Eck, Industry Platforms CTO at IBM Cloud, will discuss how these tools simplify the time-consuming tasks of selection, mapping and data integration, allowing developers ...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
SYS-CON Events announced today that Outscale, a global pure play Infrastructure as a Service provider and strategic partner of Dassault Systèmes, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Founded in 2010, Outscale simplifies infrastructure complexities and boosts the business agility of its customers. Outscale delivers a secure, reliable and industrial strength solution for its customers, which in...
SYS-CON Events announced today that Progress, a global leader in application development, has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Enterprises today are rapidly adopting the cloud, while continuing to retain business-critical/sensitive data inside the firewall. This is creating two separate data silos – one inside the firewall and the other outside the firewall. Cloud ISVs ofte...
In his session at 20th Cloud Expo, Brad Winett, Senior Technologist for DDN Storage, will present several current, end-user environments that are using object storage at scale for cloud deployments including private cloud and cloud providers. Details on the top considerations of features and functions for selecting object storage will be included. Brad will also touch on recent developments in tiering technologies that deliver single solution and an end-user view of data across files and objects...
SYS-CON Events announced today that Tintri, Inc, a leading provider of enterprise cloud infrastructure, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Tintri offers an enterprise cloud platform built with public cloud-like web services and RESTful APIs. Organizations use Tintri all-flash storage with scale-out and automation as a foundation for their own clouds – to build agile development environments...