DEV Community

Sourav Bandyopadhyay
Sourav Bandyopadhyay

Posted on

1

What is Global variables in javascript?

In JavaScript, a global variable is a variable that is accessible from anywhere in the code, including inside functions and blocks.

Global variables are declared outside of any function or block, usually at the top of a script. Once declared, they can be accessed and modified from any part of the code, which makes them convenient but also potentially risky, as they can be accidentally overwritten or modified by different parts of the code.

Here's an example of how to declare a global variable in JavaScript:

var globalVariable = "I am a global variable";

console.log(globalVariable)

function myFunction() {
  globalVariable = "I am modified";
  console.log(globalVariable);
}

myFunction(); // outputs "I am modified"
console.log(globalVariable); // also outputs "I am modified"

Enter fullscreen mode Exit fullscreen mode

In this example, globalVariable is a global variable that can be accessed and modified from any part of the code.

It's important to be careful when using global variables in JavaScript, as they can make code harder to maintain and test. It's usually better to use local variables when possible, and pass values between functions using parameters and return values.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay