Difference between var, let and const in Javascript

The var, let and const are the keywords basically used in Javascript to declare variables. Among them var is the oldest way of declaring a variable. Other two let and const are introduced in ES2015 (ES6) update. Nowadays let and const are used more frequently in modern javascript compared to var.

In this article, we will try to understand the difference between them in respect to their scope.

Before getting into the difference first we need to know what is function scope and block scope.

Function Scope – Created by declaring a function

Block Scope – Created by if statement, for loops, while loops etc.

var in Javascript:

Var declarations are globally or functionally scoped. The var is globally scoped when it is declared outside a function and it is available for the whole program. Var is functionally scoped when it is declared inside a function.

Example of var with global scope:

Output:

2

2

The scope of variable a is global and it can be accessed anywhere in the program.

Example of var with function scope:

Output:

2

Reference Error: a is not defined

The scope of variable is within the function so if we try to access outside the function it shows error.

Limitation with var:

Var variable can be redeclared and updated. If we accidentally declared a new variable with the same name, it will override the existing value of that variable.

Output:

7

Last assigned value 7 is updated to the variable a.

If we use the var variable before declaration it is initialized with undefined value.

Output:

Undefined.

Let in javascript:

It is an improved version of var keyword. Let does not allow variable redeclaration.

Output:

Syntax error: Identifier ‘a’ has already been declared.

Scope of let:

Let is block scoped.

Output:

20

10

Now try to access b outside the function.

Output:

Reference Error : b is not defined.

If we use a variable before declaration it is not initialized with undefined just returns an error.

Output:

Reference Error: Cannot access ‘a’ before initialization

const in javascript:

Const variables maintain constant values. They share some similarities with let.

Like let declarations, const are block scoped. The difference is that unlike let, const cannot be updated or re-declared.

Output:

Type Error: Assignment to constant variable

User cannot change the properties of const object but they can change the value of properties of const object.

Output:

Type Error : Assignment to const variable.

Points to remember

varletconst
Function scopedBlock scopedBlock scoped
Allow duplicate identifiersDoes not allow duplicate identifiersDoes not allow duplicate identifiers
Value can be updatedValue can be updatedValue cannot be updated
Hoisted and initialized with undefinedHoisted but error if we try to access before declarationHoisted but error if we try to access before declaration

How to read all the cells from a sap.m.Table in SAP UI5

Steps involved in determining the total line items of a sap.m.Table

  1. get the sap.m.Table instance
  2. call the getItems() method of the sap.m.Table instance
  3. Loop through the records. For each row, get the mAggregations of the line item and then get the text property by accessing the cells of the item.
Line Items and Cells under the sap.m.Table

Main Code Below:
var tableItems = mTable.getItems();
document.write("Total no of items:", tableItems.length);
for(iRow = 0; iRow < tableItems.length; iRow++)
  {
    document.write("<br>");
    document.write(tableItems[iRow].mAggregations.cells[0].mProperties.text);
    document.write(",",tableItems[iRow].mAggregations.cells[1].mProperties.text)
    document.write(",",tableItems[iRow].mAggregations.cells[2].mProperties.text);
  }

Full code: Please run it in https://jsbin.com/?html,output
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Sap m Table">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>SAP M TABLE</title>
  
  <script id='sap-ui-bootstrap' type='text/javascript'
            src='https://sapui5.hana.ondemand.com/resources/sap-ui-core.js'
            data-sap-ui-theme='sap_bluecrystal'
            data-sap-ui-libs='sap.m,sap.ui.table'
            data-sap-ui-compatVersion='edge'></script>
  
            <script type='text/javascript'>

var jsonData = [ {columnOne : "Data row A1", columnTwo : "Data row 100", columnThree : "Data row hundred"},

                 {columnOne : "Data row A2", columnTwo : "Data row 200", columnThree : "Data row two hundred"},

                 {columnOne : "Data row A3", columnTwo : "Data row 300", columnThree : "Data row three hundred"}  ];

var jsonModel = new sap.ui.model.json.JSONModel(jsonData);

var  mTable  =  new sap.m.Table({

                columns : [

                      new sap.m.Column({ header  :  new sap.m.Label({  text : "Column One" }) }),

                      new sap.m.Column({ header  :  new sap.m.Label({  text : "Column Two" }) }),

                      new sap.m.Column({ header  :  new sap.m.Label({  text :  "Column Three" }) })

  ]

}).placeAt("content");

mTable.setModel(jsonModel);

mTable.bindAggregation("items", {

path  :   "/",

template  :  new sap.m.ColumnListItem({

cells : [

new sap.m.Text({ text : "{columnOne}"  }),

new sap.m.Text({ text :  "{columnTwo}" }),

new sap.m.Text({ text :  "{columnThree}" }),

]

})

});
var tableItems = mTable.getItems();
document.write("Total no of items:", tableItems.length);
for(iRow = 0; iRow < tableItems.length; iRow++)
  {
    document.write("<br>");
    document.write(tableItems[iRow].mAggregations.cells[0].mProperties.text);
    document.write(",",tableItems[iRow].mAggregations.cells[1].mProperties.text)
    document.write(",",tableItems[iRow].mAggregations.cells[2].mProperties.text);
  }
</script>
              
</head>
<body class='sapUiBody'>
    <div id='content'></div>
</body>
</html>

Why the Apple stocks are falling?

Reasons :

  1. There is a low in demand for apple devices due to the high inflation rate. Apple phones are one of the high quality Mobile phones, but the cost of the Apple mobile is very high
  2. During Covid Pandemic season, People were forced to sit at home due to severe Lockdown measures. So there was a huge necessity to buy high end gadgets to spend their time. But as soon as the lockdown is removed, people wanted to move spend their money in travel and other activities.
  3. Most of the electronic gadgets are produced in China. But due to China’s Zero covid policy, there is a shortage of Iphones in Apple stores. It has lead to huge Supply chain issues.

What is the difference between sap.m.Table and sap.ui.table

Parametersap.m.tablesap.ui.table
ApplicationUsed as responsive tables ( Mainly for mobiles ) Used in desktop centric applications
selectionOnly lines of record can be selected. individual cells in the table cannot be selectedIndividual cells of record can be selected.
UsageIt is not used for large set of dataIt is used for large set of data
how to get total rowstableInstance.getItems()tableInstance.getRows()
how to get bindingtableInstance.getBinding(‘items’)tableInstance.getBinding(‘rows’)

How to dynamically create a sap.m.table in SAP UI5

Required steps:

  1. define and initialize a variable with JSON Data ( Key value pairs )
  2. define a JSON Model reference variable and transfer the JSON Data through the constructor
  3. define a sap.m.Table reference and set the column Headings. Use the placeAt method to set the content
  4. Set the JSON Model to the table
  5. Assign the cell values to each row using the columnListItem class. Finally call the bindAggregation method of the Table reference and pass the cell values in the method call.

CODE EXAMPLE

SAP M TABLE

        <script type='text/javascript'>

var jsonData = [ {columnOne : “Data row A1”, columnTwo : “Data row 100”, columnThree : “Data row hundred”},

             {columnOne : "Data row A2", columnTwo : "Data row 200", columnThree : "Data row two hundred"},

             {columnOne : "Data row A3", columnTwo : "Data row 300", columnThree : "Data row three hundred"}  ];

var jsonModel = new sap.ui.model.json.JSONModel(jsonData);

var mTable = new sap.m.Table({

            columns : [

                  new sap.m.Column({ header  :  new sap.m.Label({  text : "Column One" }) }),

                  new sap.m.Column({ header  :  new sap.m.Label({  text : "Column Two" }) }),

                  new sap.m.Column({ header  :  new sap.m.Label({  text :  "Column Three" }) })

]

}).placeAt(“content”);

mTable.setModel(jsonModel);

mTable.bindAggregation(“items”, {

path : “/”,

template : new sap.m.ColumnListItem({

cells : [

new sap.m.Text({ text : “{columnOne}” }),

new sap.m.Text({ text : “{columnTwo}” }),

new sap.m.Text({ text : “{columnThree}” }),

]

})

});

What is a jQuery Object

A collection of Document Object Model(DOM) elements which are generated from a HTML is called as jQuery object. It is represented as $( ). The elements which are selected are stored in this object. It is much similar to an Array. The selected element or the DOM node index in the SAP UI5 App can be used in the jQuery object to get the UI5 control instance.

var ui5_control_instance = $($0).control(0) ===> UI5 control instance is retrieved.

The elements in the object are thus accessed through the numeric indices. The property length specifies the total number of elements

numpy.tril() in Python

numpy.tril() returns a copy of the array matrix with an element of the lower part of the triangle with respect to k. It returns a copy of array with lower part of triangle and above the kth diagonal zeroed.

Syntax:

numpy.tril(m,k=0)

Parameters:

m- number of rows in the array.

k-It is optional. Diagonal below which to zero elements. k=0 is the main diagonal and its default.

k>0 is above it and k<0 is below it.

Return value:

It returns a copy of the matrix with elements above the kth diagonal zeroed.

Example: 

import numpy as np

m = np.array([[1,2,3],[4,5,6],[7,8,9]])

print(“Sample array”)

print(m)

print(“\ntril() function without any parameter:”)

print(np.tril(m))

print(“\nAbove 1st diagonal zeroed.”)

print(np.tril(m,-1))

print(“\nAbove 2nd diagonal zeroed.”)

print(np.tril(m,-2))

numpy.triu() in Python

numpy.triu() returns a copy of the array matrix with an element of the upper part of the triangle with respect to k. It returns a copy of array with upper part of triangle and below the kth diagonal zeroed.

Syntax:

numpy.triu(m,k=0)

Parameters:

m- number of rows in the array.

k-It is optional. Diagonal above which to zero elements. k=0 is the main diagonal and its default.

k>0 is above it and k<0 is below it.

Return value:

It returns a copy of the matrix with elements below the kth diagonal zeroed.

Example:

import numpy as np

m = np.array([[1,2,3],[4,5,6],[7,8,9]])

print(“Sample array”)

print(m)

print(“\ntriu() function without any parameter:”)

print(np.triu(m))

print(“\nBelow 1st diagonal zeroed.”)

print(np.triu(m,-1))

print(“\nBelow 2nd diagonal zeroed.”)

print(np.triu(m,-2))