This write-up will demonstrate the working of the colon “:” in JavaScript.
What Does JavaScript Colon (:) Do?
In JavaScript, the colon “:” has a variety of uses. Let’s see the working of the colon “:” in many situations such as:
- in switch statement
- in ternary operation
- for object literal
- for setting labels
Method 1: Use Colon “:” in Switch Statement
Here, we will see the working of the Colon “:” in the switch statement for checking the added cases.
Example
Firstly, we will create a variable named “age” and assigns the value “18”:
Then, use Colon “:” in the switch statement that will check the age based on different cases:
case 15:
console.log("He is 15 years old");
break;
case 20:
console.log("He is 20 years old");
break;
default:
console.log("His age is 18 Years");
}
Output
Method 2: Use Colon “:” in Ternary Operation
Let’s see the working of the Colon “:” in the ternary operator.
Example
We will first create two variables, “a” and “b”, by assigning values “12” and “8”, respectively:
var b = 8;
Then, check which variable is greater using the ternary operator:
Finally, print the result using “console.log()” method:
The output shows the variable a is greater than b:
Method 3: Use Colon “:” for Object Literal
For creating an object in JavaScript, you can also use the colon “:” in a program. It works in such a way that you have to place the object property name before the colon and its value after that.
Example
Create an object “car” with properties “color” and “model”:
color: "Black",
model: 2019
}
Then, we will get the color of the car object and display on the console:
Output
Method 4: Use Colon “:” for Setting Labels
You can also utilize colon for setting labels which are explained in the following example.
Example
Firstly, we will create three variables “a”, “b” and “res”:
var b = 52;
var res = 0;
Then, set a label where we will use a colon:
Then, define a loop using which we will add the numbers until “a” is less than “b”:
break sum;
}
}
Lastly, we will print the sum using the “console.log()” method:
Output
We have covered all the basic information about colon “:” in JavaScript.
Conclusion
The colon “:” is a punctuation mark used in different ways in JavaScript, such as checking the case in the switch statement, setting labels, or setting object properties by creating object literals. Its use depends on your requirements. In this write-up, we have demonstrated the working of the colon “:” in JavaScript with examples.