How to Colon in JavaScript

Anika Tabassum Era Feb 02, 2024
  1. Colon in the Ternary Operation in JavaScript
  2. Colon in JavaScript for Object Literal Structure
  3. Use Colon in a Switch-Case Statement
  4. Set Labels With Colon in JavaScript
How to Colon in JavaScript

Colon (:) in JavaScript can be used in multiple cases. We will describe the colon convention in the ternary operator, JavaScript object literal structure, switch-case statements, and go-to statements or setting labels.

Colon in the Ternary Operation in JavaScript

The conditional operation in JavaScript is also doable in inline structure, and this specification of the if-else statement looks more neat and clear.

Firstly, a condition is applied upon which a statement will execute, and if that fails, the next statement will be executed. Here the dissection symbol between the statements is the colon.

var p = 42;
var q = 7;

console.log(p > q ? 'It\'s ' + p : 'Oops it\'s ' + q);

Output:

colon in ternary operation

Colon in JavaScript for Object Literal Structure

In the case of object literal structure in JavaScript, the key-value pairs are set with a colon. The left side of the colon is the keys, and the right side of the colon is for the value.

var object = {hair: 'long', color: 'black', age: 42}

             console.log(object.color + object.age);

Output:

object_literal_and_colon

Use Colon in a Switch-Case Statement

A switch-case statement has multiple cases for drawing out the apt solution.

While initializing the cases, we separate them with the code-block with a colon. Even the default statement in the switch-case is directed with a colon.

var day;
switch (new Date().getDay()) {
  case 6:
    day = 'It\'s Saturday';
    break;
  case 0:
    day = 'It\'s Sunday';
    break;
  default:
    day = 'Oh it\'s not holiday.'
}

console.log(day);

Output:

switch_statement_with_colon

Set Labels With Colon in JavaScript

This coding practice is not very much appreciated in most cases but can aid in many problems. After labeling a certain code block, we use a colon right after the label.

var x = 5;
var y = 42;
var z = 0;
sum: while (x < y) {
  z = x++;
  if (x >= y) {
    break sum;
  }
}

console.log(z);

Output:

set_labels_with_colon

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook