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
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
As you move to the cloud, your network should be efficient, secure, and easy to manage. An enterprise adopting a hybrid or public cloud needs systems and tools that provide: Agility: ability to deliver applications and services faster, even in complex hybrid environments Easier manageability: enable reliable connectivity with complete oversight as the data center network evolves Greater efficiency: eliminate wasted effort while reducing errors and optimize asset utilization Security: imple...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
Transforming cloud-based data into a reportable format can be a very expensive, time-intensive and complex operation. As a SaaS platform with more than 30 million global users, Cornerstone OnDemand’s challenge was to create a scalable solution that would improve the time it took customers to access their user data. Our Real-Time Data Warehouse (RTDW) process vastly reduced data time-to-availability from 24 hours to just 10 minutes. In his session at 21st Cloud Expo, Mark Goldin, Chief Technolo...
The next XaaS is CICDaaS. Why? Because CICD saves developers a huge amount of time. CD is an especially great option for projects that require multiple and frequent contributions to be integrated. But… securing CICD best practices is an emerging, essential, yet little understood practice for DevOps teams and their Cloud Service Providers. The only way to get CICD to work in a highly secure environment takes collaboration, patience and persistence. Building CICD in the cloud requires rigorous ar...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
When it comes to cloud computing, the ability to turn massive amounts of compute cores on and off on demand sounds attractive to IT staff, who need to manage peaks and valleys in user activity. With cloud bursting, the majority of the data can stay on premises while tapping into compute from public cloud providers, reducing risk and minimizing need to move large files. In his session at 18th Cloud Expo, Scott Jeschonek, Director of Product Management at Avere Systems, discussed the IT and busine...
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
Is advanced scheduling in Kubernetes achievable? Yes, however, how do you properly accommodate every real-life scenario that a Kubernetes user might encounter? How do you leverage advanced scheduling techniques to shape and describe each scenario in easy-to-use rules and configurations? In his session at @DevOpsSummit at 21st Cloud Expo, Oleg Chunikhin, CTO at Kublr, will answer these questions and demonstrate techniques for implementing advanced scheduling. For example, using spot instances ...
First generation hyperconverged solutions have taken the data center by storm, rapidly proliferating in pockets everywhere to provide further consolidation of floor space and workloads. These first generation solutions are not without challenges, however. In his session at 21st Cloud Expo, Wes Talbert, a Principal Architect and results-driven enterprise sales leader at NetApp, will discuss how the HCI solution of tomorrow will integrate with the public cloud to deliver a quality hybrid cloud e...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
Companies are harnessing data in ways we once associated with science fiction. Analysts have access to a plethora of visualization and reporting tools, but considering the vast amount of data businesses collect and limitations of CPUs, end users are forced to design their structures and systems with limitations. Until now. As the cloud toolkit to analyze data has evolved, GPUs have stepped in to massively parallel SQL, visualization and machine learning.
DevOps is under attack because developers don’t want to mess with infrastructure. They will happily own their code into production, but want to use platforms instead of raw automation. That’s changing the landscape that we understand as DevOps with both architecture concepts (CloudNative) and process redefinition (SRE). Rob Hirschfeld’s recent work in Kubernetes operations has led to the conclusion that containers and related platforms have changed the way we should be thinking about DevOps and...