In the world of developers, millions use a programming language that powers the web - JavaScript. In 1995, JavaScript was born, created by Brendan Eich, Netscape Communications Corporation programmer. It took Eich just ten days to develop the programming language of the web.
In this article, I’ve shared five questions I had when I first started learning JavaScript to build an interactive website. Hopefully, these thoroughly answered questions will help you begin your journey as a JavaScript developer.
In brief, functions are objects in JavaScript as they can have properties and methods like an object. Can we pass objects to functions as parameters? Yes.
Have a look at a simple example below:
1
2
3
function print(result) {
result();
}
The print()
function takes another function, i.e result()
, as a parameter and calls it inside.
A callback is a function passed into another function as an argument that invokes (“calls back”) later inside the function to operate.
The execution of code statements takes place sequentially. Since the higher-order function completes its execution once the callback function execution is completed, synchronous callbacks are known to be blocking. For instance,
1
2
3
4
5
6
7
8
9
10
function print(number, result) {
console.log(`{number} is {result}`);
}
function checkPosOrNeg(number, callback) {
const result = (number > 0) ? 'Positive' : 'Negative';
callback(number, result);
}
checkPosOrNeg(90, print);
// 90 is Positive
In this case, the callback function, i.e.print, executes immediately instead of waiting for asynchronous operations to complete.
In contrast, asynchronous callbacks are executed after the execution of the higher-order function. Therefore, they are also known as non-blocking since they don’t execute line by line or higher-order function doesn’t wait for callback function execution. Instead, it takes the responsibility to execute it later on a certain event. For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function LoadingTopCoder(callback, UserName) {
console.log("Loading topcoder.com!");
if (callback) {
setTimeout(() => callback(UserName), 3000)
}
console.log("Log in completed!");
}
function LogInComplete(UserName) {
if (UserName) {
console.log(UserName + " Logged In.");
}
}
LoadingTopCoder(LogInComplete, "MaryamSidd");
/*Output:
Loading topcoder.com!
Log in completed!
-> undefined
MaryamSidd Logged In.
*/
Here the output LogInComplete() is printed in the last position since callback’s asynchronous execution has delayed its execution from three seconds to the time where the execution is done.
Before learning what a method is in JavaScript, let’s look more into functions.
The function is defined using a “function” keyword followed by my function name, optional parameters, and a set of tasks is enclosed in curly braces.
However, when this block of code-function definition is stored as object properties, it is known as a method.
The syntax is following:
1
2
3
4
5
6
object = {
methodName: function () {
// Content
}
};
object.methodName() //object method can be accessed
This example accesses the fullPath() method of a WebsitePath object.
1
2
3
4
5
6
7
8
const WebsitePath = {
Website: "topcoder.com",
navigate: "/community/learn/",
fullPath: function () {
return "www." + this.Website + this.navigate;
}
};
console.log(WebsitePath.fullpath()); //www.topcoder.com/community/learn/
Typically, it describes fullPath() as a method of the WebsitePath object, and fullPath as a property.
If fullpath property is called with () , it executes as a function.
However, if fullPath property is called without () , it will return the function definition. For instance,
console.log(WebsitePath.fullpath); //[Function: fullpath]
Before answering this question, first there is a dire need to know what object-oriented programming is and its four core principles.
Object-Oriented Programming (OOP) is a style of programming that is centered around objects rather than functions. In other words, it focuses on what developers want to manipulate rather than how they want to manipulate it.
Remember: Object-oriented programming is not a language or a tool! It is a programming paradigm.
The four core concepts in object-oriented programming are:
In OOP we combine a group of related variables and functions into a unit, i.e object. The variables are referred as properties and functions as methods.
Let’s have a look at this example.
A. procedural implementation
1
2
3
4
5
6
7
let baseSalary = 4000;
let overtime = 5;
let rate = 10;
function getWage(baseSalary, overtime, rate) {
return baseSalary + (overtime * rate);
}
B. OOP Implementation
1
2
3
4
5
6
7
8
9
let employee {
let baseSalary: 4000;
let overtime: 5;
let rate: 10;
getWage: function () {
return this.baseSalary + (this.overtime * this.rate);
}
};
employee.getWage();
Any idea why OOP implementation is better than procedural?
Have a look at the function in B, it has no parameters in contrast to A, which has three parameters. The reason for this is that these parameters are modeled as properties of an object, i.e. employee. These properties and functions, i.e getWage, are highly related to the part of one object.
“The best functions are those with no parameters!” - Robert C Martin
We can hide some of the properties and methods from the outside and only show the essentials which gives us a couple of benefits.
Make the interface of the objects simpler
Reduce the impact of change
It is a mechanism that allows a programmer to eliminate redundant code. For example, HTML elements like text boxes, check boxes, and drop-down lists. All these elements have few properties in common, i.e. hidden, innerHTML, etc, and methods, i.e click(),focus(), etc. Instead of redefining all these properties and methods for every type of HTML element we can define it once in a generic object such as an HTML element and have other objects (textBox, CheckBox, Drop-down lists) inherit these properties and methods.
Poly means many and morph means form, so polymorphism simply means many forms. It is a technique that allows a programmer to get rid of long switches and case statements.
Let us step back to the HTML elements example. All the objects (textBox, CheckBox, Drop-down lists) should have the ability to be rendered on a page, right? But the way each element is rendered is different from the others. So, in a procedural way, there would be several switch and case statements. But in OOP we can implement a render method in each of these objects and the render method will behave differently depending on the type of object the viewer is referencing.
Although JavaScript is not a class-based object-oriented language, it is a prototype-based object-oriented language.
According to MDN docs:
Prototype-based programming is a style of object-oriented programming in which classes are not explicitly defined, but rather derived by adding properties and methods to an instance of another class or, less frequently, adding them to an empty object.
A prototype is an object from which the behaviors or logic are reused. JavaScript brings focus on an application’s behavior first and then groups them into classes.
There are certain features in JavaScript that make it look similar to object-oriented.
In JavaScript, you’ll explore most of the elements of an object such as functions, arrays, strings, etc.
In JavaScript objects are created in the following ways:
Object literals
1
2
3
4
5
6
7
8
9
10
11
//Defining object
let personName = {
first_name: 'Maryam',
last_name: 'Siddiqui',
//method
getter: function () {
return (`Name :
{personName.first_name} {personName.last_name}`)
}
}
console.log(person.getter()); //Name :Maryam Siddiqui
Object constructor
1
2
3
4
5
6
7
8
//using a constructor
function personName(first_name, last_name) {
this.first_name = first_name;
this.last_name = last_name;
}
//creating new instances of person object
let person1 = new personName('Maryam', 'Siddiqui');
console.log(person1.first_name); //Maryam
Object.create() -modifies the proto property
1
2
3
4
5
6
7
8
9
10
11
12
const Intro = {
Age: 20,
printIntroduction: function () {
console.log(`My name is {this.name}. Am I
{this.Age} years old.`)
}
}
// Object.create() method
const person1 = Object.create(Intro);
// "name" is a property set on "person1", but not on "Intro"
person1.name = 'Maryam';
person1.printIntroduction();
The above example portrays encapsulation. But here, it is more focused on the object’s interface instead of implementation details.
Moving to abstraction, while most OOP languages include access modifiers to limit the scope of a variable, JavaScript does not. However, there are still a few techniques to limit the scope of variables inside of a class or object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Abstraction example
function Language(name, creator) {
let lang = name;
let creatorName = creator;
let getDetails_noaccess = function () {
return (`Programming Language: {lang} is created by : {creator}`);
}
this.getDetails_access = function () {
return (`Programming Language: {lang} is created by : {creator}`);
}
}
let lang1 = new Language('JavaScript', 'Brendan Eich');
console.log(lang1.lang);
console.log(lang1.getDetails_noaccess);
console.log(lang1.getDetails_access());
//undefined
//undefined
//Programming Language: JavaScript is created by: Brendan Eich
In the example above, when we attempt to access a language object’s property and its function, it returns undefined. However, we can access this from the language object(lang1.getDetails_access()). We can limit the scope of a function by modifying how it is defined.
Classes are known to be a template of an object that are instances of the classes. As discussed before, JavaScript is a prototype-based object-oriented language as it has no classes like other object-oriented languages.
In ECMAScript 2015, JavaScript debuted the class keyword. JavaScript appears to be an OOP language as a result. However, it is merely adding syntactic sugar to the current prototyping method. In the background, it continues prototyping, while the outward body is presented like OOP.
Inheritance in JavaScript is different from other OOP languages since it inherits objects instead of classes. The purpose of it is to reuse an object’s properties and methods with other inherited objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//Inheritance example
class Vehicle {
constructor(name) {
this.name = name;
}
//method to return the string
toString() {
return (`Name of the car: {this.name}`);
}
}
the class company extends Vehicle {
constructor(name, color) {
//super keyword - refer to the immediate Vehicle's class (parent's class) instance variable.
super(name);
this.color = color;
}
toString() {
return (`{super.toString()},company color: {this.color}`);
}
}
let company1 = new company('Civic', 'Silver');
console.log(company1.toString());
//Name of the car: Civic, color: Silver
In the example, we establish a vehicle object with specific properties and methods, after which the company object inherits the vehicle object and uses all of the vehicle object’s properties and methods while also defining specific properties and methods of its own.
Lastly, there are a variety of ways in JavaScript that we can implement various sorts of polymorphism, and perhaps we may have already done it unknowingly.
Are null and undefined the same in JavaScript? The answer is NO.
Although null and undefined are among the seven primitive data types and treated as false in boolean operations in JavaScript, they are different.
According to MDN:
The value null represents the intentional absence of any object value.
Since null must be assigned, it reflects the absence of identification such as a variable pointing to no object. Whereas undefined is returned by a statement or a method when a variable hasn’t been assigned any value.
Surprisingly, typeof gives a different result, i.e. null is an object, where undefined is a type itself.
1 2 3 4
typeof null; - > 'object' typeof undefined; - > 'undefined'
even though both are primitive values. Hence even if equality is checked.
1 2
null !== undefined // true
it shows that they are different.
Therefore, null is assigned to a value to indicate that the variable doesn’t point to any object, while undefined indicates the absence of the variable itself. Most importantly, null is converted to zero (0) while performing a primitive operation.
According to MDN:
The string object is used to represent and manipulate a sequence of characters.
Using string literals that include double quotes, single quotes, or backticks, string as a primitive are created:
1 2 3
var id = "20K123"; //double quotes var id = '20K123'; //single quotes var id = \`20K123\`; //backticks
While using the String() constructor,string as an object is created:
var id = new String(
20K123);
Individual characters can be accessed in the following ways:
Treat the string as an array.
1
2
3
const id = '123';
console.log(id[1]);
`// "2"
Use the method charAt().
1
2
const id = '123';
console.log(id.charAt(0)); // "1"
You need to notice something very important here, i.e. string starts from zero, for example, console.log(id[0]) will give an output of one.
To join strings the ‘+’ -addition operator is used to create a new string.
1 2
var lang = "JavaScript"; console.log(lang + " is WebDevelopment backbone."); //JavaScript is WebDevelopment backbone.
To add the variable within the string, the syntax, i.e ****, is used with backticks. That is:
1 2
var lang = "JavaScript"; console.log(`{lang} is WebDevelopment backbone.`); //JavaScript is WebDevelopment backbone.
1 2 3
const broken_string = 'I' m a broken string '; console.log(broken_string); //SyntaxError: Unexpected identifier
Can you identify the error? If yes, that’s great.
In the middle of a single-quoted string, the attempt to use an apostrophe will end the string. Thus, the rest of the string will be read as code.
Three possible solutions to the error can be:
Use an alternative string syntax, i.e. double-quotes " "
Use an escape character \ before a special character, i.e.apostrophe.
Use backticks ``
Simply, the uppercase value is different from the lowercase value.
1 2 3
const Lower_case = 'j'; const Upper_case = 'J' console.log(Lower_case == Upper_case); // false
This means that string characters cannot be changed; however, new values can be assigned.
1
2
3
4
5
var lang = JavaScript;
lang[0] = "j";
console.log(lang); //JavaScript
lang = "javascript";
console.log(lang); //javascript
This could be done in the following ways by using:
“+” addition operator
" \ " escape operator
" \n" escape sequence : newline
Have a look!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//1 const multipleLines = "This is a string" + "that spans across" + "multiple Lines."; //2 const multipleLines = "This is a string\ that spans across\ multiple Lines"; //3 const multipleLines = "This is a string\nthat spans across\nmultiple Lines"; console.log(multipleLines); //Output /* This is a string that spans across three lines. */
You can use the built-in length property to find a string length.
1 2
const lang = 'JavaScript'; console.log(lang.length); // 10
Hopefully, this is enough knowledge of strings in JavaScript.
I believe it is easy to identify callbacks. When a defined function is passed as an argument to another function to invoke it, instead of invoking the function itself, you’ve created a callback function. In simple words, a JavaScript method is a property containing a function definition. Hopefully, any confusion you may have had has been cleared to conclude that JavaScript is a prototype-based object-oriented language.
Additionally, null is an object assigned to a variable to indicate that it points to no object. Lastly, this article enriches your knowledge regarding the string in JavaScript.
Dmitri Pavlutin Blog. 2022. Everything About Callback Functions in JavaScript. [online] Available at: https://dmitripavlutin.com/javascript-callback/#:~:text=There%20are%202%20kinds%20of%20callback%20functions%3A%20synchronous%20and%20asynchronous..
Difference between methods and functions in JavaScript. GeeksforGeeks. (2022, April 11). From https://www.geeksforgeeks.org/difference-between-methods-and-functions-in-javascript/
Introduction to object-oriented programming in JavaScript. GeeksforGeeks. (2022, July 6). From https://www.geeksforgeeks.org/introduction-object-oriented-programming-javascript/
Lo, M. (2021, February 17). Null and undefined in Javascript. Medium. From https://medium.com/weekly-webtips/null-and-undefined-in-javascript-d9bc18acdaff
Javascript string. Programiz. (n.d.). From https://www.programiz.com/javascript/string