Create Time Table using JavaScript at the developer console

Viewed 74

I am learning JavaScript and I want to make times table from 2 to 10 and want to display it at the developer console. I could only do the times table of 2. But I could not do it up to 10.

My code is :

var i = 0;
var j = 2;
var product = i*j;

for (i=0; i<=10; i++) {
  console.log(j,"*",i,"=",product);
}

I wrote this code and could make it only for the times table of two. What can I add to it to make the times table up to 10 and display it at the developer console? The time table must be displayed vertically.

2 Answers

The var product = i*j; here is constant. You should put this inside the For Loop:

var i = 0;
var j = 2;


for (i=0; i<=10; i++) {
  var product = i*j;
  console.log(j,"*",i,"=",product);
}

Edit: You are still using ES5 syntax. It is fine but since today is already 2020, I recommend you to learn modern JavaScript ES6 (aka ES2015) and beyond. I think ES6 is cleaner and makes a lot of things easier. Here's your code example from ES5 to ES6:

const j = 2;

for (let i = 0; i <= 10; i++) {
  console.log(`${j} * ${i} = ${j * i}`);
}

Helpful Links: let, const, template literals

Indeed, learning ES5 first is still relevant because it is still valid for ES6+ and won't give you a headache by often searching ES5 syntax that you don't understand when working on legacy codes.

You also can use console.table if you desire:

const j = 2;
const table = [];
for (let i = 0; i <= 10; i++) {
    table.push({i,j,product:i*j});
}
console.table(table)

Related