What is Global Variable ?
A global variable is a variable that is defined and accessible throughout the entire program or a significant portion of it, rather than being limited to a specific function or block of code. Global variables are declared outside of any function, typically at the top of a program, making them accessible from any part of the code.
Benefits of using Global variable
While the use of global variables is generally discouraged due to potential issues like unintended side effects and decreased code maintainability, there are specific scenarios where global variables can be beneficial:
- Global State Management: Global variables can be useful for managing global state within a program. For example, in some cases, a program might need to maintain a global configuration or settings that should be accessible from various parts of the code.
- Constants: Global variables can be used to define constants that are accessed from multiple functions or modules. This can help centralize the definition of constants, making it easier to update them consistently throughout the code.
- Simplifying Function Signatures: In some cases, using global variables can simplify function signatures by reducing the number of parameters that need to be passed. This can make the code cleaner and more readable, especially in situations where many functions need access to the same data.
It’s important to note that while these benefits exist, caution should be exercised when using global variables to ensure that they are used judiciously and do not compromise the principles of good software design, such as modularity and encapsulation. In many cases, alternative approaches, such as passing parameters or using dependency injection, are preferred to minimize the potential downsides associated with global variables.
How to use it ?
var invitedByValues = [];
$.ajax({
type: 'get',
url: "{{ url('api/v1/j/invitedManagerUserGetting') }}/" + userAuthId + '/' +
organisation_id,
dataType: "json",
async: false,
dataSrc: 'data',
"beforeSend": function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + localStorage.getItem(
'a_u_a_b_t'));
},
success: function(data) {
console.log('success main manager id value a rha hai ki nahi', data);
var projectManagerSelect = $('#project_manager');
// Do not re-declare invitedByValues, use the global one
invitedByValues = [...new Set(data.map(item => item.invited_by))];
console.log('Unique invited_by values:', invitedByValues);
// Now you can use invitedByValues as needed
// For example, log each unique invited_by value
invitedByValues.forEach(invitedBy => {
console.log('Unique invited_by value:', invitedBy);
});
var authEmail = "{{ Auth::user()->email }}";
if (!projectManagerSelect.find('option[value="' + authEmail + '"]').length) {
projectManagerSelect.append('<option value="' + authEmail + '">' + authEmail +
'</option>');
}
}
});