08-03-2023

Code demystified: Shorthand to Define Methods in Objects

#javascript #ES6 #objects


Going through the documentation of the react-markdown library, I was confused by this code example:

import React from 'react' import ReactDom from 'react-dom' import ReactMarkdown from 'react-markdown' import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter' import {dark} from 'react-syntax-highlighter/dist/esm/styles/prism' // Did you know you can use tildes instead of backticks for code in markdown? ✨ const markdown = `Here is some JavaScript code: ~~~js console.log('It works!') ~~~ ` ReactDom.render( <ReactMarkdown children={markdown} components={{ code({node, inline, className, children, ...props}) { const match = /language-(\w+)/.exec(className || '') return !inline && match ? ( <SyntaxHighlighter children={String(children).replace(/\n$/, '')} style={dark} language={match[1]} PreTag="div" {...props} /> ) : ( <code className={className} {...props}> {children} </code> ) } }} />, document.body )

react-markdown is a library that renders markdown text safely into React elements. Here I’ve written a thorough guide on how to use it.

In the code example, the concise syntax method that came with ES6 was used. To define a method inside an object, we no longer need to create a property and assign it to a function expression. Instead we define the function as a method directly.

Let's look at a more basic example, provided by MDN:

const obj = { foo() { return 'bar'; } }; console.log(obj.foo()); // Expected output: "bar"

This is equivalent to this:

const obj = { foo: function() { return 'bar'; } }; console.log(obj.foo()); // Expected output: "bar"

So with the traditional way the above code would look like this:

import React from 'react' import ReactDom from 'react-dom' import ReactMarkdown from 'react-markdown' import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter' import {dark} from 'react-syntax-highlighter/dist/esm/styles/prism' // Did you know you can use tildes instead of backticks for code in markdown? ✨ const markdown = `Here is some JavaScript code: ~~~js console.log('It works!') ~~~ ` ReactDom.render( <ReactMarkdown children={markdown} components={{ code: function({node, inline, className, children, ...props}) { const match = /language-(\w+)/.exec(className || '') return !inline && match ? ( <SyntaxHighlighter children={String(children).replace(/\n$/, '')} style={dark} language={match[1]} PreTag="div" {...props} /> ) : ( <code className={className} {...props}> {children} </code> ) } }} />, document.body )

There are a lot of ES6 features, I really like and wouldn’t want to miss, like destructuring or the optional chaining operator. However, I realized that I prefer the traditional way to define methods because it’s more explicit and readable in my opinion.

RESOURCES

Schmedtmann, The Complete JavaScript Course 2023: From Zero to Expert! (udemy course)

MDN

elifscode

© 2023 designed & built by Elif Gömleksiz