Explain Codes LogoExplain Codes Logo

What does ':' (colon) do in JavaScript?

javascript
object-literal-declarations
json-data-structures
destructuring
Anton ShumikhinbyAnton Shumikhin·Mar 10, 2025
TLDR
The `:` symbol is fundamental in JavaScript and is used in:

1. **Object literal properties**: It denotes a key-value pair relationship.
```javascript
const book = { title: '1984', author: 'Orwell' };
  1. Ternary operator: It distinguishes the true and false return expressions.
const access = age >= 18 ? 'Granted' : 'Denied';

Practical Usage

Defining properties in Object Literals and JSON:

  • : is used for object literal declarations in JavaScript.
  • Also crucial in JSON (JavaScript Object Notation) data structures, vital for AJAX calls.
const car = { type: 'Tesla', model: 'Model S' }; // vanilla JS object const jsonCar = "{\"type\": \"Tesla\", \"model\": \"Model S\"}"; // JSON string

(Car not included with this code)

Control Breaks in Loops with Labels:

  • : with labels can fine-tune flow control with break or continue in nested loops.
chocoLoop: for (let i = 0; i < 5; i++) { vanillaLoop: for (let j = 0; j < 5; j++) { if (j === 3) break chocoLoop; // Breaks the outer `chocoLoop`, not the `vanillaLoop` } } // Infinite vanilla ice cream > choco ice cream. Fight me. 🍦

jQuery Filter Selectors:

  • In jQuery, the colon designates filter selectors, a nifty DOM manipulation tool.
$('div:hidden'); // Selects hiding divs like hide-n-seek.

Ternary Operators:

  • Write one-liner conditional expressions but beware of unanticipated side effects.
const result = condition ? actionIfTrue() : actionIfFalse(); // when you can’t make up your mind.

Comprehensive Guide

Access Methods:

  • : assigns functions and properties which can be accessed by dot notation or square brackets.
const robot = { speak: function() { console.log('Beep boop'); } }; robot.speak(); // Dot notation: "Beep boop" robot['speak'](); // Square brackets: "I’m fluent in over 6 million forms of communication."

Syntax clarity:

  • You can omit unnecessary quotes around keys unless they consist of special characters for cleaner syntax.
const player = { name: 'John Doe', age: 30, 'player-score': 3200 // Quotes needed due to the hyphen }; // Other features not included: fetch quest, looting, grinding, respawn point.

Destructuring:

  • : helps in destructuring objects too. makes your code more readable and manageable.
function createUser(firstName, lastName) { return { firstName, lastName }; } // Now you too can play god with JS objects

References