# 6 Tricks to Write Less JS ## 1. Ternary Operator ### commonly used ``` javascript let isEmpty = true; if (isEmpty === true) { console.log('Empty'); } else { console.log('Is not empty'); } ``` ### less code ``` javascript let isEmpty = true; isEmpty ? console.log('Empty') : console.log('Is not empty'); ``` ### the shortest way ``` javascript let isEmpty = true; console.log(isEmpty ? "Empty" : "Is not empty"); ``` ## 2. Destructuring ``` javascript const post = { data: { id: 1, title: 'Post 1', content: 'Hello world', author: 'Christopher' } } const id = post.data.id; const title = post.data.title; const content = post.data.content; const author = post.data.author; console.log(id, title, content, author); ``` ``` javascript const post = { data: { id: 1, title: 'Post 1', content: 'Hello world', author: 'Christopher' } } const {id, title, content, author} = post.data; console.log(id, title, content, author); ``` ## 3. Short For Loop ``` javascript const fruits = ['apple', 'banana', 'orange']; for (let i = 0; i < fruits.length; i ++) { const fruit = fruits[i]; console.log(fruit); } ``` ``` javascript const fruits = ['apple', 'banana', 'orange']; for (let fruit of fruits) console.log(fruit); ``` ## 4. Assign a Value If Exists ``` javascript let port; if (process.env.PORT) { port = process.env.PORT; } else { port = 5000; } ``` ``` javascript let port = process.env.PORT || 5000; ``` ## 5. Template Literals ``` javascript const name = 'Christopher'; const age = 24; console.log(name + ' is ' + age + ' years old.'); ``` ``` javascript const name = 'Christopher'; const age = 24; console.log(`${name} is ${age} years old.`); ``` ## 6. Objects with Identical Keys and Values ``` javascript const userDetails = { name: name, // 'name' key = 'name' variable email: email, location: location }; ``` ``` javascript const userDetails = { name, email, location }; ``` ### Resource [@scalipsum](https://www.instagram.com/p/B_Pp5ZLgYX2/) ###### tags: `JavaScript`