Jedd Soh
Jedd Soh

Reputation: 11

How does a function work inside the push method?

I have 2 questions.

  1. Regarding var Webflow = Webflow || [];, what is the purpose of setting the variable to have the OR operator with a blank array?

  2. Regarding the push method that follows ( Webflow.push(function() {...), how/why is there a function created inside the push method. I understand the push method is used to add items to an array, but I can't find much info online about how it works when you put create a function inside the push method. Does it ultimately make the original variable "Webflow = Webflow OR [result of the final function]?

I hope my questions are clear enough. Any insight or clarity, even if it doesn't directly answer my questions would be helpful. My goal is to fully understand every line of this code. Thank you! 🙏

<script>
var Webflow = Webflow || [];
Webflow.push(function () {
  var l = $("#flowbaseSlider1 .w-slider-arrow-left");
  var r = $("#flowbaseSlider1 .w-slider-arrow-right");
  $("#flowbaseSlider1")
    .on("click", ".back-button", function () {
      l.trigger("tap");
    })
    .on("click", ".next-button", function () {
      r.trigger("tap");
    });
});
</script>

I've been Googling each aspect of the code to fully understand it.

Upvotes: 0

Views: 871

Answers (2)

Badacadabra
Badacadabra

Reputation: 8497

Here are some more elements to fully understand the code in your question...

var Webflow = Webflow || []

This is basically a variable declaration with a short-circuit evaluation. In this case, we have a logical OR expression (Webflow || []) thanks to the use of the || operator (see Logical OR (||) - JavaScript | MDN). This is where the magic of boolean operations comes into play... What does that mean? If Webflow is a truthy value, then var Webflow = Webflow. Otherwise, var Webflow = [].

For the record, this syntax was often used in ES5 projects to get default parameters within functions because it is quite handy:

function somebody(username) {
  username = username || 'Badacadabra';
  console.log(username);
}

somebody();

We could also write something like this...

function somebody(username) {
  if (!username) {
    username = 'Badacadabra';
  }

  console.log(username);
}

somebody();

... or like that (which is cumbersome):

function somebody(username) {
  username = username ? username : 'Badacadabra';
  console.log(username);
}

somebody();

In the above code, since I do not pass any argument when I call my somebody() function, username is, at first, undefined. But undefined is a falsy value, so in the boolean context where the || operator is used, username becomes 'Badacadabra'. I would get the same result calling my function like so:

somebody(false); // Badacadabra
somebody(''); // Badacadabra
somebody(null); // Badacadabra
somebody(0); // Badacadabra
// ...

However, if I put a truthy value in there, it will be kept:

somebody('Jedd Soh'); // Jedd Soh

ES6 introduced default parameters that you can use more easily now:

function somebody(username = 'Badacadabra') {
  console.log(username);
}

Webflow.push(function() {})

JavaScript is a very flexible language where you can find functions in many different situations: functions which call themselves, functions associated with keys in object literals, functions inside other functions, and of course, functions in arrays...

So, in JavaScript, you have several options when you want to create a new function. But I think we can say that there are two main concepts (because defining a function through the Function constructor explicitly is not recommended):

  1. Function declaration
  2. Function expression

On the one hand, function somebody() {} is a function declaration (or statement). On the other hand, var somebody = function() {}; is a function expression with somebody as the variable name and an anonymous function assigned. A function expression could be named too, especially for recursion. It is sometimes used in IIFEs.

An array may contain strings or numbers, but also arrays, object literals and... functions (which are Function objects). If I print somebody.constructor === Function;, it will return true. Therefore, yes, you can push functions with Array.prototype.push().

var arr = [];

arr.push(function () {
  console.log('Hello');
});

arr.push(function () {
  console.log('World');
});

arr[0](); // Hello
arr[1](); // World

Upvotes: 0

Konrad
Konrad

Reputation: 24661

  1. It would throw an error - TypeError: Cannot read property push of undefined otherwise

  2. You can push a function into an array. If you do that the array will just hold the function reference.

const someFunction = function() { return 5 }

const array = []
array.push(someFunction)

console.log(array[0])

const value = array[0]()
console.log(value)

Does it ultimately make the original variable "Webflow = Webflow OR [result of the final function]?

No, no magic happens, just a function inside an array

Upvotes: 1

Related Questions