Last active
April 29, 2026 08:51
-
-
Save TracyGJG/994cdfc3adde7b51294b1426681ad099 to your computer and use it in GitHub Desktop.
Coding styles in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Case study | |
| Write a function that, when given an object returns the value of a specific property of that object. | |
| Exercise | |
| Create an object with two numeric properties (x=42 and y=666) and log just the x property to the console. | |
| */ | |
| // Procedural style | |
| { | |
| function getPropertyX(obj) { | |
| return obj.x; | |
| } | |
| const testObj = { x: 43, y: 666 }; | |
| console.log('Procedural', getPropertyX(testObj)); | |
| // or taking the instructions literally. | |
| function logPropertyX(obj) { | |
| console.log('Procedural', obj.x); | |
| } | |
| } | |
| // OOP style (use a method because everything is an object/class!) | |
| { | |
| class classZ { | |
| #x; | |
| #y; | |
| constructor(x, y) { | |
| this.#x = x; | |
| this.#y = y; | |
| } | |
| get x() { | |
| return this.#x; | |
| } | |
| } | |
| const testObj = new classZ(42, 666); | |
| console.log('OOP', testObj.x); | |
| } | |
| // or, literally, add method log | |
| { | |
| class classZ { | |
| #x; | |
| #y; | |
| constructor(x, y) { | |
| this.#x = x; | |
| this.#y = y; | |
| } | |
| log() { | |
| console.log('OOP', this.#x); | |
| } | |
| } | |
| // and call: | |
| const testObj = new classZ(42, 666); | |
| testObj.log(); | |
| } | |
| // Functional style | |
| { | |
| const getProperty = (propName) => (obj) => obj[propName]; | |
| const testObj = { x: 42, y: 666 }; | |
| console.log('Functional', getProperty(`x`)(testObj)); | |
| // or | |
| const getX = getProperty(`x`); | |
| console.log('Functional', getX(testObj)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment