Types of Literals in JavaScript
1. String Literals
const name1 = 'Alice';
const name2 = "Bob";
const greeting = Hello
; // Template literal
2. Numeric Literals
const age = 25; // Integer
const pi = 3.14; // Floating point
const hex = 0xFF; // Hexadecimal (255)
const binary = 0b1010; // Binary (10)
const octal = 0o12; // Octal (10)
3. Boolean Literals
const isTrue = true;
const isFalse = false;
4. Array Literals
const fruits = ['apple', 'banana', 'cherry'];
5. Object Literals
const person = {
name: 'John',
age: 30
};
6. Null Literal
const empty = null;
7. Undefined Literal
undefined is usually a value assigned by JavaScript when a variable is declared but not initialized.
let x;
console.log(x); // undefined
8. Regular Expression Literal
const pattern = /ab+c/;
9. Template Literals (Special type of string literal)
const user = 'Jane';
const message = Hello, ${user}!
; // String + Expression
✅ 1. Template Literals
Used to embed variables and expressions in strings.
const name = "Alice";
const age = 25;
const message = My name is ${name} and I am ${age} years old.
;
console.log(message);
✅ 2. HTML Element (for DOM templates)
In web development, the HTML element holds HTML that you can clone and insert into the DOM using JavaScript.
const template = document.getElementById("card-template");
const clone = template.content.cloneNode(true);
clone.querySelector(".title").textContent = "Product Name";
clone.querySelector(".description").textContent = "Product Description";
document.body.appendChild(clone);
✅ 3. Template Functions or Rendering Templates
You can create your own template functions to build strings or HTML based on data:
function renderUser(user) {
return
;
<div class="user">
<h3>${user.name}</h3>
<p>Age: ${user.age}</p>
</div>
}
const user = { name: "Bob", age: 30 };
document.body.innerHTML = renderUser(user);
Top comments (0)