One of the most popular programming languages nowadays is JavaScript. Every modern web browser already has it preinstalled and it can be used to create front-end and back-end apps using a variety of frameworks and libraries. Scripts are what this language refers to as programs. They can be included directly in the HTML of a web page and executed immediately when the page loads. Plain text is used to deliver and run scripts. They don’t require any further setup or compilation to function. In this tutorial, we will learn about JavaScript’s various data types and different types of functions.
JavaScript offers many data types to store various sorts of values. In JavaScript, there are two main kinds of data types.
Primitive data type
Non-primitive (reference) data type
JavaScript supports eight basic data types.
String
- It helps store textual data.
Example:“This is a string”;
Number
- It stores a decimal or non-decimal number.
Example:3, 3.14
BigInt
- It stores numbers greater than 253-1 which are not permissible in number data type. You add n to the end of the number literal to create a BigInt.
Example:9.439437534957n, 1n
Boolean
- It stores either true or false.
Example:true, false
Null
- It stores a null value.
Example:const data = null;
Undefined
- It represents a variable that is not assigned.
Example:const data;
Symbol
- A symbol is an unchangeable, singular primal value (non-primitive data type).
Example:const data = Symbol();
Object
- It is a collection of data consisting of key-value pairs (non-primitive data type).
Example:const student = {name: ‘John’, age: 15}
A string is a data type that helps us store an arrangement of characters. It has various methods that could be used to manipulate and change its content.
Example:const data = "This is a string";
There are three ways in which we can define a string:
Using single quotes:const hello = 'Hello World';
Using double quotes: Similar to using single quotes and can be used interchangeably:const hello = "Hello World"
Using backticks: Backticks are typically used when a string has to contain variables or expressions. Wrapping variables or expressions as shown below does this.
1 2 3
const first_name = "John"; const last_name = "Cena"; const name = `My name is {first_name} {last_name}`;
We can concatenate strings with the help of the “+” operator:
1 2 3 4 5 6
const name = 'Tina'; const data = 'Hello ' + name; console.log(data); // Result in the console // Hello Tina
Use the array-like []
syntax and the zero-based index to retrieve the characters in a string. The example below returns the string’s first character with the index zero.
1
2
const data = "Tina";
console.log(data[0]); //T
To find the length of the string we can use the “length” property.
1 2
const str = "I am a student" console.log(str.length); //14
Null represents an empty or unknown value to a variable. It can be used to reassign it to some other value in the future.const val = null;
A null
object is one that has a valid value, no attributes, cannot be changed, and only one instance of it is present in the system at any one moment.
With objects we can store a collection of data inside one entity. It is a non-primitive data type that consists of unordered key-value pairs. Each object may include any mix of these fundamental data types and reference data types, as objects are more complicated. A reference or a pointer to the reference value is supplied to variables. The object’s storage location in memory is indicated by the reference or pointer in question. The values are not really kept in the variables.
1
2
3
4
5
const school = {
name: 'xyz school',
address: '123 street',
grade: 10
}
We can use dot notation to access the value of the key,console.log(school.name) // xyz school
or we can use the square bracket notation.console.log(school["name"]) // xyz school
A property’s key may be a string. A property’s value can be anything, including a text, a number, an array, or even a function.
JavaScript can also contain objects inside an object. For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const employee = {
name: 'Sam',
age: 25,
work: {
designation: 'developer',
department: 'analytics team'
}
}
// accessing property of employee object
console.log(employee.work); // {designation: 'developer', department: 'analytics team'}
// accessing property of work object
console.log(employee.work.department); // analytics team
In contrast to being defined for the object itself, which is known as the object’s own property, inherited properties are those that have been passed down from the object’s prototype.
All objects in JavaScript are capable of inheriting traits and actions from other objects. Prototype is the name of the object from which we are inheriting. The prototype object contains all the inherited properties of an object, and we may read the inherited properties of an object by invoking proto, which takes the form objectName. The function hasOwnProperty method may be used to determine whether a property is an object’s own property.
1
2
3
4
5
6
const student = {
name: 'Tina',
age: 10,
grade: 5
}
console.log(student.hasOwnProperty('age')) // true
Javascript is a prototype-based object-oriented programming language and not a class-based object-oriented language.
Each object in object-oriented programming has the ability to receive messages, handle data, and communicate with other objects. It is not necessary for a language to include characteristics like encapsulation, modularity, polymorphism, and inheritance in order for it to be object-oriented. Classed-based programming languages are another name for object-oriented programming languages that utilize classes, while using classes is not a must to be object-oriented.
Prototypes are used by JavaScript to specify object attributes such as methods and inheritance.
A JavaScript function is a section of code created to carry out a certain purpose. The function keyword is used to define a JavaScript function, which is then followed by the function’s name and parenthesis ()
.
Function names may also include underscores, dollar signs, and other characters. Names of parameters may be included in parenthesis and separated by commas: (parameter1, parameter2, …). Curly brackets enclose the code that the function will execute: {}
Example: A function to multiply two numbers:
1 2 3
function multiply(a1, a2) { return a1 * a2; }
An object’s property that has a function declaration is known as a JavaScript method. Methods are represented as object attributes and are functions.
1
2
3
4
5
6
const student = {
name: 'Tina',
greet: function () {
console.log('hello');
}
}
The object student consists of the method greet.
We can access the method using:student.greet();
JavaScript has various built-in methods as well.
If we want to access the properties of an object inside a method we have to use the “this” keyword.
1
2
3
4
5
6
7
8
const student = {
name: 'Tina',
age: 15,
greet: function () {
let last_name = 'Smith';
console.log('The name is' + ' ' + this.name + ' ' + last_name);
}
};
We can pass objects as parameters to functions in JavaScript. A function is also a type of object, hence we can pass a function as a parameter to other functions.
JavaScript executes code in a top-down, sequential fashion. However, there are some situations when code executes (or must execute) both post-event and not sequentially. We refer to this as asynchronous programming. Callbacks ensure that a function will execute immediately following the completion of a job rather than before it. It protects us from errors and issues while assisting us in writing asynchronous JavaScript code. A callback function is created by passing it as a parameter to another function and then calling it back immediately after an event or action has been performed.
Example:
1
2
3
function hello(callback) {
callback();
}
Here the callback function is passed as an argument to the hello function.
1
2
3
4
5
6
7
8
9
10
11
12
13
function hello1() {
console.log("This is first");
}
function hello2() {
console.log("This is second");
}
hello1();
hello2();
// Result in the console
// This is first
// This is second
Now we will use the setTimeout function on the hello1 function while calling it. setTimeout calls the function after a certain number of specified milliseconds.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function hello1() {
console.log("This is first");
}
function hello2() {
console.log("This is second");
}
setTimeout(hello1, 3000);
hello2();
//Result in console
// This is second
// This is first (after 3000 milliseconds or 3 seconds)
As we see above when we call the setTimeout function, the hello1()
function doesn’t get executed until 3000 milliseconds are completed. Therefore, setTimeout()
is an example of a callback function.
The second function in the example above doesn’t wait for the first function to finish. However, you may utilize a callback function to delay the execution of the subsequent statement until the outcome of the preceding function call. For instance,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function hello1(myFunction) {
console.log("This is first");
// this is executed only after hello1() is executed
myFunction();
}
function hello2() {
console.log("This is second");
}
setTimeout(hello1, 2000, hello2);
//Console output
// This is first
// This is second
The code in the aforementioned program is running synchronously. The hello1()
function receives the hello2()
function as an input. The hello1()
function is only called by the setTimeout()
method after two seconds. The hello2()
function does, however, hold off until the hello1()
function has finished running.