Interview Question - JavaScript Functions - Size

This is an interview question on JavaScript Objects and Function combined.

Code

const f = (key) => {
let obj = {
name: 'bonsaiilabs',
location: 'Victoria, BC',
size: () => 2
}
return obj[key]
}
console.log(f('size'))

Full Transcript

In this question, we have created a function f that takes one parameter. The implementation of f returns a value from the object that it creates inside it. The value returned is based on the key provided. In the last line we are calling the function f with size as the argument and printing the result on the console. Let's work together to find the right answer. So as we see, the first thing f does that it creates an object called obj. This object contains two properties, name and location. The values for these properties are of type string. And it contains a method known as size(). The value of this property is a function. It is an anonymous arrow function which does not take any input and returns the value of two every single time it is called. The next line of f retrieves the value from the object obj, which means if you send the key as name you will get bonsaiilabs back.

Finally, in the last line of this code, we are sending the size as the key and logging the result on the console. Since size() is a method on object, you will get function back, which is the correct answer to this question. Let's run the code in the editor to make sure our understanding is correct. When I hit run for the same code, we can confirm that we get the function size as the output. And that's it. If you work with JavaScript or any other frameworks such as jQuery, angular, or react, you have executed JavaScript on the browser. So the new course that we have launched is relevant for you. It's called Browser JavaScript and event loop. This goes educates on how JavaScript is executed behind the scenes, and we'll cover various topics such as ExecutionContext and event loop. You will have the opportunity to visually see every step of JavaScript code execution. Check out the course link in the description below to learn more about the course and let us know if you have any questions. Keep learning and see you next time.