A guide to JavaScript Literals

JavaScript Literals are the fixed value that cannot be changed, you do not need to specify any type of keyword to write literals. Literals are often used to initialize variables in programming, names of variables are string literals.

A JavaScript Literal can be a numeric, string, floating-point value, a boolean value, or even an object. In simple words, any value is literal, if you write a string "Studytonight" is literal, any number like 7007 is literal, etc.

JavaScript supports various types of literal.

Numeric Literal - An integer must have at least one digit (0-9). It does not contain any fractional part. In JavaScript, integers can be expressed on three different bases.

i) Decimal ( base 10) - Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no leading zeros.

        
123, -20, 12345
        
    

ii) Hexadecimal ( base 16) - Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D, E, F, or a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal.

        
7b, -14, 3039        
    

iii) Octal (base 8) - Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number is octal.

        
173, -24, 30071
        
    

Floating-Point Literal - A floating number has the following parts.

A fraction.

An exponent.

A decimal integer.

        
7.9712, -11.29, 60.4e9
        
    

Boolean Literal -  The Boolean type has two literal values.

true

false

String Literal - A string literal is a combination of zero or more characters enclosed within a single(') or double quotation marks (").

        
 “hello”, “world”        
    

String Special Characters:

Character Description
\n New line
\t Tab
\b Backspace
\f Form feed
\r Carriage return
\' Single quote
\" Double quote
\\ Backslash character (\)

Array Literal - An array literal is a list of zero or more expressions representing array elements that are enclosed in a square bracket ( [ ] ).

        
var person =[‘John’, ’Carter’, ’Layfield’];
        
    

Object Literal - It is a collection of key-value pairs enclosed in curly braces( { } ). The key-value pair is separated by a comma.

 

        
var sports ={‘cricket’:1, ‘football’:2};
        
    

Regular Expression Literal - Regular Expression is a pattern, used to match a character or string in some text. It is created by enclosing the regular expression string between forwarding slashes.

        
 var regexp = /xy-z/
        
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top