DEV Community

Davis O Matengo
Davis O Matengo

Posted on

Global variable Vs Local Variable

A global variable is declared outside a function while a local variable is declared inside a function. The scope of that given variable 'local variable' will remain inside that function and it can not be used outside of that function.

N/B To be updated with more content

Top comments (2)

Collapse
 
cmuralisree profile image
Chittoji Murali Sree Krishna • Edited

Hmm, explanation is okay, but try giving some more info, like:

const brand_name = "mercedes"; 
// Global variable

function suv(){
const suv_name = "g-wagen";
// Local variables
document.querySelector("h1").innerHTML = 
    "vehicle :" + suv_name + brand_name;
}
function sedan(){
document.querySelector("h2").innerHTML = 
     "vehicle :" + suv_name + brand_name;
// Here it gives an error bcz suv_names 
// is not defined in this function or or 
// globally, but it's defined in another function,
// so it will be private for this function
}
Enter fullscreen mode Exit fullscreen mode

Hence Global variables can be used any where in the code, but local variables can be accessed only in that particular function,

if you explain like this with more info, people can understand

I typed it in mobile, so if you find any typos, please ignore.

Collapse
 
bethropolis profile image
Bethuel

Can't wait for updates