facebook youtube pinterest twitter reddit whatsapp instagram

Exploring Data Types, and Variables in JavaScript

In JavaScript or any programming language, a data type is an attribute of data that tells the interpreter how the programs intend to use the given data.

JavaScript support a couple of data type which are integer numbers of varying sizes, characters, Booleans, Floating point number to mention a few.

The interesting thing about coding in JavaScript is the fact that it is a loosely typed language, meaning a single variable can contain any type of data, string, boolean, etc. Unlike other languages where you need to first declare what the variable would do, you don’t need that in JavaScript, just store your variable away, and use it how you see fit.

Let's start with...

Variables

A data type can’t hold itself, and so, we need a certain type of container or a memory location that stores the value. An example of such is a variable.

Variable can be thought of as a memory location that can hold values of a specific data type, the name “variable” means something that is likely to vary or something that is subject to variation, so, with that meaning, we can say a variable may change during the life of the script or program.

Variable Naming Convention:

  • A valid variable name can starts with a dollar sign followed or a letter or underscores followed by letters, digits, or underscores.
  • They cannot start with digits as the first character
  • They can’t contain any space, and they are case sensitive, meaning $book is different from $Book

Before you can use a variable or constant in a JavaScript script, you must declare it, this can be done with either the let or const keywords.

To declare variable myBook, I'll do something as follows:

let myBook;

You can also define multiple variables in a single let statement:

let x, y, add;

The best practice when using a variable is to make sure you assign an initial value to your variables when you declare the, don't just do let x;but do let x = 4;

Since it can vary, you can change it later if you want. Initializing a value to a variable with the let statement would avoid undefined value (meaning empty).

To declare a constant instead of a variable, use const instead of let. const works just like let except that you must initialize the constant when you declare it, and once a const is declared the values cannot be changed. Here is an example of a constant:

const IMAGE = "black";
const PIXEL = 720;

You don't have to use all caps, this is just a way to tell it apart from a variable.

Use const when you know a value won't change, e.g a pixel of a certain device, an image format, and something you know you won't change.

Integers

Integers are any natural number, whether positive or negative, e.g 1, 5, 900, -5, -6, 7, etc are all integer numbers. In JavaScript, you can represent all integer between −9,007,199,254,740,992 (−253) and 9,007,199,254,740,992 (253).

Consider we have the following assigned to the below variables:

$myVar1 = 5;
$myVar2 = 3;

We can add, multiply, subtract and even divide value of 2 variables, so, to add the 2 variables, you can do:

> $myVar1 = 2; $myVar2 = 3;
> $myVar1 + $myVar2;
// Output is: 5

The above would simply return 5, you can apply the same syntax to substraction, division, and multiplication, so, I don’t need to show you that again.

Also, if you have ever need to be sure of what type is actually returned, you can use typeof keyword followed by the variable name to get it, here is an example:

$myVar1 = 2; $myVar2 = 3;
$total = $myVar1 + $myVar2;

console.log(typeof $total);
// number

Hope you get that. If it was a string, it would return string, if boolean it would return boolean, etc

Here is a bit more advanced example:

$var1 = 5; $var2 = 3;
((2 + 2 + $var1)) * + $var2; 

// Output is: 27

The above is a basic math, and the math rules still apply in JS, so, what happens here is that it would first do operation on 2 + 2 + $var1, which is 9, and it then multiply the result by 3 ($var2), which then gives us 27.

If the variable already has an integer value, and you want to basic operation (add, sub, divide, multiply) on it, here are short and superb way, you can do it real quick:

$var1 += 4; // Take the value of $var1 and add it by 4, while also storing it in $var1

$var1 *= 4; // Take the value of $var1 and multiply it by 4, while also storing it in $var1

$var1 /= 2; // Take the value of $var1 and divide it by 4, while also storing it in $var1

$var1 -= 4; // Take the value of $var1 and minus it by 4, while also storing it in $var1

Keep in mind that, whatever you get would be replaced by the last operation, for example, if you have $var1 set to 5, and you did $var1 += 4;, the answer would be the new value of $var1, which in this case would be 9.

Before we go to the next section, let’s look at increment and decrement in JS, if for example $var1 is 5, and you want to increment it by 1, you can do:

$var1 = 5;
$var1++;

// Output is 5

If you do the above, the output is still going to be 5 (I’ll explain why later), but here is the fix:

$var1 = 5;
$var1++; 
$var1; 

// The output is: 6

The above is called post-increment, it also applies to substraction, which would be $var--this is called post-decrement.

Isn’t it weird that the first time we tried incrementing the value in the variable, it didn’t work until we had to output it again below the code, before I explain why it works that way, let me introduce you to pre-increment, here is how that works:

Assuming the initial value of the var variable is 5, and you run the following code:

$var1 = 5;
++$var1; 

// The output is: 6

This would give you 6 right off the bat.

Here is the explanation:

Post-increment ($var1++) and the pre-increment(++$var1) are used to increase the value by one while decrement is the opposite of increment; decrease the value by one.

When using a post-increment (e.g i = $var1++), it means first assign the value of ‘$var1’ to ‘i’, then increment x, which is why we have post; after. It won’t get used immediately, only after.

Pre-increment (e.g i = ++$var1) means increment $var1 first and then assign the value of x to y straight away, so, when using pre-increment, it increment or decrement straight away.

Let’s take another example, say you have the following:

$var1 = 5;
i = $var1++;
i; // i would be assigned 5

If the value of ‘$var1’ is 5 then value of variable ‘i’ will be 5 because old value of ‘x’ is used, remember post means after.

and if you have the following:

$var1 = 5;
i = ++$var1;
i; // i would be assigned 6

If the value of ‘$var1’ is 5 then value of variable ‘i’ will be 6 because the value of i gets incremented before using it in a expression.

So, when should you use one of the two?

The answer is simple, use post-increment when you don’t want to increment straight away and use pre-increment when you want to increment right-way, pre-increment will be faster since it doesn’t make any copy.

Floating Point

A floating-point is a number that has a decimal in them followed by a significant digit e.g 88.222727.

So, when dealing with a number that can’t give us an even result, it results in a floating-point number, in most cases, JS would handle this for you, e.g, when you do 4/5 it gives you:

0.8

The good thing about javascript is that you can break long numbers up into chunks by using underscores, for example:

let trillion = 1_000_000_000_000;
trillion;

// output is 1000000000000

We are using underscore as a thousands separator, this can make things easier to read. Note that, this is a new standard, and it's only implemented by modern major browsers.

Now, let’s get into math methods, here are examples of how it works (I have added explanations on all of ’em):

/*
# Example 1: Math.abs(number) (This function is used to return the absolute (positive) value of a number.)
#
# The output of the below is: 3
*/
Math.abs(0 - $var2);

/*
#
# Example 2: Math.pow(base, number) (This function  returns x raised to the power of y, e.g 2^2 = 4.)
#
# The output of the below is: 3125
*/
Math.pow(5, $var1);

/*
#
# Example 3: Math.sqrt(arg: number) (This function multiply a number by itself)
#
# The output of the below is: 5
*/
Math.sqrt(25);

/*
#
# Example 4: Math.random() (Gives any random number in decimal that is lesser than 1, e.g 0.3444)
#
*/
Math.random(); 
// If you want to get a random number higher than that, you can do:
let $var = Math.random() * 10;
console.log($var); // This would give random number in decimal from 1 to 9, e.g 9.422

// If you want to get a random number fron 1 to 10 in integer, you can add + 1, and you then round it to floor:
let $var = Math.floor(Math.random() * 10 + 1);
console.log($var); // Would return a random number from rang 1 - 10.

/*
#
# Example 5: Math.round(number) (Round to the nearest integer)
#
# The output is 8
*/
Math.round(7.8);

/*
#
# Example 6: Math.ceil(number) (Round up to an integer)
#
# The output is 8
*/
Math.ceil(7.2);

/*
#
# Example 7: Math.floor(number) (Round down to an integer)
#
# The output is 7
*/
Math.floor(7.8);

/*
#
# Example 8: Math.PI (π: circumference of a circle / diameter)
#
*/
Math.PI; // 3.14

/*
#
# Example 9: Math.E (The base of the naturla logarithm)
#
*/
Math.E; // 2.718281828459045

/*
#
# Example 10: Math.max(values) (Return the largest argument)
#
*/
Math.max(9,4,5); // 9

/*
#
# Example 11: Math.min(values) (Return the smallest argument)
#
*/
Math.min(9,4,5); // 4

Text & String

The JavaScript type for representing text is the string. A string is a sequence of characters, words, or other data (e.g dollar sign, etc). JavaScript uses the UTF-16 encoding of the Unicode character set, and JavaScript strings are sequences of unsigned 16-bit values.

One important thing to note is that in JavaScript, strings are immutable, meaning once a string is created, it is not possible to modify it, this is different in programming languages like C, PHP, Ruby, etc where strings are mutable.

If you are wondering the meaning of a character set, don’t worry it is simple. A character set is a set of symbols and encodings.

To put it simply, a character set defines how and which characters are stored to support a particular language or languages

Suppose that we have an alphabet with four letters: A, B, a, b. We give each letter a number: A = 0, B = 1, a = 2, b = 3. The letter A is a symbol, the number 0 is the encoding for A, and the combination of all four letters and their encodings is a character set, hope you get the idea now.

Now, let's go over how to use a string in Js. To include a string in a JavaScript program, you simply enclose the characters of the string within a matched pair of single or double-quotes. Here is an example:

"" // Empty String. It has zero character
"I am a string enclosed in double-quotes"
'I am a string enclosed in a single quote'
"She's at my house"
`You can also use backticks to enclose a string`

Typically, a string is written on a single line, as of ES5, you can break a string literal across multiple lines by ending each line with a backslash(\).

Here are examples:

'A two\nlines string' // 2 lines string written on one line

// one-line string written on 3 lines:
"one\
 long\
 line"

// A two-line string written on two lines with backtick:
`You can also write multiline string
the way I am doing it, just enclose it with backtick`

Note: If a string is enclosed in a quotes, PHP will interpret the escape sequences for special characters, the backslash allows you to escape from the usual interpretation of the quote character. I won’t list them all, but here are the most popular used ones:

Sequences and Their Meaning

\nThis advances to the next newline e.g


"Hello \nHow You Are ? ";

gives

Hello 
How You Are ?
\tHorizontal tab e.g


"\tHello, How You Are ? ";

gives

	Hello, How You Are ?
\vVertical Tab,
\\Backslash. e.g


"Hello, How Are You \\? ";

gives

Hello, How Are You \?
\"Double quotes, e.g


echo "Learn Enough To Be Dangerous - \"Author\"";

gives

Learn Enough To Be Dangerous - "Author"

Let's see a couple of examples of how you can use a string.

Suppose you have the following:

$userName = "devsrealm_guy";
let greetuser = "Welcome," + " " + $userName;

You guessed it, greetuser would give you "Welcome, devsrealm_guy"

The + operator with string is used for concatentaing two string together. Really, we can just use: "Welcome," + $userName but that would return Welcome,devsrealm_guywith no space, so, + " " + means we are concatenating a space + another value, in short, you can add anything with the 2 double quotes like so: "Welcome," + "middle" + $userNamewhich would return Welcome,middledevsrealm_guytrust you understand that now.

You can also append a string to variable, e.g:

$str = "One";
$str +=" Two"; // Append Two to whatever is in the $str variable
console.log($str);
// => One Two

$str +=" Three"; // Append Three to whatever is in the $str variable
console.log($str);
// => One Two Three

Also, strings can be compared with the standard === equality and !==inequality operators: two strings are equal if and only if they consist of exactly the same sequence of 16-bit values. Strings can also be compared with the <, <=, >, and >= operators.

Before we go into the next section, let me quickly show you another way you can do a variable replacement, consider the following example:

$bk = "books";
"We currently have 15 $bk in the library";

In the above example, we stored book into the variable $bk and if you look at the following example carefully, I am trying to expand the variables in the string, you might expect this to give you something like: "We currently have 15 books in the library" but this won't work because JS interpreter would consider $bk a string. We can off course concatenate it, but here is a better solution:

let $bk = "books";
`We currently have 15 ${ $bk } in the library`;

// => "We currently have 15 books in the library"

As you can see, we are no longer using double quotes, but a backtick, the final value of a string literal in backticks is computed by evaluating any included expressions, it expands whatever is in that variable into a normal string literal text.  The expression inside the braces is evaluated and then converted to a string and inserted into the template, replacing the dollar sign, the curly braces, and everything in between them.

It serves as a superb substitution for concatenation, they are quicker to type and code looks cleaner. Suppose you want to programmatically replace book to books when there is more than one book, not using the backticks and curly braced expression would cause unnecessary assignment of variables, look at the following example:

let $bk = "book";
`We currently have 15 ${ $bk }s in the library`;

// => "We currently have 15 books in the library"

Like, I don't even need to add books to the variable, it allows me to smoothly separate the variable name and the characters inside a string, this only won't let me write beautiful codes, but also help in avoiding unnecessary variables, imagine having to define a variable for "book", and another variable for "books". Just don't forget to use the backticks whenever you are in need of something like this.

Just like you saw in the integer sections, there are also a couple of handy methods you can use with string, the below are examples of beautiful API for working with strings:

Note: I'll represent the output like so: =>

let myString = "Hello, world"; // Init some strings
/*
#
# Example 1: Determining the Length of a String
#
# Make sure you append length method to the myString variable
# 
*/ 
myString.length;      // => 12

/*
#
# Example 2: Obtaining portions of a string
#
# Make sure you append the method to the myString variable
# 
# Note: The first chacter is of index 0, so, H has zero index in "Hello"
*/ 
myString.slice(3,6);           // => "lo" the 4th and 5th char
myString.substring(3,6);      //  => "lo" same as slice
myString.slice(-5);           // => "world" the last 5 char
myString.split(", ");         //=> ["Hello", "world"]: split at delimiter string, meaning, Hello would be at index 0, and world would be at index 1

/*
#
# Example 3: Creating a modified version of a string, toUpperCase, toLowerCase, replace
#
# Make sure you append the method to the myString variable
# 
*/ 
myString.replace("Hello", "Hey");  / / => "Hey, World"
myString.toLowerCae();             //  => "hello, world"
myString.toUpperCase();           //   => "HELLO, WORLD"

// Example:
console.log(myString.toUpperCase());
// => HELLO, WORLD
console.log(myString.toLowerCase());
// => hello, world
/*
# Unicode NFC normalization: ES6, 
# this is used for converting string into its unicode normalization form, 
# this is good if you know ur strings are the same but not sure if 
# the unicodes are the same, if the sequence of unicode code points are not the same
# semantically, it is not identical to the computer.
*/
myString.normalize();

/*
#
# Example 4: Inspecting individual (16-bit) characters of a string
#
# Make sure you append the method to the myString variable
# 
*/ 
myString.charAt(0);                 // => "H"; The first character 
myString.charCodeAt(0);             // => 72: 16-bit number at the specified position
/*
#  => "d": last character, we are using the lenght method to
# get the total lenght of the string in our case, it is 12
# and when you sub 1 from it, we get 11, that's how we are able to get the last char 
*/
myString.charAt(myString.lenght-1); 

/*
#
# Example 5: Searching a string position
#
# Make sure you append the method to the myString variable
# 
*/ 
myString.indexOf("d");          // => 11 , position of letter d
myString.indexOf("o", 5);       // => 8 , position of letter 0, after the 5th index
myString.indexOf("u");          // => -1, nothing like "u" in the string contained in myString variable
myString.lastIndexOf("l");      // => 10 , position of last letter l

/*
#
# Example 6: Boolean searching functions in ES6 and later
#
# Make sure you append the method to the myString variable
# 
*/ 
myString.starsWith("world");              // => false , the string doesn't start with "world"
myString.endsWith("world");               // => true , the string endswith "world"
myString.startsWith("Hel");               // => true, the string startswith "Hel"
myString.includes("orl");                 // => true, the string includes "orl"

/*
#
# Example 7: Trimming functions
#
# 
*/ 
" love ".trim();         // => "love" -   remove spaces at start and end
" love ".trimStart();    // => "love " -  remove spaces on left. Also trimLeft
" mean ".trimEnd();      // => " mean" -  remove spaces at right. Also trimRight

/*
#
# Example 8: String Padding Functions
#
# 
*/ 
"xy".padStart(5);             // => "   xy"     - pad with 5 spaces on the left to a length of 5
"xy".padEnd(4);               // => "xy  "      - pad with 4 spaces on the right to a length of 4
"yx".padStart(3, ".")         // => ".yx"        - add dot(.) on the left to a length of 3
"yx".padStart(5, ".")         // => "...yx"       - add dots(.) on the left to a length of 5
"x".padEnd(7, "-")            // => "x------"     - add dashes on the right to a length of 7

/*
#
# Example 9: Concatenation methods
# 
*/ 
myString.concat( Faruq);    // => "Hello, world Faruq" - you can also use the + operator, it's your choice
myString.repeat(2);         // => "Hello, worldHello, world" concatenate n copies
"hey".repeat(2);            // => "heyhey" repeat hey x2

/*
#
# Example 10: Uppercase and Lowercase
#
*/

As you can see it provides lots of methods you can use to manipulate strings, depending on what you are working on, you can also treat strings as read-only arrays, and you can access individual characters from a string using square brackets instead of the charAt() method, something like this:

let myString = "Hey Man";
myString[2]                                                      // => y
myString[4]                                                      // => M , it doesn't count space as an array item
myString[myString.length-1]                           // => n, last char

Booleans

We've seen an example of boolean, but you might not be aware of it, Boolean is a type that can either be True or False, they can only have one of two values (True or False), please note that the Ture is not the string, "True", likewise the False is not the string "False". It's simply the value True and False and as you've seen, they can be used to perform tests on an operation.

Here is an example:

let x = 5;
x === 5;      // => true

We are testing to see whether the value of the variable x is equal to the number 5. If it is, the result of this comparison is the boolean value true. If a is not equal to 5, the result of the comparison is false.

See:

let x = 3;
x === 5;       // => false

If you are already familiar with any language, then the thing is, boolean values are often used in control structures, you are not just aware. The if/else statement in JavaScript performs one action if a boolean value is true and another action if the value is false.

Here is an example:

let x =5;
if (x === 5) {
    ++x;
} else {
  "Not equals to 5";
}
// => 6

let x =4;
if (x === 5) {
    ++x;
} else {
  "Not equals to 5";
}

// => "Not equals to 5"

We are checking whether x equals to 5, if true(you see what I did there, true is a boolean value), increment x, and if else prints 'Not equals to 5"

As you can see the first example gave us 6, and the second one gave us "Not equals to 5", because it returns a boolean value of false.

Boolean values have a toString() method that you can use to convert them to the strings “true” or “false”.

null and undefined

In computer programming, a null is a character denoting nothing, in JavaScript, we also have the undefined value that denotes nothing also, the only difference between the two is that you'll usually get an undefined value when you query the value of an object property or array element that does not exist.

null and undefined are not that distinct, but if you apply the typeof operator to the undefined value, it returns“undefined”, indicating that this value is the sole member of a special type. If there is anything you should take away, a null is a character that denotes nothing, and you can assign it to variables or property, while you typically get an undefined value when an object property element does not exist, but you can also assign it to variables, so, it's only a matter of preference.

Conversions and Equality

Conversions and equality are one of the misunderstood concepts in JS, but it's actually super simple. In JavaScript, we have two operators that test whether two values are equal of which are:

  • Strict equality operator: ===
  • non-strict equality operator: ==

For example: when you have:

"0" == 0 // => true

JavsScript would convert the string into a number, and then compare, which is why it returns true. We were previously discussing that null and undefined basically mean the same thing, and if you test the equality:

null == undefined // => true

JS would treat both values as equal, the thing is, the values are equal but not identical. A value is only identical, if they are of the same type, string ‘5’, is not identical to integer 5, but they are equal to one another. So, here is the thing, if you are testing for identical values use strict equality (===), and this is what you should mostly be using, as it not only tests if the types are identical but also if the values are the same. In short, to be on the safer side, always use strict equality.

If your value is coming from somewhere you are not sure of the type or you don't want JavaScript to make the conversion for you, meaning, you want to explicitly convert the values yourself to keep your code clearer.

You can use the following explicit type conversion:

Number("55")      // converts string "55" to number 55
Number(true)       // converts boolean true to number, it would gives us 1, and false gives 0
Number(null)       // converts null to number, which would return 0
Number('Hey')       // we are trying to convert a string to a number, it would return NaN, meaning not a number
Number([1,2,3,4])    // same as above
String(true)        // converts boolean value true to string "True"
String([1,2,3,4,5]) // converts the array values to string "1,2,3,4,5"
Boolean([])         // converts an empty objects to true

Here is another way you can so conversions:

parseInt("6 I have no idea")        // => 6
parseFloat(" 3.14 what is this")    // => 3.14
parseInt("-19.84")                  // => -19 integers can't have a decimal numner, so, it picks the integer portion
parseFloat(".1")                    // => 0.1
parseInt("0.1")                     // => 0
parseInt(".7")                      // => NaN: integers can't start with "."
parseFloat("$92.07")               // => NaN: numbers can't start with "$"

The parseInt() and parseFloat() functions are more flexible, the parseInt() parses only integers, while parseFloat() parses both integers and floating-point numbers. You'll hardly ever need this, but it is good you know they exist.

Template Literals

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. We've talked about this before, where we did:

let $bk = "book";
`We currently have 15 ${ $bk }s in the library`;

// => "We currently have 15 books in the library"

The ${ bk } is a template literal, and as you can see we are expanding the variable $bk.

Imagine you want to inject an HTML from your js script into your HTML page, you'll normally do something like so:

let name = 'The Devsrealm Guy';
let age = 18;
let profession = 'Web Developer';
let html; // define the variable that would contain our html codes

/*
# Without Template Literals ES5
# We are concatenating all of the variables to form an html ul..li tag
 */
html = '<ul>' +
    '<li>Name: ' + name + '</li>' +
    '<li>Age: ' + age + '</li>' +
    '<li>Profession: ' + profession + '</li>' +
    '</ul>';
/*
#
# Change the HTML content of the current document.
# This will overwrite all existing HTML elements inside <body>,
# with whatever is in the html variable
#
 */
document.body.innerHTML = html;

Output:


1. Injecting js to html... without template literal

While this isn't bad, you can make your life easier with template literals like so:

let name = 'The Devsrealm Guy';
let age = 18;
let profession = 'Web Developer';
let html; // define the variable that would contain our html codes

/*
# With Template Literals ES5
# In a multiline template string or literals, make sure it is enclosed in a backtick
 */
html = `
  <ul>
    <li>Name: ${name}</li>
    <li>Age: ${age}</li>
    <li>Profession: ${profession}</li>
    <li>${2 + 2}</li>
    <li>${greet()}</li>
    <li>${age > 20 ? 'Over 20' : 'Under 20'}</li>
  </ul>
`;
function greet() {
    return "I am Within The Template Literals";
}
/*
#
# Change the HTML content of the current document.
# This will overwrite all existing HTML elements inside <body>,
# with whatever is in the html variable
#
 */
document.body.innerHTML = html;

In a multiline template string or literals, make sure it is enclosed in a backtick.

As you can see, I can even run functions or even conditions, you can do just about any expressions, which is amazing, here is the output:

 Injecting js to html... with template literal

Arrays

An array is an orderly arrangement of a collection of multiple values, that is the basic explanation I can up with. You can think of them as a collection of values stored in a specific variable, and also provides a way to access the value.

Indexed Arrays

A simple analogy of understanding how array work is picturing a single door storage cabinet, here is what it looks like:

Single Door Cabinet

The above cabinet has 6 shelves, so, let’s imagine that you can store items on each shelf, so, for example, you might have a book on the first shelf, a cloth on the second shell, electric bills on the third shelf, and so on.

You might not be thinking about this, but the way you put them in, is the way it comes out, for example, a book was placed on the first shelf, so, to take it out, you gonna go to the first shelf, you won’t go to the second shelf nor would you go to the third shelf, they are orderly arranged, which is the way it works in an array.

Unlike the cabinets here, there is no limit to the shelves you can have in an array, you can have millions of them, each shelf can contain anything that a variable can contain, be it a string, empty, a number, and even another array (nested array).

There are two ways you can define an array in JS, the first way is a square-brackets [1,2,3,4,5]; which is my preferred way in JS, and the second way is instantiating an object, and passing a value const numbers = new Array(1,2,3,5);

Here is an example:

$myVar= [4,8,15,16,23,42];

Just like the cabinet analogy, $myVar would be the cabinet, since that is the place we are storing our array items, the position you put the array items are the shelves, and they are going to stay in that exact order, so that way, we can retrieve them by the position of how that are arranged, seems easy right!

Before we go about retrieving them, I want you to note that by default, array indices start at zero, this is also called a Zero-based array indexing, it is a way of numbering the items in an array such that the first item of it has an index of 0. So, if want to output the first item in the array, we would query the number 0, which would then return 4 in our case, and if we query index 1, it would retrieve 8. let’s see an example:

$myVar= [4,8,15,16,23,42];

console.log($myVar[0]); // The output of this is: 4
console.log($myVar[1]); // The output of this is: 8
console.log($myVar[2]); // The output of this is: 15
console.log($myVar[3]); // The output of this is: 16

So, make sure you understand this, the first item in an array would be referred to by using the index zero, like the cabinet example, an array can contain anything a variable can contain, let’s see an example:

$myCollection = ["James", 55, "Pascal", ["a", "b", "c", 8]];

In the above array, we have a string, a number, and also a nested array which also contains a couple of items (string and number), it doesn’t matter what data type you are putting in the array, just make sure they are a valid data type.

To retrieve “Pascal” you simply refer to number 2, e.g

$myCollection = ["James", 55, "Pascal", ["a", "b", "c", 8]];
console.log($myCollection[2]);

// Output
=> Pascal

But how do we query the nested array, if you reference number 3, then you might be correct, just that JS would output only number 8, and discard the rest, which isn't something we want. So, to pull data out of the nested array, we call the actual array position, which is [3], and we then call it’s children, e.g [0], [1], [2], etc, the below is an example:

$myCollection = ["James", 55, "Pascal", ["a", "b", "c", 8]];
console.log($myCollection[3][2]); 

// Output:
==> c

Note: The nested array is also called a multi dimensional array, so, I won’t cover that anymore in this guide.

You can also replace a value in an array, if I want to replace “Pascal” with “Faruq”, I simply note the position where “Pascal” is placed, in this case it is number 2, I then use an assignment operator, e.g:

$myCollection = ["James", 55, "Pascal", ["a", "b", "c", 8]];
$myCollection[2] = "Faruq";
console.log($myCollection[2]); 
// => Faruq

This isn’t actually an ideal method if you simply want to go to the end or you don’t know how long the numbers are, in that case, you can use the push method, it would then append it to the end of wherever the last index is, e.g:

$myCollection = ["James", 55, "Pascal", ["a", "b", "c", 8]];
$myCollection.push("cat");

Here is the indexes:

0: "James"
1: 55
2: "Pascal"
3: (4) ["a", "b", "c", 8]
4: "cat"

Easy right, if you want to remove an item just use variable_name.pop(); and that would remove the last item in the array. To remove the first element use variable_name.shift().

Arrays are a superb solution if you have numerous items, e.g, if you want to create a thousand usernames, you wouldn’t want to create a thousand variables, we can simply assign all of them to an array, and then use one easy-to-reference variable to pull up each username by its index.

Another good thing about an array is whatever you put in an index, stays in that index, so, an array is good for orderly arranged items, if you like, you can sort the order by numeric or alphabetically, whatever you want, is possible with an array.

Array Functions

Here are more examples of what you could do:

$myVar= [4,8,15,16,23,42];
// Get array length, how many values are in the array
val = $myVar.length;
console.log(val);
// => 6

// Check if is array
val = Array.isArray($myVar);
console.log(val);
// => true

// Find index of value
val = $myVar.indexOf(15);
console.log(val);
// => 2

You can also mutate (change or alter) an array:

// MUTATING ARRAYS

// Add on to end
$myVar.push(33);

// Add on to front
$myVar.unshift(33);

// Take off from end
$myVar.pop();

// Take off from front
$myVar.shift();

// Reverse
$myVar.reverse();

The one I really like is the splice method. It mutates the array and returns an array of all elements removed from the array. An empty array is returned if no elements are removed:

* Splice values
#
# The method mutates the array and returns an array of all elements removed from the array.
# An empty array is returned if no elements are removed.
 */
$myVar.splice(1,3);
/*
#
# Here is an example
#
 */
$myVar= [4,8,15,16,23,42];
console.log($myVar.splice(1,3));
// => [8, 15, 16] // This returned 8, 15, 15 because that is what it removed. Again, the splice methods mutates and return an array of all elemenets removed

The splice() method is also used to add new elements in a given position in an array.

// List of languages
let languages = ['python', 'java', 'c++'];

/*
# Add new languages from index 2:
# This would remove on c++ and add the other items, if you don't wannt remove any item, you can use start adding an item from index 3.
#
 */
languages.splice(2, 0, 'javascript', 'php', 'shell');

// Output result
console.log(languages);
// => ["python", "java", "c++", "javascript", "php", "shell"]

You can also concatenate a number:

// Concatenate array
numbers = [1,2,3,4,5];
numbers2 = [6,7,8,9]
val = numbers.concat(numbers2);
console.log(val);
// => [1, 2, 3, 4, 5, 6, 7, 8, 9]

Sorting an array is also another common function:

// Sorting arrays
let fruit = ['Banana', 'Apple', 'Lime', 'Tangerine', 'Orange', 'Pear'];
val = fruit.sort();
console.log(val);
// => ["Apple", "Banana", "Lime", "Orange", "Pear", "Tangerine"]

As you can see the above, we sort them in alphabetically order. You can sort number the way you can sort a string in an array, however, you can do sorting pretty easily by using the compare function:

$myVar= [4,8,15,16,23,42];
val = $myVar.sort(function(x, y){
   return x - y;
});
console.log(val);
// => [4, 8, 15, 16, 23, 42]

You can reverse it like so:

$myVar= [4,8,15,16,23,42];
val = $myVar.sort(function(x, y){
   return y - x;
});
console.log(val);
// => [42, 23, 16, 15, 8, 4]

In ES6, you can short it to the below using arrow functions:

$myVar.sort((x, y) => x - y); // For ascending sort
$myVar.sort((y, x) => y - x); // For descending sort

Honestly, I really do not like the solution above, as it might be slow, and it's kinda hard to get your head around it. The best way to sort a number is to create a TypedArray, this way, you actually know you are working on a specific data type array, and that would handle sorting easily. Here is an example:

$myVar= [4,8,15,16,23,42]; // Array Items
var num = new Int8Array($myVar);
num = num.sort();
console.log(num)
// => [4, 8, 15, 16, 23, 42]

Easy and faster. You can learn more about TypedArray

You can also find a number in an array like so:

arrayItem = [4,8,15,16,23,42]; // Array Items
function over20(arrayItem){
    return arrayItem > 20;
}
val = arrayItem.find(over20);
console.log(val);
// => 23

We created a function that takes an arrayItem, and return a value if greater than 20. We then use the find() method to return the value of the first element in the provided array that satisfies the condition in the function. That is basically how find works. It is expecting you to test a condition, you then pass the function that test the condition.

If you want to return the index of the found item, you can use findIndex():

arrayItem = [4,8,15,16,23,42]; // Array Items
function over20(arrayItem){
    return arrayItem > 20;
}
console.log(arrayItem);
val = arrayItem.findIndex(over20);
console.log(val);
// => 4

Basics of Object Literals

A JavaScript object literal is a comma-separated list of name-value pairs wrapped in curly braces. Object literals encapsulate data, enclosing it in a tidy package. This minimizes the use of global variables which can cause problems when combining code.

The following is an example of an object literal:

const user = {
    firstName: 'The Devrealm',
    lastName: 'Guy',
    age: 18,
    profession: "Web Developer",
}
const user = {
    firstName: 'The Devrealm',
    lastName: 'Guy',
    age: 18,
    profession: "Web Developer",
}
let val;
val = user; // Simulate Instantiation of Object or another way of saying this is that the values in the user object would be passed to the val variable.

// Get a certain value
val = user.firstName;
console.log(val);
// => The Devsrealm

Another you can get a value is doing:

val = user['lastName'];
console.log(val);
// => Guy

Easy enough I guess.

The good thing about Object literal values is the fact that it can be any data type, including array literals, functions, and nested object literals. Here is an example:

onst user = {
    firstName: 'The Devrealm',
    lastName: 'Guy',
    age: 18,
    profession: "Web Developer",
    interest: ['Music', 'Reading'], // can contain an array
    getBirthYear: function(){ // can contain a function
        return 2020 - this.age; // the this keyword is used to access property in an object literal
    }
}

To get the index 1 of the property in the object user, I can do:

// Get index array 1 in the user object
val = user['interest'][1];
console.log(val);
// => Reading

To get the function, I can do:

// Get the function
val = user.getBirthYear();
console.log(val);
// => 2002

In the function, I had  return 2020 - this.age,  the this keyword is used to access property in an object literal, in this case, I am accessing the property age. So, whenever you need to use a certain property, you need to use the this keyword to access the object.

You can even have a nested object:

const user = {
    firstName: 'The Devrealm',
    lastName: 'Guy',
    age: 18,
    profession: "Web Developer",
    interest: ['Music', 'Reading'], // can contain an array
    music: { // can contain an Embedded Object
        Avicii: 'Silhoulette',
        Asa: 'Jailer',
    },
    getBirthYear: function(){ // can contain a function
        return 2020 - this.age; // the this keyword is used to access property in an object literal
    }
}

Which you can access like so:

// Get the value of an embedded object
val = user.music.Avicii; or // val = user['music']['Avicii'];
console.log(val);
// => Silhoulette

You can also have an array of objects where you loop through it, here is an example:

const songs = [
    {artiste: 'Avicii', title: 'Silhoulette'},
    {artiste: 'Fela', title: 'Colonial Mentality'},
    {artiste: 'Asa', title: 'Jailer'}
];

for(let i = 0; i < songs.length; i++){
    console.log(songs[i].artiste);
}

// =>

Avicii
Fela
Asa

We created an array of objects, which have the following objects and elements:

0: {artiste: "Avicii", title: "Silhoulette"}
1: {artiste: "Fela", title: "Colonial Mentality"}
2: {artiste: "Asa", title: "Jailer"}

To get Fela, we can do: console.log(songs[1].artiste);

With that in mind, I then created a for loop that says let initial value of i equals zero(0) - this would kickstart the loop and as long as the length of the arrays is less than i, keep looping (i++). The i++ would only be incremented at the end of every loop.

We then have this: console.log(songs[i].artiste);

  • The first time it goes through, i is 0, and since the length of the array is 3 (remember length is how many items are in the array not array indexes), so, i is less than 3, it then prints the first index of the array object that has a property of artiste. Which is Avicii
  • Before the loop proceeds for the second iteration, the i++ would increment it by 1; 0 + 1 = 1, and again, the length of the array is 3, so, i is still less than 3, it prints the second index of the array object  that has a property of artiste which is Fela,
  • Before the loop proceeds for the third iteration, the i++ would increment i by 1 making it 2; 1 + 1 = 2, and again, the length of the array is 3, so, i is still less than 3, it prints the third index of the array object  that has a property of artiste which is Asa
  • Beofre the loop proceeds for the third iteration, the i++ would increment i by 1, making it 3, 2 + 1, and since 3 < 3 is false, it breaks out.

Another way you can write it using the while loop:

const songs = [
    {artiste: 'Avicii', title: 'Silhoulette'},
    {artiste: 'Fela', title: 'Colonial Mentality'},
    {artiste: 'Asa', title: 'Jailer'}
];

let i = 0;
while (i < songs.length) {
    items = songs[i].artiste;
    console.log(items);
    i++;
}

You can make things a bit fancy by printing the title and song name, something like so:

const songs = [
    {artiste: 'Avicii', title: 'Silhoulette'},
    {artiste: 'Fela', title: 'Colonial Mentality'},
    {artiste: 'Asa', title: 'Jailer'}
];
for(let i = 0; i < songs.length; i++){
    items = songs[i].artiste + " - " + songs[i].title;
    console.log(items);
}


// =>
Avicii - Silhoulette
Fela - Colonial Mentality
Asa - Jailer

Dates and Time

Javascript comes with a Date objects for working with dates and time. The Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.

To start using the date object, create a new instance of the Date:

let today = new Date();
console.log(today);

// =>  Fri Dec 04 2020 16:44:56 GMT+0100 (West Africa Standard Time)

By default, it would output the current date and time.

To get a certain date, you can do:

let somedate = new Date('4-04-2020 11:25:00');
console.log(somedate);
// => Sat Apr 04 2020 11:25:00 GMT+0100 (West Africa Standard Time)

If you use the typeof to check the type of a date, it would return an object, and that is because a date is a reference type, which is an object:

let somedate = new Date('4-04-2020 11:25:00');
console.log(typeof somedate);
// => object

You can also convert it to a string if you want to do something with it in a string format:

let somedate = new Date('4-04-2020 11:25:00');
val = somedate.toString();
console.log(typeof val);
// => String

You have access to lots of get and set methods:

let today = new Date();

// Date Get Methods
console.log(today.getMonth());            // => 11
console.log(today.getDate());             // => 4
console.log(today.getDay());              // => 5
console.log(today.getFullYear());        // => 2020
console.log(today.getHours());           // => 16
console.log(today.getMinutes());         // => 59
console.log(today.getSeconds());         // => 33
console.log(today.getMilliseconds());    // => 842
console.log(today.getTime());            // => 1607097573842

// Conversion
console.log(today.toDateString());       // => Fri Dec 04 2020
console.log(today.toTimeString());       // => 17:05:23 GMT+0100 (West Africa Standard Time)

birthday = new Date('05/07/1997');
// Set Method
birthday.setMonth(2);
birthday.setDate(7);
birthday.setFullYear(1999);
birthday.setHours(4);
birthday.setMinutes(25);
birthday.setSeconds(40);

console.log(birthday); 
// => Sun Mar 07 1999 04:25:40 GMT+0100 (West Africa Standard Time)

Related Post(s)

  • Getting Started With JavaScript (Introduction)

    This is my first JavaScript guide on this blog, and in this guide, we would go over the introduction of JavaScript, but first… What is JavaScript? JavaScript is a client-side scripting language su

  • Operator in Javascript

    Operators in javascript can either be used for logical expression where you connect two or more expressions and can be a comparison expression where you compare two values. You can also use an operat

  • Creating a Loader and Remove it After a Specific Time Using JavaScript/CSS/SVG

    In this guide, we would create a loader, and remove it after a specific time using CSS and JavaScript. The icon would be in SVG format, and the rotation would be done in CSS, while the removal after

  • Object Oriented Programming in JavaScript (The ES5 Way)

    In this guide, you'll learn and understand how to create and use Objects in JavaScript (ES5). While ES6 already supports creating classes (which is the way you create objects in Java, PHP, etc), they

  • Working With The Local & Session Storage In JavaScript

    We previously take a deep dive into the Windows Object, Properties, Methods, and even the Document Object itself, in this guide, we would explore working with the local and session storage in JavaScr

  • Guide To Functions In JavaScript

    Functions in JavaScript or any programming languages are modular building blocks for creating powerful and modular scripts, using function makes it easy to isolate a code since it would be packaged u