skip to Main Content

I’m reading a line on NodeJS and insert it into an array however i need to export it to JavaScript file in order to use it there. however I’m having difficulty since the array arrives but outside the function it’s empty. so I’m wondering if anyone is able to fix this issue or help another way to send this array from NodeJS to JavaScript.

const test = [];
export function message(n){
      
      for (var i = 0; i< n.length; i++){
            test[i] = n[0];
      }   
      //works
      console.log(test[0]);
      
}
//outside of function 
//doesn't work
console.log(test[0]);

I was hoping to access the array outside the function and be able to utilized all it’s features.

2

Answers


  1. You are exporting a function that you have defined so you would need to import that function into another file and invoke it.

    It’s not clear exactly what your use case is but imagine you are just experimenting with export/import so here is a really basic example of how to export/import a function along the lines of your use case:

    message.js

    export function message(n){
        const test = []
        for (let i = 0; i< n.length; i++){
            test[i] = n[i];
        }
        return test;
    }
    

    This will take an interable and return the new array test.

    app.js

    import {message} from "./message.js";
    const arr = message('Batman');
    console.log(arr); 
    // [ 'B', 'a', 't', 'm', 'a', 'n' ]
    
    
    Login or Signup to reply.
  2. The console.log outside of the message function is being executed before your external invocation of the message function.

    const test = []; // 1. test declaration
    
    export function message(n){ // 2. function declaration
          
          for (var i = 0; i< n.length; i++){
                test[i] = n[0];
          }   
          //works
          console.log(test[0]);
          
    }
    //outside of function 
    // works... but returns undefined because
    // test is an empty array at this point
    console.log(test[0]); // 3. calling console.log (undefined)
    

    However, I think you’re already doing what you want to do, just not quite. You can create a log function in the same scope as the message function, then invoke it from within message. E.g.,

    const test = []; // 1. test declaration
    
    function logTest() { // 2. logTest declaration
        console.log(`test[0]: ${test[0]}`);
    }
    
    export function message(n) { // 3. message declaration
        for (var i = 0; i < n.length; i++) {
          test[i] = n[0];
        }
        // works
        logTest();
    }
    
    // outside of function
    // works... but returns undefined because test is an empty array
    logTest();
    

    This way 👆🏻, you can access test from within the same scope as message.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search