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);
4 Answers
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; }
Comments
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();
Comments
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
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);
undefinedoutput