Literals
A literal is a data value that represents a fixed value in a program.
Types of Literals
A literal is a data value that represents a fixed value in a program.
Types of Literals
- Numeric Literal
- Floating-point Literal
- Boolean Literal
- String Literal
- Array Literal
- Regular Expression Literal
- Object Literal
Numeric Literal
A numeric literal can be defined in the decimal, hexadecimal, octal.
Decimal include digits from 0-9 without a leading zero.
Hexadecimal include digits 0-9 and A-F or a-f, a leading 0x indicates hexadecimal.
Octal numeric include digits from 0-7, a leading 0 indicates octal.
example
77, 90 //decimal base 10
023, 054 //octal base 8
0x3452, 0x7788 //hexadecimal base 16
Floating-point Literal
It can have the following parts
- A decimal integer that can be positive or negative
- A decimal point (.)
- A fraction (another decimal number)
- An exponent (optional)
example
2.9089, -3.4567
Boolean Literal
It can be either true or false.
String Literal
It can be either zero or more characters enclosed in double (") or single (') quotation mark.
example
"xycn"
'123456667'
Special Characters that can be used in the String literals
- \t - represents a tab.
- \f - represents a form feed, which is also referred as form feed.
- \b - represents a backspace.
- \n - represents a new line.
- \r - represents a carriage return character, which is used to start a new line of text.
- \" - represents a double quote.
- \' - represents a single quote.
- \\ - represents a back space.
- \v - represents a vertical tab.
- \uXXXX - represents a unicode character specified by a four digit hexadecimal number.
Array Literal
It is a list of zero or more expressions representing array elements that are enclosed in a square brackets ([]).
example
var numbers = ["123","234","456"]
Regular Expression Literal
Also known as RegExp, is a pattern used to match a character or string in some text.
example
var newregexp=/abc/;
or var newregexp= new RegExp("abc");
Object Literal
It is a collection of name-value pair enclosed in curly braces ({}).
example
var sports = {cricket: 11, football: 14, chess: 5};
Example
<!DOCTYPE html>
<html>
<head>
<title>javaScript Literal</title>
</head>
<body>
<h1>JavaScript Literal</h1>
<script>
var numberLiteral = 23;
var floatingpointLiteral = 45.908;
var booleanLiteral = true;
var stringLiteral = "This is a String";
var arrayLiteral = ["array literal 1", "array literal 2", "array literal 3"];
document.write(numberLiteral + "<br />");
document.write(floatingpointLiteral + "<br />");
document.write(booleanLiteral + "<br />");
document.write(stringLiteral + "<br />");
document.write(arrayLiteral[0] + "<br />");
document.write(arrayLiteral[1] + "<br />");
document.write(arrayLiteral[2] + "<br />");
</script>
</body>
</html>
0 comments:
Post a Comment