Home > Mobile >  Gain Access To variables defined within functions
Gain Access To variables defined within functions

Time:09-28

Within Js Functions, a variable can be defined but from console that variable doesn't exist is there anyway to access or edit it?

Example:(This code would be in the website)

function whatever () {
var x = 10
}

then in console if you type x it will say 'undefined'

CodePudding user response:

What you're talking about is called scope. From Mozilla's docs:

function exampleFunction() {
    var x = "declared inside function";  // x can only be used in exampleFunction
    console.log("Inside function");
    console.log(x);
}

console.log(x);  // Causes error

However:

var x = "declared outside function";

exampleFunction();

function exampleFunction() {
    console.log("Inside function");
    console.log(x);
    x = "something else";
}

console.log("Outside function");
console.log(x);

In other words, declaring variables outside the function allow access, and you can change them from within.

Alternatively, building on their example, you can use a return value in the function to assign a variable its value.

function exampleFunction() {
    return "Inside function";
}

const x = exampleFunction();
console.log(x);

CodePudding user response:

x is limited to the scope of its function. If you want to reference it outside of the function, you can either declare it outside the function:

var x = 10
function whatever () {
  // ...
}

Or you can make it a global variable by declaring it with the window object:

function whatever () {
    window.x = 10
}

whatever()

console.log(x)

  • Related