+ 4

JavaScript Foundations

This question is from a timed JavaScript Challenge. What is the output of this code? var f = [ function(a, b) { return a + b }, function(a, b) { return a - b }, function(a, b) { return a * b }, function(a, b) { return a / b }, function(a, b) { return a % b } ]; var x = f[0] (4, 6); var x = f[3] (x, 2); var x = f[4] (18, x); The output is 3. I understand the output. My question is, is this an example of an array, an object, and a method all in one?

16th Nov 2018, 7:55 AM
DumbledoresAmy
DumbledoresAmy - avatar
7 Respostas
+ 5
We will start with the building block — function. Basically it's just a wrapper of multiple statements which group together and possibly with a return value. Besides, we can call it by its name. When we are talking about methods then you may think of it like a function as well, but attaching to an object. You may find more information at:- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions
16th Nov 2018, 8:48 AM
Zephyr Koo
Zephyr Koo - avatar
+ 9
I don't understand how that x value becomes 3 in the end, to my understanding, f[0] is the one that returns result of a + b. Here's how I read the code, please guys, correct me if I misunderstood how it's done ; ) 1. x = 4 + 6 => 10 2. x = x + 2 => 12 3. x = 18 + x => 30 Did I miss anything here, any input/correction is appreciated. TIA,
16th Nov 2018, 8:55 AM
Ipang
+ 8
Oh that's quite alright, for a moment there I thought I was losing my mind, but now it's clear :D Thanks for clarification and confirmation ...
16th Nov 2018, 9:05 AM
Ipang
+ 3
YES, almost everything in JavaScript can be treated as an object, including functions. 😉
16th Nov 2018, 8:03 AM
Zephyr Koo
Zephyr Koo - avatar
+ 3
Zephyr Koo Thank you for explaining. Can you explain a little about methods? Methods are actions performed on objects. So because the object completes calculations, this makes it a method?
16th Nov 2018, 8:15 AM
DumbledoresAmy
DumbledoresAmy - avatar
+ 2
Ipang I made a mistake writing in the challenge question but fixed it. Thanks/sorry! Zephyr Koo Thank you!
16th Nov 2018, 9:02 AM
DumbledoresAmy
DumbledoresAmy - avatar
+ 1
DumbledoresAmy You're welcome! 😉
16th Nov 2018, 12:42 PM
Zephyr Koo
Zephyr Koo - avatar