Assembly in Progress...

Literals in JavaScript

Literal Basics

The term "literal", in this context, comes from computer science,  where a literal is a notation for representing a fixed value in source code. In JavaScript, it is enclosed by { } or [ ].

Object Literal: This is enclosed by { } and consists of a key (String or Number) and a value (any type) separated by a colon, with each entry separated by a comma.

const myObject = {
    "a_prop": "a string",
    "a _second_prop": 3,
    7: false
}

Literals defining Arrays: Arrays defined with a literal are wrapped in [] and separate values with a comma.

let nameArray = {
    "Tom",
    "John",
    "Tia"
}
// RESULTS IN: Tom,John,Tia

Literals defining Regular Expressions: When not using literal syntax to create regular expressions, we must start by escaping with two backslashes. This is not required with literals, making literal syntax far more common. We only need a forward slash at the beginning and end.

The literal example below represents a regex expression for a number:

const literalRegEx = /d+/

Template Literals (Strings)

Template Literals (once called Template Strings) are strings that allow for embedded expressions, multi-line strings and injections of different types into the string. For this, we use  ` `  (backticks) to enclose the string and $(variable) to include non-string items.

`A long sample string with a ${variable} mixed in`

There are many good examples of all that can be included in Template Literals at LINK

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

q
↑ Back to Top