JavaScript literals are values that are represented directly in the source code. They are not variables, but rather fixed values that cannot be changed. JavaScript supports a variety of literal types, including:
- String literals are enclosed in double or single quotes, e.g., "hello world" or 'hello world'.
- Numeric literals can be integers or floating-point numbers, e.g., 123 or 123.45.
- Boolean literals can be either true or false, e.g., true or false.
- Object literals are collections of key-value pairs enclosed in curly braces, e.g., { name: "John Doe", age: 30 }.
- Array literals are lists of values enclosed in square brackets, e.g., [1, 2, 3, 4].
Here is an example of a JavaScript program that uses literals:
var myName = "John Doe";
var myAge = 30;
var myObject = {
name: myName,
age: myAge
};
var myArray = [1, 2, 3, 4];
This program creates four variables: myName, myAge, myObject and myArray. The myName variable is assigned the string literal "John Doe", the myAge variable is assigned the numeric literal 30, the myObject variable is assigned the object literal { name: "John Doe", age: 30 }. and the myArray variable is assigned the array literal [1, 2, 3, 4].
Literals are a fundamental part of JavaScript programming. They are used to represent values in the source code, and they can be used to initialize variables, create objects, and build arrays.
No comments:
Post a Comment