Menu
Coddy logo textTech

What is a String Enum?

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 53 of 73.

String enums are declared by explicitly initializing each member with a string value:

enum Direction {
  Up = "UP",
  Down = "DOWN", 
  Left = "LEFT",
  Right = "RIGHT"
}

Unlike numeric enums that auto-increment, every member in a string enum must be explicitly initialized. The benefit is immediately clear when debugging - instead of seeing mysterious numbers like 0 or 1 in your logs, you'll see descriptive values like "UP" or "DOWN".

challenge icon

Challenge

Easy

Create a string enum named Direction with four members:

  • Up initialized to "UP"
  • Down initialized to "DOWN"
  • Left initialized to "LEFT"
  • Right initialized to "RIGHT"

Create four variables to demonstrate the enum values:

  • upDirection of type Direction and assign it Direction.Up
  • downDirection of type Direction and assign it Direction.Down
  • leftDirection of type Direction and assign it Direction.Left
  • rightDirection of type Direction and assign it Direction.Right

Print the following outputs on separate lines:

  • Print the value of upDirection
  • Print the value of downDirection
  • Print the value of leftDirection
  • Print the value of rightDirection
  • Print the string value of Direction.Up
  • Print the string value of Direction.Down

Try it yourself

// TODO: Write your code here

// Print the required outputs
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript