Literals in JavaScript: Array, Object, String
Literals represent fixed values in JavaScript. Here we'll talk about these three Literals mainly:
2. Object
3. String
An array is a collection of elements enclosed in square brackets( [] ).
Example
const arr = ['a', 'b', 'c']
To get the actual length of the array use length property as
console.log(arr.length) //output: 3
Consider another example:
console.log(arr.length) //output: 4
This is because, if you put two commas in a row in array, the array leaves an empty slot.
Note: If you include a trailing comma at the end of the list of elements, the comma is ignored.
An Object literal is a list of zero or more pairs of property names and associated values of an object, enclose in curly braces({}).
Example:
const = {name1:"value1", name2:"value2", ...}
To access the values using the name in an object:
console.log(p.uid) //output:1618
console.log(p['pid']) //output:1618
Note: property names which are not a valid identifier cannot be accessed using dot(.) property. But they can be accessed using bracket notation.
Example:
console.log(p.' ') //Syntax Error
console.log(p[' ']) //output:empty
A string literal is a sequence or zero or more characters enclosed within either double(") quotes or single(') quote.
Example: 'hello', "world", "tour's"
length property is used to get the actual length of the string as:
console.log('hello'.length) //output:5
To combine the values of string and variable together, instead of concatenation we can use template literal enclose in bach-tick(`).
Example:
console.log( `hello ${name}` ) //output: hello Narendra
Note: If you want to store a long string value, instead of writing all of them on a single line, you can write it on multiple line using a backlash. The string will escape a line break by preceding it with backlash as:
welcome to our \
page\
Think design and Create.'
console.log(welcomeMsg)
//Output: hello there welcome to our page Think design and Create
Comments
Post a Comment