JavaScript is one of the most important programming languages ever made, without it the World Wide Web that we know today would not exist. You would think that a programming language invented in 1995 would become outdated, but no, JavaScript is still as powerful as it has ever been. In fact, it’s so powerful that it is used by 98% of websites.
So anytime you see a webpage that is not a boring static webpage and has interactive features, most likely JavaScript is used in this webpage. But web development is not the only thing that JavaScript is used for, it’s also used in game development, building applications, and a lot more.
In JavaScript, the functions that are called first are executed first.
Code Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
function firstFunction() {
console.log("1")
}
function secondFunction() {
console.log("2")
}
secondFunction();
firstFunction();
// Output:
// 2
// 1
So even though firstFunction is defined before the secondFunction, the secondFunction is executed before the firstFunction because it’s called before it.
So what do we do if we want to execute functions in a certain order? Or if we want a function to wait for another function to finish before it starts executing? We use callbacks. A callback is when you pass a function as an argument to another function, so it allows functions to call other functions. The calling function is not executed until the function it has called is finished executing (in more formal terms its callback function).
Code Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function add(num1, num2) {
return num1 + num2;
}
function subtract(num1, num2) {
return num1 - num2;
}
function multiply(num1, num2) {
return num1 * num2;
}
function divide(num1, num2) {
return num1 / num2;
}
function calculator(operation, num1, num2) {
var result = operation(num1, num2);
console.log(result);
}
calculator(add, 1, 2);
calculator(subtract, 1, 2);
calculator(multiply, 1, 2);
calculator(divide, 1, 2);
// Output:
// 3
// -1
// 2
// 0.5
In this example, we need the mathematical operation to be evaluated first then the calculator to display the result.
This is where callbacks become very useful.
In this example, the operation function is passed as an argument to the calculator function.Then the calculator function calls the operation function and waits until it finishes executing. Then the calculator function displays the result to the console.
Note: Remember not to use parentheses when you pass a function as an argument.
Right: calculator(add, 3,4);
Wrong: calculator(subtract(), 3,1);
In Javascript, an object is a data type, it contains properties and methods. To better understand what an object means, compare it with a real-life object like a car. A car has properties like color, model, price, etc., and it has methods like drive, brake, etc. In short, in programming, we use objects to express real-life objects.
The function property inside an object is called a method, not a function, and there are some differences between them. Here are some:
A function exists on its own, while a method is a function that is associated with an object property.
A function is called by its name and is invoked using the () operator but when we call a method we need to use its object name, and we call it using dot notation or square-bracket notation.
To understand whether JavaScript is object-oriented we first need to understand the concept of Object-Oriented Programming (OOP). Object-oriented programming is a programming paradigm that organizes software design around objects and classes, rather than functions and logic.
OOP has four pillars:
Abstraction is hiding implementation details inside something like a prototype or a function to make code reusable and easy to maintain. For example, when you use a library and call a function in that library you don’t know (or need to know) how it’s implemented but you know what the function does and that’s enough.
Another simple example is:
If you have a coffee machine you could make coffee in two ways:
With abstraction
The machine will have a button that says “make coffee”.
Without Abstraction
The machine will have a button that says ” boil water” and another that says “add sugar to the cup”, etc.
Encapsulation is enclosing something in a capsule. In programming, it is the act of encapsulating methods and data into one unit like a class. This is done to make some parts of the code private and not accessible to everyone.
In inheritance, the subclass (child class) inherits the superclass’s (parent class) properties and methods. Also, inheritance is used for code reusability. For example, we have a superclass called animal and many subclasses like bird, dog, cat, etc. and all of these classes need to have the makeSound function. Instead of retyping the same code in every animal class, we create an animal class with properties and methods, then each subclass inherits from the superclass.
Polymorphism is a Greek word meaning many forms. So when we say that something is polymorphic, we mean that it has many shapes and forms. In programming, polymorphism is the ability of an object, function, or variable to have many forms, where ‘form’ means behavior or type.
For example, if we have a superclass with many subclasses, the method in the superclass will be inherited by all subclasses, but each class will implement this method differently.
A practical example is if there is a superclass named animal which has the subclasses dog, cat, and bird, and that animal class has a function named makeSound, which is inherited by all its subclasses. Using polymorphism, each subclass may implement makeSound differently. So in dog class, the function prints ‘bark’, while in cat class it prints ‘meow’.
So now that we understand the concept of OOP, is JavaScript object-oriented?
Yes, it is object-oriented. JavaScript is excellent in programming OOP applications and is heavily object-based, however it’s not class-based, which means that it does not contain classes but it contains objects. Since JavaScript does not contain any classes there are some differences between the classical OOP model and OOP in JavaScript.
JavaScript is not a class-based programming language, it’s prototype-based, which means that it uses functions to construct classes. Objects in JavaScript can be created using two methods:
Code Example:
1
2
3
4
var obj = {
a1: 1;
a2: 2;
}
Code Example:
1
2
3
4
5
function person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
var obj1 = person(”first”, ”last”);
In OOP, classes are blueprints that are used to create objects but because there are no classes in JavaScript we use a constructor function that contains the properties and methods then we reuse it using the prototype.
Code example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function car(model, color, price) {
this.model = model,
this.color = color,
this.price = price
};
car.prototype.getPrice = function () {
console.log('The price of the car is ' + this.price);
}
let car1 = new car('Tesla', 'red’, 17272);
console.log(car1.model); console.log(car1.getPrice());
// Output:
// Tesla
// The price of the car is 17272
Sometimes encapsulation is referred to as information hiding, and most OOP languages contain access modifiers (public, protected, private) to restrict the scope of the variable, but there are no such modifiers in JavaScript. However, there are some ways that we can limit the scope of variables.
Code Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function student(fname, lname) {
let first_name = fname;
let last_name = lname;
let getName_noAccess = function () {
return `First name: ‘+ firstname + ’ Last
name: ‘ +lastname;
}
this.getName_access = function(){
return `
First name: ‘+firstname + ’Last
name: ‘+lastname;
}
}
let student1 = new student('Tom’ , ‘Wood’);
console.log(student1.first_name); console.log(student1.getName_noAccess); console.log(student1.getName_access());
// Output:
// undefined
// undefined
// First Name: Tom Last Name: Wood
In this example, when we try to access student1.first_name and student1.getName_noAccess it returns undefined. On the other hand, when we try to access student1.getName_access(), it doesn’t return undefined. This is because when we define a property or a method using the keyword let, the property or method becomes local to the constructor function (not global).
In the classical OOP model classes inherit properties and methods from other classes, but since there are no classes in JavaScript, objects inherit properties and methods from other objects. This process is called prototype inheritance.
To understand null, first we need to learn about data types in JavaScript. JavaScript has two types of data, primitive and non-primitive.
Primitive data types:
Primitive data types are the most basic data types in the programming language, they have no properties and no methods and they only contain a single value.
Primitive data types are immutable, which means that we are unable to change their values once the variables are assigned to a value. If we try to change the value of variable x the original value will not change, instead, a new variable x with the new value will be created in another memory address.
When we assign a variable to another variable, the two variables will have the same value but different addresses in memory.
Objects are the non-primitive data types in JavaScript. An object holds the address to its value in memory. When we assign an object to another object, we are assigning the first object’s address in memory to the second object, not its value.
Code example:
1
2
3
4
var obj1 = {
a: 4;
}
var obj2 = obj1;
Now, obj1 and obj2 have the same memory address.
So, what is null in JavaScript?
Null is one of the primitive data types in JavaScript. Null is when an object points to nothing and it has no value intentionally.
Code example:var name = null;
Features of null:
Null is falsy. A falsy value in JavaScript is a value that JavaScript will change into false in conditional statements. Falsy values in JavaScript are: false, 0, empty string(‘’), NaN, undefined, and null.
When we assign null to an object, its value becomes null but its type is still object, not null. This is a JavaScript bug that may never be fixed.
Like null, undefined is also a primitive data type. When a variable is created but not initialized, its value becomes undefined. In other words, undefined is the unintentional absence of value while null is the intentional absence of value. Undefined and null have the same value but they have different types. Null’s type is object while undefined’s type is undefined.
Code Example:
1 2 3 4
var x = null; var y = undefined; console.log(x === y); console.log(x == y);
In this code, the first condition’s value is false while the second condition’s value is true because === compares equality of value and type while == compares equality of value only.
In JavaScript, string is an object that consists of an array of characters. It’s basically used to represent text in JavaScript. We can create a string in two ways:
By using a string literal to create a primitive variable.
Code Example:var string1= “This is a string primitive”;
We can create it using double quotes or single quotes
By using a string constructor (using the new keyword) to create an object.
Code Example:var string2 = new String("This is a string object");
Since strings are objects they have many methods. For example, the indexOf()
method returns the index of a certain character, the length() method returns the length of the string, and a lot more.
Special characters are encoded using escape sequences.
\: backslash
\n: new line
\’: apostrophe
\”: double quotes
If you break a string across multiple lines it will give you an error.
Code example:
1 2 3
let string1 = “this is a very long sentence that cannot be written one line”;
Well, you can always write the string on one line, right?
Code example:
1
let string1 = “this is a very very very very long sentence that cannot be written on one line”;
When you have a really long string, your line will go on endlessly and your code will be messy and hard to read, so in that case, we use concatenation. Concatenation is using the + symbol to concatenate different strings together to form one string.
Code example:
1 2 3
let string1 = “this is a very long sentence” + ”that cannot be written” + ”one line”;