2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

What is the scope of variables in JavaScript?

What is the scope of variables in javascript?  Also wanted to know where are the variables stored if defined globally?
userimage

In JavaScript, objects and functions are also variables.We have a local and global scopes


Variables declared within a JavaScript function, become LOCAL to the function.They can only be accessed within the function.

function myFunction() {
    var carName = "Volvo";    // code here can use carName
}

A variable declared outside a function, becomes GLOBAL.All scripts and functions on a web page can access it.

var carName = " Volvo";
// code here can use carName
function myFunction() {
    // code here can use carName
}

Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

function myFunction() {
    carName = "Volvo";
    // code here can use carName
}

Local variables are deleted when the function is completed.

Global variables are deleted when you close the page.they are stored in window.

Answer is