How to Work with Literals and Loops in JavaScript

How to Work with Literals and Loops in JavaScript

In this blog, we are going to learn about Literals and loops used in JavaScript. When we declare a variable and assign or store a value in it, that value is a literal and has many types which we will see further. Loops are a way of handling the control flow, JavaScript provides many types of loops which we will see further.

Literals in JavaSript

A literal is a symbolization which allows the representing a static value in basis code. Notations in JavaScript are used to loading values, for instance, floating-point numbers, Boolean, integers, characters, and strings etc. Apart from these notations, there are elements notations too in this language such as arrays, and objects. Let’s look at the types of literals we can save with examples:

1. Numeric Literals

Floating-point numbers and integers both are supported by JavaScript.Integers Literals

  • Integers must have at least one digit (0-9).
  • There is no allowance for blanks or comma within an integer value.
  • It doesn’t consist any fractional part.
  • An integer value can be either positive or negative, but if no sign leads it is supposed to be a positive value.

In JavaScript, integers can be expressed in three different bases:

  • Decimal (base10) numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no leading zeros. e.g. 123, -20, 12345
  • Hexadecimal (base16) 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. e.g.0x456fff
  • Octal (base 8) numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A foremost 0 specifies that the quantity is octal. e.g.0777

Floating number literals: We are giving below the essential parts of a floating number.

  • A decimal point (‘.’).
  • A decimal integer.
  • A fraction.
  • An exponent.
  • The exponent part is an “e” or “E” followed by an integer, which can be signed (preceded by “+” or “-“).

Example of some floating numbers:8.2935    -14.7212.4e3 [ Equivalent to 12.4 x 103]4E-3 [ Equivalent to 4 x 10-3 => .004]

2. String Literals

String literals are known as the rows or lines of characters which are surrounded by double as well as single quotes. All the quotes must be matched with each other for instance if your string is opening with a single or double quote then it must be ending with a corresponding single or double quote. In strings the double quotes can hide the single quotes and single quotes can also do the corresponding.For Examples:‘This is a string’“This is a popular string”’This is “a string”‘”This is also ‘a string’ “If you are leaving a quote empty then it would be considered as a null stringEscape sequences:

  • Strings can contain escape sequences (a single character preceded with a backslash)
  • Escape sequences are a mechanism for quoting a single character.

\’ Single quotation \” Double quotation \t Tab\f Form feed\b Backspace\n Newline\r Return\e Escape\\ Backslash

3. Boolean Literals

Boolean literals are known as the logical values which contain only one of two values such as true or false, on or off, yes or no, or 1 or 0. They are used to test whether a condition is true or false. When using numeric comparison and equality operators, the value true evaluates to 1 and false evaluates to 0. E.G.: var answer = true;Usage example:if (answer == false) {do something;}

4. Array Literals

In JavaScript, an array literal is a list of expressions, each of which represents an array, enclosed in a pair of square brackets ‘ [ ] ‘ . When an array is created using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified. If no value is supplied it creates an empty array with zero length.Examples:var abc = [ ]; ———————Creating an empty array :var abc = [“feb”, “march”, “jan”] ——Creating an array with three elements.Comma in array literals:There is no need to specify all elements in an array literal. If we put two commas in a row at any position in an array then an unspecified element will be created in that place.Example:abc = [“feb”, , “march”]This array has one empty element in the middle and two elements with values. abc[0] is “feb”, abc[1] is set to undefined,  abc[2] is “march”. If you include a single comma at the end of the elements, the comma is ignored. In the following example, the length of the array is three.abc = [“feb”, “march”,] In the following example, the length of the array is four, and abc[0] and fruits[2] are undefined.abc = [ , ‘feb’, , ‘march’];

5. Object Literals

An object literal is a comma-separated list of name-value pairs wrapped in curly braces. These are read-only types. In JavaScript an object literal is defined as follows: var userObject = {}————  An object literal without properties:var someObject = {————- With properties    some_prop: ‘some string value’,    another_prop: ‘another string value’,    int_prop: 100}; 

We create it and add properties and methods to it, and all of those properties and methods are public. Object literals are formed using the following syntax rules::  A colon separates property name from value.,  A comma separates each name/value pair from the next.There will be no comma after the last property name/value pair

ARRAY OF OBJECTS

An array can contain any data type, including objects too. Syntax:

Var aOfObj=[
             {
             },
             {
             }
                      ]

Example:

var book = [
{
'title':'Half Girl Friend',
'author':'Chetan Bhagat',
'price':'Rs.145',
},
{
'title':'You can win',
'author':'Shiv Khera',
'price':'Rs.125',
}
]
  • This array contains 2 book objects, having properties namely :titleauthorprice
  • These elements can be accessed and manipulated using the array methods.

Array Methods and Properties

Array Properties:

You can access certain data about an array by accessing array properties. The way to access array properties in JavaScript is by using dot notation. To use dot notation, you type the name of the array, followed by a period, followed by the property you want to access.Properties:

  • Prototype    Allows the addition of properties and methods to an Array object
  • Constructor A reference to the function that created the Array object’s prototype
  • Length           Either returns or sets the number of elements in an array

Array Methods

JavaScript array methods (also known as array functions) provide ways to manipulate and work with arrays. The syntax for using array methods differs depending on the particular method you are trying to use; however, most of them are accessed by using dot notation. concat()  Joins two or more arrays and returns a copy of the joined arrayscopyWithin()  Copies array elements within the array, to and from specified positionsentries()  Returns a key/value pair Array Iteration Objectevery()  Checks if every element in an array pass a testfill()  Fill the elements in an array with a static valuefilter()  Creates a new array with every element in an array that passes a testfind()  Returns the value of the first element in an array that passes a testfindIndex()  Returns the index of the first element in an array that passes a testforEach()  Calls a function for each array elementfrom()  Creates an array from an objectincludes()  Check if an array contains the specified elementindexOf()  Search the array for an element and returns its positionisArray()  Checks whether an object is an arrayjoin()  Joins all elements of an array into a stringlastIndexOf()  Search the array for an element, starting at the end, and returns its positionmap()  Creates a new array with the result of calling a function for each array elementpop()  Removes the last element of an array, and returns that elementpush()  Adds new elements to the end of an array, and returns the new lengthreduce()  Reduce the values of an array to a single value (going left-to-right)reduceRight()  Reduce the values of an array to a single value (going right-to-left)reverse()  Reverses the order of the elements in an arrayshift()  Removes the first element of an array, and returns that elementslice()  Selects a part of an array, and returns the new arraysome()  Checks if any of the elements in an array pass a testsort()  Sorts the elements of an arraysplice()  Adds/Removes elements from an arraytoString()  Converts an array to a string, and returns the resultunshift()  Adds new elements to the beginning of an array, and returns the new lengthvalueOf()  Returns the primitive value of an array

Loops

Loops can execute a block of code a number of times. When we define a loop, the application performs the tasks that you set for it within the code block defined by the loop structure. Loops make it possible to perform repetitive tasks easily. We can use loops to control the way in which the repetition occurs. For example, you can choose to end a loop early when an error exists, or you might choose to skip a particular sequence of tasks.JAVASCRIPT provides the following types of loops: 1. WhileThe while statement will execute a block of code while a condition is true.Syntax:

while (condition)
{
    code to be executed
}

Example:In the following example, the code in the loop will run, over and over again, as long as a variable (counter) is less than 5:

while (counter < 5) {
    text += "The number is " + counter;
    counter++;
}

2. Do…WhileThe do…while statement will execute a block of code once, and then it will repeat the loop while a condition is trueSyntax:

do
{
    code to be executed
}
while (condition)

Example:The loop will always be executed at least once, even if the condition is false because the code block is executed before the condition is tested:

do {
    text += "The number is " + counter;
    counter++;
}
while (counter < 10);

3. ForThe for statement will execute a block of code a specified number of timesSyntax:

for (initialization; condition; increment)
{
    code to be executed
}

Example:This example will print the value of variable i till the value reaches 5.

for (i=0; i<=5; i++)
{
document.write("<b>The number is " + i + "</b>")
document.write("<br>")
}

4. For/IN LoopThe JavaScript for/in statement loops through the properties of an object.Syntax:

for(var in obj)
{
  Code to be executed..
}

Example:Here we define an object ‘person’. Then loop through it to retrieve all names in a string variable. Here x is used as an index into the object, which auto increments till the last element is reached.

var person = {fname:"John", lname:"Doe", age:25}; 
var text = "";
var x;
for (x in person) {
    text += person[x];
}

5. For/of LoopThe for…of statement creates a loop that iterates over iterable objects. For…of loop was introduced in ES6 to be an alternative to both for..in and forEach(). For..of lets you loop over data structures that are iterable such as Arrays, strings, Maps, Sets, and moreSyntax:

for (variable of iterable) 
     {
statement
     }

variable – For every iteration, the value of the property is assigned to the variable.iterable – An object which has enumerable properties and can be iterated upon. Example:

for...of operation on an array:
    var iterable = ['mini', 'mani', 'mo'];
    for (var value of iterable) {
    console.log(value);
  }

Output: 

// mini
// mani
// mo

   For..of on strings: var iterable = 'javascript'; for (var value of iterable) { 
   console.log(value); }

// Output:

// "j"
// "a"
// "v"
// "a"
// "s"
// "c"
// "r"
// "i"
// "p"
// "t"

Role of Break and Continue in JavaScript

You can use the break and continue to interrupt the execution of a loop. BREAK statement “jumps out” of a loop. The loop and continues executing the code after the loop. Example:

for (i = 0; i < 10; i++) {
    if (i === 3) { break; }
    text += "The number is " + i + "<br>";
}

Output:

The number is 0
The number is 1
The number is 2

In the above example when ‘i’ becomes equal to 3 a break statement is executed and it jumps out of the loop.CONTINUE statement “jumps over” one iteration in the loop. It breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.Example:

for (i = 0; i < 10; i++) {
    if (i === 3) { continue; }
    text += "The number is " + i + "<br>";
}
A loop which will skip the step where i = 3.
The number is 0
The number is 1
The number is 2
The number is 4

In the above example when ‘i’ equals 3 the continue statement is executed, so the 3rd value is skipped and the loop continues.Conclusion:In this write up we have seen the role of literals and loops in JavaScript. Literals allow us to create data in multiple formats such as string, numbers, array, and objects for data manipulation. Loops allow us to handle the control flow of our application for performing repetitive tasks, JavaScript provides while, do while, for loop. This was just an introductory part of JavaScript, to learn more in depth opt for JavaScript Master course.

Leave a Reply

You must be logged in to post a comment.

Copy link