Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Gain Access To variables defined within functions

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'

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!