Member-only story
Object Literals in JavaScript
These come up in interviews more than you think
What are Object literals in JavaScript?
More than one interviewer has asked me this question for front-end positions. If you have done any kind of JavaScript development, you have used an object literal at some point. I’ll explain and provide some sample code.
Object Literal
In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces.
Those values can be properties and functions. Here’s a snippet of an object literal with one property and one function.
var greeting = {
fullname: "Michael Jackson",
greet: (message, name) => {
console.log(message + " " + name + "!!");
}
};
Here’s the snippet to use the object we just created to log the fullname
and call the greet
function with the fullname
value.
Let’s suppose we want to access the fullname
inside the greet
function instead of having to read it from a parameter. If we try to access it directly by doing something like this:
greet = (message)=> {
console.log(message + " " + fullname + "!!");
}
We will get an undefined error. The fullname
property isn’t visible directly.
However, you can create a function (e.g. getFullName()
)that accesses the fullname
value using the this
keyword, which is just the current object context.
If you’d like to read more about the this
keyword, visit W3 Schools. The function would look like this:
getFullName: () => {
return this.fullname;
}
The greet function now would look like this:
greet: (message) => {
console.log(message + " " + this.getFullName() + "!!");
}
All members of an object literal in JavaScript, both properties and functions, are public. The only place you can put private members…