Home > front end >  Javascript - arrays
Javascript - arrays

Time:10-27

  • 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);
    

CodePudding user response:

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; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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();
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

chrome developer tools example

CodePudding user response:

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);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Second way is using IIFE

var b = [];
var n = 1;

(function name() {
  b.push(n);
  console.log(b);
})()
console.log(b);
<iframe name="sif5" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif6" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related