2

I have simple requirement, I need abc available in hello function but getting undefined I know below code giving me undefined and It should give

function hello(){
 console.log("printing abc ",abc);
}

function test(){
 var abc  = "hello";
 hello();
}

but is anything there that I can make abc available in hello function without passing manually, I am doing this for napajs execute function where i have to call nested function and I do not want to pass variable in hierarchy .

Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29
  • You can declare the variable globally like before `hello()` and then you can use this variable in any function or nested function. – Sahid Hossen Aug 31 '18 at 05:56
  • I can't I have to declare in function. – Nishant Dixit Aug 31 '18 at 05:56
  • 1
    Not sure if I get this correctly. Anyhow, I would say that you still need to rely on lexical scoping to reference free variables from within a function. That is, you need some environment; not necessarily the global environment, but _some_ environment nonetheless. – Ilio Catallo Aug 31 '18 at 06:12
  • Javascript gives you an assortment of ways to get `abc` into hello. You can pass it into `hello` with `hello(abc)` and then define `hello` to take a parameter. You can assign it to a variable in a scope shared by both. etc... But if your requirement is to declare it in `test()` and have it just be available in `hello()`…that's not going to happen. You should explain *why* the normal ways of passing data won't work, otherwise ti seems like an [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Mark Aug 31 '18 at 07:32

3 Answers3

2

Here is your answer

function hello(){
    console.log("printing abc", this.abc);
}

function test(){
    this.abc  = "hello";
    hello();
}

test();
Pavan Sikarwar
  • 833
  • 5
  • 14
1

Try using let instead of var. Not sure of the result, but technically let will be block scoped

r0ulito
  • 487
  • 2
  • 13
0
'use strict'

function hello(){

  console.log('---------1-------------')

  console.log("printing abc ",abc);

 }

 function test(){
   console.log('--------------2-----------')

  abc  = "hello";

  hello();

 }

 global.abc ='anjj';

 var a = test();

//please try this way

AKX
  • 152,115
  • 15
  • 115
  • 172
thirtharaj
  • 11
  • 4