Javascript: Working with Two dimensional arrays

You can work with one dimensional arrays by specifying the array elements in square brackets.

var colors = ["blue", "red", "white", "green"];

Now if you want to work with two dimensional arrays, you can make a one dimensional array as one of the elements specified in square brackets

var codes = [ [1, 2, 3, 4], [5, 6, 7, 8]]

Now to access each element, you have to specify both the row number and column number

codes[0][0]
1

You can also have varying length for a row

var codes = [ [1, 2], [5, 6, 7, 8]]

As you can see row 1 has length 2 and row 2 has length 4.
If you access an array element which is not present, you will get undefined

codes[0][3]
undefined
Advertisements

Javascript: Working with Arrays (One Dimensional)

Working with arrays in Javascript is very simple. Specify the array elements in comma separated format in square formats.

var colors = ["blue", "red", "white", "green"];

The index of the first element of the array starts with 0. So to access the first element of the array

colors[0]
"blue"

You can find the length of an array using length

colors.length
4

Check how to work with 2 Dimensional arrays.

Javascript: Working with Strings

Working with strings in Javascript is very simple. You need to put the string in double quotes or single quotes

"Joys of Programming"
'Programming made simpler and easier'

Now if you want to use them, you can simply use them in variables.

var site_name = "Joys of Programming";

Let’s same operations like concatenation (+)

site_name = site_name + ": Programming made easier and joyful"
"Joys of Programming: Programming made easier and joyful"

Javascript: Working with Floating point Numbers

Javascript is dynamically typed language. So unlike other programming languages like C/C++/Java, you need not explicitly specify the type like float, double to work with floating point numbers. You can simply mention

var price = 34.23;

Yes, it is as simple as that.
And perform operations like

new_price = price + 12.34;

Javascript: Working with Constants

Variables in Javascript which can take variable values during program execution. But if you want to work with constants like PI, you can make use of const.

The syntax is

const name [= value];

The best example for a const is PI (used in various mathematical formulas)

const pi = 3.14;

There are some more things that one can understand from the above syntax. The following line is completely fine

const interest;

If you have followed the post on assignment of variables, you will know that interest has the value undefined.

Now let’s try to declare interest again

const interest;
const interest = 3.0;

You will get the following error

TypeError: redeclaration of const interest

But the following statements are totally fine

var interest;
var interest = 3.0;

This is because constants once declared remains same throughout the program and cannot be declared once again