How to count all elements in an array in PHP?

To count all the elements in an array, PHP offers count() and sizeof() functions. The count() and sizeof() both functions are used to count all elements in an array and return 0 for a variable that has been initialized with an empty array. These are the built-in functions of PHP. We can use either count() or sizeof() function to count the total number of elements present in an array.

For example

We will discuss the program implementation for all the array elements using both count() and sizeof() methods.

Example 1: Counting using count()

<?php  
    $ele = array("Ryan", "Ahana", "Ritvik", "Amaya");  
    $no_of_ele = count($ele);  
    echo "Number of elements present in the array: ".$no_of_ele;  
?>

Output

Number of elements present in the array: 4

Example 2

<?php  
    $ele = array(14, 89, 26, 90, 36, 48, 67, 75);  
    $no_of_ele = sizeof($ele);  
    echo " Number of elements present in the array: ".$no_of_ele;  
?>  

Output

Number of elements present in the array: 8

Example 3: Counting using sizeof()

<?php  
    $ele = array("Jan", "Feb", "Mar", "Apr", "May", "Jun");  
    $no_of_ele = sizeof($ele);  
    echo " Number of elements present in the array: ".$no_of_ele;  
?>

Output

Number of elements present in the array: 6

Example 4

<?php  
    $ele = array(14, 89, 26, 90, 36, 48, 67);  
    $no_of_ele = sizeof($ele);  
    echo " Number of elements present in the array: ".$no_of_ele;  
?>

Output

Number of elements present in the array: 7

Example 5: Example using 2D array

<?php  
    $snacks = array('drinks' => array('cold coffee', 'traffic jam', 'Espresso',  
    'Americano'), 'bevrage' => array('spring rolls', 'nuddles'));  
    echo count($snacks, 1);  
    echo "</br>";  
    echo sizeof($snacks, 1);      
?>  

Output

8
8

PHP Array Functions

PHP provides various array functions to access and manipulate the elements of array. The important PHP array functions are given below.

1) PHP array() function

PHP array() function creates and returns an array. It allows you to create indexed, associative and multidimensional arrays.

Syntax

  1. array array ([ mixed $… ] )  

Example

<?php    
$season=array("summer","winter","spring","autumn");    
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";    
?>    

Output:Season are: summer, winter, spring and autumn

2) PHP array_change_key_case() function

PHP array_change_key_case() function changes the case of all key of an array.

Note: It changes case of key only.

Syntax

  1. array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )  

Example

<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
print_r(array_change_key_case($salary,CASE_UPPER));   
?>    

Output:Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )

Example

<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
print_r(array_change_key_case($salary,CASE_LOWER));   
?>    

Output:

Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )

3) PHP array_chunk() function

PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can divide array into many parts.

Syntax

  1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )  

Example

<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
print_r(array_chunk($salary,2));   
?>    

Output:

Array ( 
[0] => Array ( [0] => 550000 [1] => 250000 ) 
[1] => Array ( [0] => 200000 )
)

4) PHP count() function

PHP count() function counts all elements in an array.

Syntax

  1. int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )  

Example

 

<?php    
$season=array("summer","winter","spring","autumn");    
echo count($season);    
?>   

Output:4

5) PHP sort() function

PHP sort() function sorts all the elements in an array.

Syntax

  1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )  

Example

<?php    
$season=array("summer","winter","spring","autumn");    
sort($season);  
foreach( $season as $s )    
{    
  echo "$s<br />";    
}    
?>    

Output:

autumn
spring
summer
winter

6) PHP array_reverse() function

PHP array_reverse() function returns an array containing elements in reversed order.

Syntax

  1. array array_reverse ( array $array [, bool $preserve_keys = false ] )  

Example

   

<?php    
$season=array("summer","winter","spring","autumn");    
$reverseseason=array_reverse($season);  
foreach( $reverseseason as $s )    
{    
  echo "$s<br />";    
}    
?> 

Output:

autumn
spring
winter
summer

7) PHP array_search() function

PHP array_search() function searches the specified value in an array. It returns key if search is successful.

Syntax

  1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )  

Example

<?php    
$season=array("summer","winter","spring","autumn");    
$key=array_search("spring",$season);  
echo $key;    
?>    

Output:

2

8) PHP array_intersect() function

PHP array_intersect() function returns the intersection of two array. In other words, it returns the matching elements of two array.

Syntax

  1. array array_intersect ( array $array1 , array $array2 [, array $… ] )  

Example

  

<?php    
$name1=array("sonoo","john","vivek","smith");    
$name2=array("umesh","sonoo","kartik","smith");    
$name3=array_intersect($name1,$name2);  
foreach( $name3 as $n )    
{    
  echo "$n<br />";    
}    
?>  

Output:

sonoo
smith

PHP Multidimensional Array

PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column.

Definition

  1. $emp = array  
  2.   (  
  3.   array(1,”sonoo”,400000),  
  4.   array(2,”john”,500000),  
  5.   array(3,”rahul”,300000)  
  6.   );  

PHP Multidimensional Array Example

Let’s see a simple example of PHP multidimensional array to display following tabular data. In this example, we are displaying 3 rows and 3 columns.

IdNameSalary
1sonoo400000
2john500000
3rahul300000

  

<?php    
$emp = array  
  (  
  array(1,"sonoo",400000),  
  array(2,"john",500000),  
  array(3,"rahul",300000)  
  );  
  
for ($row = 0; $row < 3; $row++) {  
  for ($col = 0; $col < 3; $col++) {  
    echo $emp[$row][$col]."  ";  
  }  
  echo "<br/>";  
}  
?>  

Output:

1 sonoo 400000 
2 john 500000 
3 rahul 300000 

PHP Associative Array

PHP allows you to associate name/label with each array elements in PHP using => symbol. Such way, you can easily remember the element because each element is represented by label than an incremented number.

Definition

There are two ways to define associative array:

1st way:

  1. $salary=array(“Sonoo”=>”550000″,”Vimal”=>”250000″,”Ratan”=>”200000”);  

2nd way:

  1. $salary[“Sonoo”]=”550000″;  
  2. $salary[“Vimal”]=”250000″;  
  3. $salary[“Ratan”]=”200000″;  

Example

  

<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");  
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
echo "Vimal salary: ".$salary["Vimal"]."<br/>";  
echo "Ratan salary: ".$salary["Ratan"]."<br/>";  
?>  

Output:

Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000

   

<?php    
$salary["Sonoo"]="550000";  
$salary["Vimal"]="250000";  
$salary["Ratan"]="200000";   
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
echo "Vimal salary: ".$salary["Vimal"]."<br/>";  
echo "Ratan salary: ".$salary["Ratan"]."<br/>";  
?> 

Output:

Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000

Traversing PHP Associative Array

By the help of PHP for each loop, we can easily traverse the elements of PHP associative array.

   

<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");  
foreach($salary as $k => $v) {  
echo "Key: ".$k." Value: ".$v."<br/>";  
}  
?> 

Output:

Key: Sonoo Value: 550000
Key: Vimal Value: 250000
Key: Ratan Value: 200000

PHP Indexed Array

PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by an index number which starts from 0.

PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.

Definition

There are two ways to define indexed array:

1st way:

  1. $size=array(“Big”,”Medium”,”Short”);  

2nd way:

$size[0]="Big";  
$size[1]="Medium";  
$size[2]="Short";  

PHP Indexed Array Example

 

<?php  
$size=array("Big","Medium","Short");  
echo "Size: $size[0], $size[1] and $size[2]";  
?> 

Output:Size: Big, Medium and Short

<?php  
$size[0]="Big";  
$size[1]="Medium";  
$size[2]="Short";  
echo "Size: $size[0], $size[1] and $size[2]";  
?>  

Output:Size: Big, Medium and Short

Traversing PHP Indexed Array

We can easily traverse array in PHP using foreach loop. Let’s see a simple example to traverse all the elements of PHP array.

<?php  
$size=array("Big","Medium","Short");  
foreach( $size as $s )  
{  
  echo "Size is: $s<br />";  
}  
?>  

Output:

Size is: Big
Size is: Medium
Size is: Short

Count Length of PHP Indexed Array

PHP provides count() function which returns length of an array.

<?php  
$size=array("Big","Medium","Short");  
echo count($size);  
?>  

Output:

3

PHP Arrays

PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single variable.


Advantage of PHP Array

Less Code: We don’t need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.


PHP Array Types

There are 3 types of array in PHP.

  1. Indexed Array
  2. Associative Array
  3. Multidimensional Array

PHP Indexed Array

PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:

  1. $season=array(“summer”,”winter”,”spring”,”autumn”);  

2nd way:

$season[0]="summer";  
$season[1]="winter";  
$season[2]="spring";  
$season[3]="autumn";  

Example

<?php  
$season=array("summer","winter","spring","autumn");  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
?>  

Output:

Season are: summer, winter, spring and autumn

<?php  
$season[0]="summer";  
$season[1]="winter";  
$season[2]="spring";  
$season[3]="autumn";  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
?>  

PHP Associative Array

We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

  1. $salary=array(“Sonoo”=>”350000″,”John”=>”450000″,”Kartik”=>”200000”);  

2nd way:

$salary["Sonoo"]="350000";  
$salary["John"]="450000";  
$salary["Kartik"]="200000";  

Example

<?php    
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");    
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
echo "John salary: ".$salary["John"]."<br/>";  
echo "Kartik salary: ".$salary["Kartik"]."<br/>";  
?>    

Output:

Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

 

<?php    
$salary["Sonoo"]="350000";    
$salary["John"]="450000";    
$salary["Kartik"]="200000";    
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
echo "John salary: ".$salary["John"]."<br/>";  
echo "Kartik salary: ".$salary["Kartik"]."<br/>";  
?>   

Output:

Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

PHP Data Types

PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be categorized further in 3 types:

  1. Scalar Types (predefined)
  2. Compound Types (user-defined)
  3. Special Types

PHP Data Types: Scalar Types

It holds only single value. There are 4 scalar data types in PHP.

  1. boolean
  2. integer
  3. float
  4. string

PHP Data Types: Compound Types

It can hold multiple values. There are 2 compound data types in PHP.

  1. array
  2. object

PHP Data Types: Special Types

There are 2 special data types in PHP.

  1. resource
  2. NULL

PHP Boolean

Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE.

Example:

<?php   
    if (TRUE)  
        echo "This condition is TRUE.";  
    if (FALSE)  
        echo "This condition is FALSE.";  
?>  

Output:

This condition is TRUE.

PHP Integer

Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers without fractional part or decimal points.

Rules for integer:

  • An integer can be either positive or negative.
  • An integer must not contain decimal point.
  • Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
  • The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.

Example:

<?php   
    $dec1 = 34;  
    $oct1 = 0243;  
    $hexa1 = 0x45;  
    echo "Decimal number: " .$dec1. "</br>";  
    echo "Octal number: " .$oct1. "</br>";  
    echo "HexaDecimal number: " .$hexa1. "</br>";  
?>

Output:

Decimal number: 34
Octal number: 163
HexaDecimal number: 69

PHP Float

A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional or decimal point, including a negative or positive sign.

Example:

<?php   
    $n1 = 19.34;  
    $n2 = 54.472;  
    $sum = $n1 + $n2;  
    echo "Addition of floating numbers: " .$sum;  
?>  

Output:

Addition of floating numbers: 73.812

PHP String

A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters.

String values must be enclosed either within single quotes or in double quotes. But both are treated differently. To clarify this, see the example below:

Example:

<?php   
    $company = "Javatpoint";  
    //both single and double quote statements will treat different  
    echo "Hello $company";  
    echo "</br>";  
    echo 'Hello $company';  
?>

Output:

Hello Javatpoint
Hello $company

PHP Array

An array is a compound data type. It can store multiple values of same data type in a single variable.

Example:

<?php   
    $bikes = array ("Royal Enfield", "Yamaha", "KTM");  
    var_dump($bikes);   //the var_dump() function returns the datatype and values  
    echo "</br>";  
    echo "Array Element1: $bikes[0] </br>";  
    echo "Array Element2: $bikes[1] </br>";  
    echo "Array Element3: $bikes[2] </br>";  
?>  

Output:

array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM

You will learn more about array in later chapters of this tutorial.

PHP object

Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly declared.

Example:

<?php   
     class bike {  
          function model() {  
               $model_name = "Royal Enfield";  
               echo "Bike Model: " .$model_name;  
             }  
     }  
     $obj = new bike();  
     $obj -> model();  
?>  

Output:

Bike Model: Royal Enfield

This is an advanced topic of PHP, which we will discuss later in detail.

PHP Resource

Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references to external PHP resources. For example – a database call. It is an external resource.

This is an advanced topic of PHP, so we will discuss it later in detail with examples.

PHP Null

Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as it is case sensitive.

The special type of data type NULL defined a variable with no value.

Example:

<?php   
    $nl = NULL;  
    echo $nl;   //it will not give any output  
?>

Output:

JavaScript Array

JavaScript Array is also like a data type that is used to store one or more than one value of a similar type together. It’s like a container which is used to store values in a single variable. We can use an array to store values of string type, or integer type, or an object or any other valid data type in JavaScript. But the type of all the values stored in an array should be the same.

An array in JavaScript is “not” provided contiguous memory locations to store its values. In JavaScript, we do not have to provide the length of the array while declaring an array, yes, we can simply declare an empty array and then add as many elements in it as we want. Arrays are list-like objects which have many built-in functions defined in its prototype for accessing elements, adding elements, array traversal, etc.

JavaScript does not have a specific array datatype for defining arrays. But, there is a predefined Array object and its methods to work with arrays. Arrays also have properties in JavaScript like length which is not a function but a property.

We can create JavaScript array either by using the new keyword or using the array literal notation i.e. [](square brackets).

JavaScript Array using Literal Notation

We can also create an array using array literal notation. An Array literal notation is a comma-separated list of items enclosed within square brackets.

Syntax to create an Array using Array Literal notation:

Creating an array using the array literal notation is simple than creating array using new keyword.

var arr = [ ];  // empty array

var fruits = ["mango","apple","orange","guava"];  // Array having elements

Let’s take an example to see how we can create a simple array using array literal notation.

<script>
    var arr = ["Yamaha","Honda","KTM"];
    console.log(arr.length)
</script>

3

As you can see in the above code example, we have used the length property of array to print the count of elements present in it. The length property of array is used very frequently while traversing an array.

JavaScript Array using new

  • We create an empty Array whenever we don’t know the exact number of elements to be inserted in the Array.
  • An empty array can be created using the new keyword.
  • We can then use the push() method to add elements at the end of the array, or use the unshift() method to add to the front of the array. There are many different ways of adding data to an array in JavaScript.

Syntax to create an Array:

Following is the syntax for creating an array using the new keyword.

let arr = new Array(); // empty array

let arr = new Array(10); // array of 10 elements size

let arr = new Array("Java","C","C++"); // array with 3 values

Now, let’s take a simple example to see this in action.

<script>
    let fruits = new Array("mango","apple","banana","guava");
    console.log(fruits);
</script>

[“mango”, “apple”, “banana”, “guava”]

JavaScript Array: Accessing Elements

We can access array elements by using index value of the stored data elements. Ever data element stored in an array is stored at an index. The array index starts from 0 and goes upto the value (Array.length – 1). So, the first element will be stored at index value 0 and the last element is stored at index value (Array.length – 1)

let fruits = ["mango","apple","orange","guava"];   // Array having elements

console.log(fruits[0]);   // Accessing element
console.log(fruits[1]);   // Accessing element
console.log(fruits[fruits.length-1]);   // Accessing element

mango apple guava

JavaScript Array: Traversal or Iteration

Since an array is an object, we can iterate over its elements using for loop. We have already covered JavaScript for Loop in one of our previous tutorials. We have used the for-of loop in the below example, but you can use the simple for loop as well.

let fruits = ["mango", "apple", "orange", "guava"];  // Array having elements
for(f of fruits)    // Traversing array 
	document.wrtie(f + " ");

mango apple orange guava

For the beginners, let’s see one example of array traversal using the basic for loop as well,

let fruits = ["mango", "apple", "orange", "guava"];  // Array having elements
// Traversing array 
for(let i=0; i < fruits.length; i++)    
{
	document.write(fruits[i] + " ");
}

Array forEach Function:

To loop over an array, we can also use the Array function forEach which is defined in its prototype definition. Let’s see an example for that,

let bikes = ["Honda", "KTM", "Yamaha"];
// using forEach function
bikes.forEach(function(item, index, array) {
    document.write(item, index);
})

Honda 0 KTM 1 Yamaha 2

JavaScript Array Object Methods

Below we have specified some of the popular methods that are used for performing various operations on array in JavaScript like adding a new element, removing an element, searching an index of an element, etc.

1. concat(): Joins two or more arrays and returns the joined array.

2. join(): Join all the elements of an array into a string.

3. pop(): Removes the last element of an array and returns that element.

4. reverse(): Reverse the order of a list of elements in an array.

5. shift(): Removes the first element of an array and returns that element.

6. slice(): Selects a part of an array and return that part as a new array.

7. sort(): Sort the elements of an array.

8. push(): Adds new element as the last element and returns the length of the new array.

9. unshift(): Adds new elements to the array and returns the new length.

10. splice(): Adds or removes elements of an array.

11. fill(): Fill the elements into an array with static values.

12. every(): It determines whether all elements of an array are satisfying the provided function conditions.

13. isArray(): To check if the value is an array or not.

14. indexOf(): To find the index of an element in the array.

15. forEach(): To loop over the array values.

Apart from these, there are many more Array prototype functions available. Let’s see a few of these functions in action:

1. Add an element as the Last Element of Array

let bikes = ["Honda", "KTM", "Yamaha"];
bikes.push("Triumph");
console.log(bikes);

[“Honda”, “KTM”, “Yamaha”,”Triumph”]

2. Add an element as the First Element of Array

let bikes = ["Honda", "KTM", "Yamaha"];
bikes.unshift("Triumph");
console.log(bikes);

[“Triumph”,”Honda”, “KTM”, “Yamaha”]

3. Find the index of an Array Element

let bikes = ["Honda", "KTM", "Yamaha"];
// use console.log or document.write for output
console.log(bikes.indexOf("KTM");

1

4. Reverse the Array

let bikes = ["Honda", "KTM", "Yamaha"];
console.log(bikes.reverse());

[“Yamaha”,”KTM”,”Honda”]

Similarly, you can try various functions in the live terminal given below.

JavaScript Array Live Example:

Now let’s see some JavaScript Array code live in action. In the terminal below, we have declared an array, and have implemented a loop to traverse the array. Now, please try using the above mentioned functions to see how they work. Practicing code will help you grasp the concepts faster.

Array Live Example

Array Example:

var bikes = new Array(“Yamaha”,”KTM”,”Triumph”,”Honda”); for(i=0;i<bikes.length;i++) { document.write("
“+bikes[i]); } document.write(“

Reverse order: ” + bikes.reverse() + “

“);

In this topic, we explained JavaScript Array and its functions along with various operations that are commonly performed on Array. We have covered multiple code examples to help you understand the concept.

JavaScript Data Types

JavaScript Data types are used to identify the type of data that is stored inside a variable during the script execution. As we have already specified about the Dynamic Typed JavaScript feature so we do not have to specify the data type of the variable while declaring it.

So JavaScript data types are basically for identification purposes to know what is being stored in the variable, when it’s stored, not before that.

Dynamically typed language is a language that infers data types at runtime. It allows storing different types of values to a variable during programming.

Below we have a basic example, where we have defined a variable with a numeric value and then updated it to store a string value. So JavaScript allows this.

var x = 5;    // x is a number
x = "studytonight";    // x is string here.

JavaScript broadly supports three types of Data types, they are:

  • Primitive Type
  • Reference Type
  • Special Data Type

Let’s cover each one of this one by one while seeing which category has all data types.

JavaScript Primitive Data Type

JavaScript Primitive data types can be classified further into the following types:

  1. String Data Type
  2. Boolean Data Type
  3. Number Data Type

These are the most common data types, used for storing sequences of characters, true/false and numeric values respectively. Let’s cover them one by one with examples.

1. JavaScript String Data type

Whenever we write a character or sequence of characters inside single or double quotes then it becomes String. For example “StudyTonight“.

We can use both single or double-quotes to create string type values.

var str = "Ferari F60";  // string using double quotes

var str1 = 'Volvo S60';  // string using single quotes.

To have a single quote as part of the string we should use the double quote to enclose the string value and vice versa. And if you want to include a single quote in the string which is defined by enclosing it within single quotes only, in that case, we must use a backslash \ to escape the single quote, and similarly, we can escape the double quote too in a string value.

Let’s see an example of this:

var str1 = "Ferari's F60";    // Output: Ferari's F60

var str2 = 'Volvo "S60"';   // Output: Volvo "S60"

var str3 = 'Ferari\'s F60';    // Output: Ferari's F60

We have covered JavaScript String in details and also covered various String methods in JavaScript.

2. JavaScript Boolean Data type

JavaScript Boolean Data type is used in conditional based programming. It can have two values, either true or false.

var isOn = true;  // bulb is on

var isOn = false;  // bulb is off

We get Boolean values while comparing two numbers, for example:

doument.write(4 < 2)  // false
doument.write(4 > 2)  // true

We will see this in the JavaScript If else Flow Control tutorial.

3. JavaScript Number Data type

JavaScript Number Data type can be with or without decimal points and can have negative and positive values.

var x = 45; // Number without decimal point

var y = 45.90; // Number with decimal point - floating point

var z = -10; // Number with negative value

The JavaScript Number data type also represents some special values like Infinity-Infinity and Nan. When a positive number is divided by zero (it’s a popular case of runtime error), in JavaScript it’s represented as Infinity. Similarly, when a negative number is divided by zero we will get -Infinity.

var a = 100;
var b = -100;
var c = 0;

alert(a/c);  // Infinity 
alert(b/c);  // -Infinity

And Nan means Not a number, if we try to perform any operation between a numeric value and a non-numeric value like a string we will get this as output.

var a = "Studytonight";
var b = 7;

alert(a/b);    // Nan

JavaScript Composite Data types

These data types can hold collections of values and more complex entities. It is further divided into Object, Array and Function.

  1. Object data type
  2. Array data type
  3. Function data type

1. JavaScript Object Data Type

In JavaScript, an object data type is used to store the collection of data. Object’s properties are written as key:value pairs, which are separated by commas and enclosed within curly braces {}.

The key (name) must always be a string, but the value can be of any data type. This is pretty similar to a map data structure in many programming languages which also stores key-value pairs like this.

var name = { };   // It will create an empty object.

var emp = {firstname="ram", lastname="singh", salary=20000};

2. JavaScript Array Type

JavaScript Array data type is written inside a pair of square brackets [] and is used to store multiple values of the same datatype be it strings, numbers etc. The items in a JavaScript array are also written in a comma-separated manner.

Each element in the array gets a numeric position, known as its index. The array index starts from 0 or we can say that array indexes are zero-based, so that the first array element is arr[0] and not arr[1].

Let’s take an example for JavaScript array:

// Creating an Array
var cars = ["Ferrari", "Volvo", "BMW", "Maseratti"];

3. JavaScript Function Type

You must be thinking, how a function can be a datatype. But in JavaScript functions act as a data type which can be assigned to a variable. JavaScript Function is nothing but a set of statement inside a code block which is used to perform a specific operation and this datatype is of callable in nature. So, you can call it anywhere in the program whenever needed.

Since functions are objects, so it is possible to assign them to a variable.

Functions can be stored in variables, objects, and arrays. Functions can be passed as arguments to other functions too and can be returned from other functions as well.

var welcome = function() {
                  return "Welcome to StudyTonight!";
              }

JavaScript Special Data types

JavaScript also has some special data types, although seeing function called as a data type would have already been special for you. But there are two more.

  1. Undefined Data type
  2. Null Data type

Let’s cover each of them one by one.

1. JavaScript Undefined Data Type

When a variable is just declared and is not assigned any value, it has undefined as its value. Yes, undefined is a valid data type in JavaScript and it can have only one value which is undefined.

We can even use this value while doing some comparison. Let’s take an example:

var a;   // Undefined

alert(a == undefined);   // returns true

2. JavaScript Null Data Type

JavaScript Null data type is used to represent no value. It is not similar to undefined, and neither it is similar to empty value or zero value. The Null datatype means, the variable has been defined but it contains no value.

The Null data type can have only one value, which is null. Let’s take an example for this:

var a = null;

alert(a);    // Output will be null

JavaScript typeOf Operator

The typeOf operator in JavaScript can be used to check the data type of any variable. Although its an operator but we are mentioning it here, because it’s oftenly used to check the data type of any variable.

Let’s take a few examples to see how this works:

// Function datatype
var welcome = function() {
                  return "Welcome to StudyTonight!";
              }

typeOf welcome;    // function

var a = null;

typeOf a;   // null

// Array datatype
var cars = ["Ferrari", "Volvo", "BMW", "Maseratti"];

typeOf cars;    // array

You can try this with other data types too.

JavaScript Literals and Keywords

JavaScript Literals are the fixed value that cannot be changed, you do not need to specify any type of keyword to write literals. Literals are often used to initialize variables in programming, names of variables are string literals.

A JavaScript Literal can be a numeric, string, floating-point value, a boolean value or even an object. In simple words, any value is literal, if you write a string “Studytonight” is a literal, any number like 7007 is a literal, etc.

JavaScript supports various types of literals which are listed below:

  • Numeric Literal
  • Floating-Point Literal
  • Boolean Literal
  • String Literal
  • Array Literal
  • Regular Expression Literal
  • Object Literal

JavaScript Numeric Literal

  • It can be expressed in the decimal(base 10), hexadecimal(base 16) or octal(base 8) format.
  • Decimal numeric literals consist of a sequence of digits (0-9) without a leading 0(zero).
  • Hexadecimal numeric literals include digits(0-9), letters (a-f) or (A-F).
  • Octal numeric literals include digits (0-7). A leading 0(zero) in a numeric literal indicates octal format.

JavaScript Numeric Literals Example

120 // decimal literal

021434 // octal literal

0x4567 // hexadecimal literal

JavaScript Floating-Point Literal

  • It contains a decimal point(.)
  • A fraction is a floating-point literal
  • It may contain an Exponent.

JavaScript Floating-Point Literal Example

6.99689 // floating-point literal

-167.39894 // negative floating-point literal

JavaScript Boolean Literal

Boolean literal supports two values only either true or false.

JavaScript Boolean Literal Example

true // Boolean literal

false // Boolean literal

JavaScript String Literal

A string literal is a combination of zero or more characters enclosed within a single(') or double quotation marks (").

JavaScript String Literal Example

"Study" // String literal

'tonight' // String literal 

String literals can have some special characters too which are tabled below.

String Special Characters:

CharacterDescription
\bIt represents a backspace.
\fIt represents a Form Feed.
\nIt represents a new line.
\rIt represents a carriage return.
\tIt represents a tab.
\vIt represents a vertical tab.
\'It represents an apostrophe or single quote.
\"It represents a double quote.
\\It represents a backslash character.
\uXXXXIt represents a Unicode character specified by a four-digit hexadecimal number.

JavaScript Array Literal

  • An array literal is a list of zero or more expressions representing array elements that are enclosed in a square bracket([]).
  • Whenever you create an array using an array literal, it is initialized with the elements specified in the square bracket.

JavaScript Array Literal Example

var emp = ["aman","anu","charita"];  // Array literal

JavaScript Regular Expression Literal

Regular Expression is a pattern, used to match a character or string in some text. It is created by enclosing the regular expression string between forward slashes.

JavaScript Regular Expression Example

var myregexp = /ab+c/; // Regular Expression literal

var myregexp = new RegExp("abc"); // Regular Expression literal

JavaScript Object Literal

It is a collection of key-value pairs enclosed in curly braces({}). The key-value pair is separated by a comma.

JavaScript Object Literal Example

var games = {cricket :11, chess :2, carom: 4}  // Object literal

JavaScript Keywords

Every programming language has its own keywords and reserved words. Every keyword is created to perform a specific task and the compiler or interpreter already knows about the built-in keywords and reserved words. JavaScript supports a rich set of keywords that are listed in the below table.

KeywordDescription
forThe for keyword is used to create a for-loop.
do/whileThe do and while both keywords are used to create loops in JavaScript.
if/elseThe if and else keywords are used to create conditional statements.
continueThe continue keyword is used to resume the loop.
breakIt is used to break the loop.
functionThe function keyword is used to declare a function.
debuggerIt is used to call the debugger function
classThe class keyword is used to declare the class.
returnReturn keyword is used to return function from the function.
floatIt is used to declare float type variable.
intIt is used to declare int type variable.
privateIt is an access modifier.
publicPublic is an access modifier that gives the class public access.
varVar is used to declare a variable.
switchThe switch creates various statement blocks and executes only on block depending on the condition or the case.
try/catchIt creates a block for error handling of the statements.

NOTE: While defining name of any function or variable, you should not use any keyword or reserved words.

In this tutorial, we learned about JavaScript literals, different types of literals along with examples. We also covered the JavaScript keywords and reserved words.