JavaScript is a widely used programming language among techies, in part because it is relatively simple to learn and because of its well-known frameworks, which are important in the development of various apps and software. It is the preferred language for writing front-end and back-end internet applications since it is the web’s primary programming language.
To add interactivity, behavior, and other complicated features to components on a website or web page exactly as intended, it is essential to have a firm grasp of JavaScript. This article will describe some of the essential JavaScript aspects, as having a solid understanding of how these concepts work will make anyone a better programmer.
A callback function is one of the superpowers of JavaScript. It is the way JavaScript passes a function into another function as an argument. The callback function is called in the outer function to execute an action.
Arguments in JavaScript are values that are passed to the parameters of a function. They are accessible only in the function they are passed into when that function is called. Think of parameters as variables that are used to hold values in a function.
For example: showing a pop-up message welcoming a user after the user inputs a username.
1
2
3
4
5
6
7
8
9
10
11
12
13
function greetings(username) {
alert('Welcome ' + username);
}
//the function declaration above is to be passed into the function below thereby making it a callback function.
function saveUserName(callback) {
var name = prompt('Please enter your username.');
callback(username);
}
//the above function states the callback function as a parameter
saveUserName(greetings);
//the greetings function (the callback function), is initially declared, then invoked by passing it as an argument into another function.
The above callback function is executed immediately and shows a pop-up with the welcome and username message.
JavaScript is known for its asynchronous programming, also known as code blocks, that run in the background and do not stop other functions or programs from running until they are completed, which is where callback functions find their use.
The main importance of a callback function is to execute a code in response to an event in a program. The event can be a simple answer to an input prompt or just a mouse click. With callback functions, a program can be written to execute a particular action in response to an event without stopping the whole application. A callback function will not run unless it is triggered by an event.
Methods in JavaScript are closely linked to JavaScript objects and allow them to carry out an action. A method in JavaScript is any property of an object that has a function as its value.
Typically, methods are used to define the behavior of objects in JavaScript.
Objects in JavaScript are data types that hold a collection of data in key/value pairs. This key/value pair is referred to as a property.
For example: to create an object that has a property in JavaScript, the key/value pair is used within curly braces.
1
2
3
4
5
6
let student = {
firstName: 'Jimmy',
lastName: 'Carter',
age: 21
};
//the `student` object has three properties `firstName`, `lastName` and `age` with the respective values ` 'Jimmy'`, ` 'Carter'`, and `21`.
Note: The value of a property could be a string, number, an array, or even a function. When the value is a function it is regarded as the method of that object.
For example: to create a method of an object, a function is created as a property value.
1
2
3
4
5
6
7
8
9
10
11
let student = {
firstName: 'Jimmy',
lastName: 'Carter',
age: 14,
greeting: function () {
console.log(‘Good day my teachers!’)
}
};
//the `greeting` property which takes the function value is a method of this object.
student.greeting();
//this method prints out ‘Good day my teachers’ to the console.
When an object has many properties a comma is used to separate them.
As JavaScript is an object-oriented programming language, methods will be encountered and used frequently. While methods can be created when needed, JavaScript comes with a number of in-built methods, some of which include:
for…of iterator()
- It loops through the items of an array and works like the for-loop.
For example:
1 2 3 4 5
const bestFruit = [‘Mango’, ‘Cashew’, ‘Pineapple’, ‘Guava’]; for (const item of bestFruit) { console.log(item) } //prints `’Mango’, ‘Cashew’, ‘Pineapple’, and ‘Guava’` to the console.
includes()
- It is used to check if a particular string exists in a collection of values.
For example:
1 2 3 4
const bestFruit = [‘Mango’, ‘Cashew’, ‘Pineapple’, ‘Guava’]; const findFruit = bestfruit.includes(‘Apples’); console.log(findFruit) //returns false since ‘Apples is not included in the Array.’
spread operator()
- It is used to display a list of items from an array instead of using a loop.
For example:
1 2 3
const bestFruit = [‘Mango’, ‘Cashew’, ‘Pineapple’, ‘Guava’]; console.log(...bestFruit); //three dots are used to represent the spread operator. The above prints out ‘Mango’, ‘Cashew’, ‘Pineapple’, and ‘Guava’ to the console.
map()
- It is used to modify the items in an array. The mapped items are returned as a new array. It is quite similar to the filter
method because they both return a new array. However, the difference is that the map
method is used to modify items in an array, while the filter
method is not used for that.
For example:
1
2
3
4
5
const age = [10, 20, 30, 40, 50];
age.map(function (item) {
return item + 5;
})’;
//returns [15, 25, 35, 45, 55]
JavaScript is, in fact, object-oriented. A programming style known as object-oriented programming (OOP) centers programs or codes on data or objects rather than logic. JavaScript is one of the most widely used object-oriented languages.
An object in JavaScript is a form of data with separate characteristics, also known as properties, and behaviors, also known as methods. JavaScript’s object literal and object constructor may both be used to build objects.
By using two curly brackets, object literals basically create objects.
For example:
1
2
3
4
5
6
7
8
9
let student = {
firstName: 'Jimmy',
lastName: 'Carter',
age: 14,
greeting: function () {
console.log(‘Good day my teachers!’)
}
};
//this simply prints out `Good day my teachers to the console`.
Contrary to what is obtainable in other programming languages, JavaScript in its strict sense is a prototype-based-object-oriented programming language - which means it does not have classes. It defines behaviors using a constructor function and then reuses it using the prototype, rather than the class-based object-oriented programming found in popular languages like Python, Java, and C++, amongst others.
Another object-oriented mechanism supported by JavaScript is classes.
Note: Classes were introduced to JavaScript in the ECMA Script 2015 as a method to create objects using a more understandable and concise syntax over the longer and more complex prototype-based inheritance.
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Student {
constructor(firstname, lastname, age) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
}
getInformation() {
return (`I am years old.`)
}
}
// Creating an object with the help of the constructor function
let student1 = new Student('Jimmy', 'Carter', 14);
let student2 = new Student('Jon', 'Pike', 22);
console.log(student1.firstname); // This prints out ‘Jimmy’ to the console
console.log(student2.lastname); // This prints out ‘Pike’ to the console
console.log(student1.getInformation()); // This prints out ‘I am 14 years old’ to the console.
A value that is intentionally left out or absent is represented by the primitive data type null in JavaScript. It is often applied to a variable when the variable’s assigned value is to be removed.
For example:
1 2
let student = null // assigns the value null to the variable console.log(student) //prints null to the console
Note: The typeof null
returns ‘object’ in JavaScript which is not supposed to be because properties cannot be assigned to it as compared to real objects. This is a JavaScript language error that causes bugs in some instances especially when trying to find real objects.
These two are frequently mistaken for one another. Nonetheless, it is important to keep in mind that while JavaScript provides undefined
to a variable that does not yet have a value, it never assigns null
.
For example:
1 2
let student // no value assigned is assigned to the variable. console.log(student) //prints undefined to the console.
Note: The data type of a variable that has not been assigned a value is undefined.
In addition, when arithmetic operations are performed on null
, its value is converted to zero. However, this is not the case for undefined.
For example:
1
2
let myAge = 21 + null;
console.log(myAge) //prints out 21 to the console.
While:
1
2
let myAge = 21 + undefined;
console.log(myAge) //prints out NaN(Not-a-Number) to the console.
Strings are primitive data types that include no characters or a collection of characters enclosed in quotes - either single or double quotes.
For example:
1
2
let myName = ‘Jimmy Carter’; // where ‘Jimmy Carter’ is a string.
let myAge = ‘22’; // where “22” is a string.
In JavaScript, strings are treated as objects which provide a lot of properties and methods available to them, making it easy to manipulate and work with strings. Some of which include;
String length
property: This property makes it possible to determine the length of a string.
For example:
1 2
let myName = ‘My name is Jimmy Carter’; console.log(myName.length) // 23 is printed to the console which is the number of all the characters and the space within the quotes.
Replace()
method: This method replaces a specific value with another within a string. It returns a new string and does not change the initial string it was used on.
For example:
1 2 3
let myName = ‘My name is Jimmy’; let myNewName = myName.replace(‘Jimmy’, ‘Carter’) console.log(myNewName) //prints out ‘My name is Carter’ to the console.
For more information on JavaScript, kindly visit Mozilla Developer Network.