How `this` behaves in JavaScript
April 24, 2025
1 min
This really is a must read for any JavaScript developer. I have written this guide to shorthand JavaScript coding techniques
This is a great code saver when you want to write an if..else statement in just one line.
// Longhand:const x = 20let answerif (x > 10) {answer = 'greater than 10'} else {answer = 'less than 10'}// Shorthand:const answer = x > 10 ? 'greater than 10' : 'less than 10'const answer =x > 10 ? 'greater than 10' : x < 5 ? 'less than 5' : 'between 5 and 10'
// Longhand:if (variable1 !== null || variable1 !== undefined || variable1 !== '') {let variable2 = variable1}// Shorthand:const variable2 = variable1 || 'new'
// Longhand:if (likeJavaScript === true)let a;if ( a !== true ) {}// Shorthand:if (likeJavaScript)let a;if ( !a ) {}
const fruits = ['mango', 'peach', 'banana'];// Longhand:for (let i = 0; i < fruits.length; i++)// Shorthand:for (let fruit of fruits)for (let item in sampleArr)
// Longhand:const x = 1920,y = 1080const obj = { x: x, y: y }// Shorthand:const obj = { x, y }
// Longhand:function sayHello(name) {console.log('Hello', name)}setTimeout(function () {console.log('Loaded')}, 2000)list.forEach(function (item) {console.log(item)})// Shorthand:sayHello = name => console.log('Hello', name)setTimeout(() => console.log('Loaded'), 2000)list.forEach(item => console.log(item))
// Longhand:function calcCircumference(diameter) {return Math.PI * diameter}// Shorthand:calcCircumference = diameter => (Math.PI * diameter;)
// Longhand:const welcome = 'You have logged in as ' + first + ' ' + last + '.'const db = 'http://' + host + ':' + port + '/' + database;// Shorthand:const welcome = `You have logged in as ${first} ${last}`;const db = `http://${host}:${port}/${database}`;
// Longhand:const observable = require('mobx/observable');const action = require('mobx/action');const runInAction = require('mobx/runInAction');const store = this.props.store;const form = this.props.form;const loading = this.props.loading;const errors = this.props.errors;const entity = this.props.entity;// Shorthand:import { observable, action, runInAction } from 'mobx';const { store, form, loading, errors, entity } = this.props;
// Longhand:// joining arraysconst odd = [1, 3, 5];const nums = [2 ,4 , 6].concat(odd);// cloning arraysconst arr = [1, 2, 3, 4];const arr2 = arr.slice()// Shorthand:// joining arraysconst odd = [1, 3, 5 ];const nums = [2 ,4 , 6, ...odd];// cloning arraysconst arr = [1, 2, 3, 4];const arr2 = [...arr];
Quick Links
Legal Stuff
Social Media