Literals in JavaScript
In the Comments in JavaScript blog, we have learned about what are Comments, and ways to add comments. Comments in JavaScript are like helpful notes for developers, explaining or annotating code without affecting how the program runs. They enhance human understanding and serve as documentation. In this blog, we will learn about Literals used in JavaScript.
What are Literals?
In JavaScript, literals are fixed values that stay the same and don't change. No special keyword is needed to write a literal. They're essential for setting initial values in programming and can be strings, numbers, booleans, floating-point, or even objects. For instance, if we write the number 9546, it's a numeric literal, and if we write "Hello," it becomes a string literal.
Types of Literals
String Literal
A string literal is a sequence of characters surrounded by single(‘’), double (""), or backticks (``) quotes. Let’s take a look at the example
Output:
Number Literals
A literal number represents a numerical value. It can be an integer or a floating-point number. Let’s take a look at the example
Output:
Boolean Literal
A boolean literal has only two values: true or false. Let’s take a look at the example
Output:
Array Literal
An array literal is used to build an array of values. It is surrounded by square brackets “[ ]” and comprises a list of values separated by commas “[ , , ]”. Let's take a look at the example
Output:
Object Literal
An object literal is used to generate a key-value pair object. It is surrounded by curly brackets "" and contains a comma-separated list of key-value pairs. Let's take a look at the example
Output:
RegExp Literal
A regular expression literal is used to create a regular expression pattern. It is enclosed in forward slashes (/.../). Let’s take a look at the example
Output:
Null Literal
The null literal represents the intentional absence of any object value. Let’s take a look at the example
Output:
Undefined Literal
The undefined literal represents an uninitialized or non-existent variable or property. It is typically not explicitly assigned. Let’s take a look at the example
Output:
Symbol Literal
A symbol literal represents a unique and immutable value. Symbols are often used as object property keys. Let’s take a look at the example
Output:
In JavaScript, literals are like straightforward shortcuts for expressing values directly in code, such as numbers or text. They serve as constants that stay fixed throughout the program.