1
  • I'm a total beginner in JS. Now trying to handle arrays

  • question: why the code below doesn't work. The aim is to make a function that adding the variable to the arrays but the outcome is still undefined. I hot stucked.

    var b = [];
    var n = 1;
    
    function name() {
      b.push(n);
      console.log(b);
    }
    
    console.log(b);
    
1
  • How are you executing your code? Actually, it's not giving any undefined output Commented Oct 26, 2021 at 7:26

4 Answers 4

3

You need to call the name() function, then your code will work as expected

var b = []; var n = 1;

function name() { b.push(n); console.log(b); };

name();
.as-console-wrapper { max-height: 100% !important; top: 0; }

You could also create an IIFE (Immediately-invoked function expression, like so:

(() => {
  var b = [], n = 1;
  b.push(n);
  console.log(b);;
})()
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

1

In the code you written function name is declared but never used. Try to call the function like this name()

var b = []; var n = 1;
function name() { 
  b.push(n); console.log(b); 
}
name();

chrome developer tools example

Comments

1

There are two ways to do this.

Either make that function IIFE(Immediately Invoked Function Expression) or call that function

IIFEes are generally used for reducing the pollution of global scope.

First way by calling the function explicitly:-

   

var b = [];
var n = 1;

function name() {
  b.push(n);
  console.log(b);
}
name()
console.log(b);

Second way is using IIFE

var b = [];
var n = 1;

(function name() {
  b.push(n);
  console.log(b);
})()
console.log(b);

Comments

0

You should call the function or if you want to execute the function without calling it you should use the IIFE(Immediately Invoked Function Expression) pattern;

var b = [];
var n = 1;

(function name() {
  b.push(n);
  console.log("Inside the function: ",b);
})();

console.log("Outside the function: ",b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.