Imagine a casual day as usual, and you suddenly get it in your head to learn JavaScript. Excellent!! What could be better than learning the most commonly used programming language according to the Stackoverflow 2022 developer survey (tenth time in a row!) and the second most popular (after Python’s recent takeover) language on Github?
In this article we’ll go through some of the common jargon used throughout one’s journey to mastering JavaScript. Whether you are completely new to the programming world or coming from a different language to JavaScript, this article is for you!
JavaScript, on paper, is a single-threaded, non-blocking, asynchronous programming language.
Woah!! That was too much in just a single line. Let’s go through each of those briefly.
In computer programming every application consists of one or more processes. These processes are entities that use system resources or interact with other applications to get their assigned task done.
These processes further consist of one or more threads. Whenever the application execution begins, it’s the thread that does the actual work. They can communicate with other threads in the same process or even threads in different processes.
So when we say JavaScript is single-threaded, it indicates that it spins up a single thread to perform all the tasks of the application as compared to having multiple threads do those tasks.
💡 Quick heads up:
If you are familiar with the Java programming language, you will know that Java, in contrast to JavaScript, is a multi-threaded programming language, meaning that we can create as many threads as required to perform the tasks.
Asynchronous and synchronous deal with how the program flow is executed.
Let’s go through a simple JavaScript code snippet.
1
2
var a = 10; // 1️⃣
console.log('Let\'s see the value of a. It is ' + a) // 2️⃣
Code breakdown
1️⃣ - We have created a variable called ‘a’ and assigned a value of ten to it.
2️⃣ - We have used an inbuilt JavaScript function to print/display some value to the console. Here, we’re trying to print the value of the variable ‘a’ that we just assigned in the previous statement.
Copy and try running the above code in an online JS editor.
You should see the resultant log printed as ‘Let’s see the value of a. It is 10’.
What happened here is pretty easily understandable. We wrote two synchronous statements, which didn’t depend on any external sources, nor did they wait for anything to get executed. We ran the program, they got executed one after another.
Now, let’s go through another code sample.
1
2
3
4
5
6
7
8
console.log('I\'m the first statement'); // 1️⃣
fetch("https://jsonplaceholder.typicode.com/users") // 2️⃣
.then(x => x.json()) // 3️⃣
.then(response => {
console.log('I\'m the second statement. Lets\' see the response.');
console.log(response)
}); // 4️⃣
console.log('I\'m the third statement'); // 5️⃣
Code breakdown
1️⃣ - We printed a simple log.
2️⃣ - We are using an inbuilt asynchronous JavaScript function called ‘fetch’. This function accepts a URL which needs to be called and gives its response.
3️⃣ - Here we have a .then() method, which is a callback method, wrapping our response as in a json format.
4️⃣ - Here again we have a .then() method, printing the response to the console.
5️⃣ - We printed a simple log.
When we run the above code we get the following output
I’m the first statement
I’m the third statement
I’m the second statement. Let’s see the response.
[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
But, alas! This is not what we would have expected looking at the code that we wrote above. We see that the third statement is printed before the second statement.
What happened here?
The fetch function we used above is an asynchronous function which does not wait for its execution and does not block the further flow. Hence, flow immediately goes to the third (5️⃣) statement. When the fetch function gets its response from API, it executes the callbacks (.then() functions) attached to it and we get the second statement printed.
This proves that JavaScript is indeed non-blocking and asynchronous in nature.
Asynchronicity in the recent versions of JavaScript is handled in three ways:
Using callbacks
Via promises
Using async/await
We’ll go through callbacks in this article. You can read this article for more information on promises.
Earlier in our second code snippet we saw how we attached .then()
callbacks to an asynchronous function to react to its response. This is the reason why we need callbacks.
Imagine we have an asynchronous statement in between a bunch of synchronous statements and consider that all the statements post the asynchronous one were dependent on the response of the asynchronous statement.
It wouldn’t have been possible to make this happen if it weren’t for callbacks. Since we have callbacks attached we can wrap our synchronous code inside them and the dependent code would execute happily.
The JavaScript event handling mechanism also relies on callbacks for their execution. Events in JavaScript are predefined actions performed by either the user or by the browser itself. Whenever the event is triggered the callback function attached to it is called.
Consider the below code snippet
1 2 3 4
const button = document.querySelector('button'); // 1️⃣ button.addEventListener('click', () => { // 2️⃣ console.log(‘Button is clicked!!!’); // 3️⃣ });
Code breakdown
1️⃣ - We have used the browser DOM API to get reference to a button.
2️⃣ - We are attaching the event listener to this button. The first parameter is the type of event, that is ‘click’. The second parameter is the callback function itself.
3️⃣ - Inside the callback function we are printing the log.
What happens when we run the code?
Nothing immediately. We just have attached the listener to the button click event. Now whenever the button is clicked, the callback is triggered and we get the log printed.
Read more about callbacks in this article.
Method is a very common term, we all must have heard it at least once in our programming journey. Methods exist in most languages, if not all, although they may be called by different names.
In Java too, these are called methods. In JavaScript they are mainly called ‘functions’ but interchangeably used with ‘methods’ as well.
The use of methods in programming languages, including JavaScript, is to wrap some code statements inside it so that this wrapped code can be used elsewhere to reduce code duplication.
A method has a name, may take one or more input parameters, may or may not modify these parameters, and may or may not return a result/response.
Consider the following code snippet
1
2
3
4
5
function add(first, second) { // 1️⃣
const sum = first + second; // 2️⃣
console.log('The sum is ' + sum); // 3️⃣
}
add(4, 5); //4️⃣
Code breakdown
1️⃣ - We have written a function declaration with two input parameters.
2️⃣ - We did the addition of two input parameters and stored a variable ‘sum’.
3️⃣ - We have printed the sum in console.
4️⃣ - We are calling the function by its name with parameters wrapped.
What has happened here?
We created a simple function called ‘add’. We did that by using an inbuilt JavaScript keyword ‘function’ followed by a suitable name for the function which can be used to reference this function anywhere later in the code. Then, inside the parentheses we wrote comma separated parameter names. Then, inside braces, we wrote some statements. That’s it. We just created a very simple function (or method) in JavaScript.
There are basically three ways to declare a function in JavaScript.
1
2
3
4
5
function add(first, second) {
const sum = first + second;
console.log('The sum is ' + sum);
}
add(4, 5);
1
2
3
4
5
const add = function (first, second) {
const sum = first + second;
console.log('The sum is ' + sum);
}
add(4, 5);
1
2
3
4
5
const add = (first, second) => {
const sum = first + second;
console.log('The sum is ' + sum);
}
add(4, 5);
💡 Some quick things to remember on functions in JavaScript:
We can assign a function to a variable. This is not very trivial in Java.
The input parameters passed while calling a function need not be the same as what they were when creating a function. Again, this is opposite of the case in Java, where if you have three input parameters defined in a function, you should pass three exact parameters while calling it.
They may or may not return a value.
Before we learn whether JavaScript is object-oriented, we’ll have a brief look at what an Object-Oriented Programming (OOP) language is.
Typically an OOP language deals with data in the form of classes, objects, and methods/functions. Loosely, a language is object-oriented if it adheres to four or five principles defined to be object-oriented. It is not necessary for an object-oriented language to follow all of them strictly as it may achieve a similar principle in different terms.
These principles are:
Encapsulation - This is how the language encapsulates (📦) the data it is handling. It may do this via classes/objects.
Abstraction - This is how the language hides certain details from anyone trying to access data it beholds. Through abstraction the language has control of what inside the class is accessible to the outside world and what is not.
Inheritance - This is how the language helps to extend functionality of one class by using properties and functions from other classes.
Polymorphism - This is what helps the language achieve many forms, that is to perform in different ways depending on the requirements, say which overridden method to use at compile time out of several overridden methods.
Now that we know what an object-oriented programming language is, the question is, is JavaScript one?
There is no direct yes or no answer to this question!
For example, although JavaScript has classes, which can help blueprint an object, objects do not necessarily need a class for their implementation! There are other ways JS behaves differently neglecting few strictly defined OOP rules.
JavaScript is also a functional as well as an interpreted programming language as compared to, say, Java which is purely an object-oriented language. So for a language which wants to be everything, it is difficult for it to adhere to everything a paradigm requires. In English terms this is loosely similar to the phrase, “Jack of all trades, master of none” (🌚) .
Because of this a blurry line is created with the object-orientation of JavaScript.
So yes, JavaScript is an object-oriented programming language, but with few caveats.
Every language has data types. Data types help the language to hold language specific data. There are eight of them in JavaScript.
These are string, number, bigInt, boolean, object, symbol, undefined, and null.
As we see above, ‘null’ is also one of the data types which indicates a null or void value. When a variable is just created and not assigned any value, then its value is ‘undefined’. Then we can assign it as ‘null’ indicating a placeholder.
There are probably a few questions that arose in your mind about this. Let’s look at a few of them.-
Null acts as a placeholder for any future data we might assign to the variable. A typical variable value will be undefined -> null -> some value.
How do I avoid null in JavaScript?
We can check if an object or variable is null by using the equality operator (==).
We have read about data types above. String is one of them. String is a primitive type used to represent ‘textual’ data.
Consider the following code snippet:
1 2
const name = ‘topcoder’; // 1️⃣ console.log(‘My name is‘ + name);
Code breakdown
1️⃣ - We have declared a variable and assigned some textual data to it.
What has happened here?
We created a variable and assigned the value ‘topcoder’ to it.
💡 Things to note on string
String can be quoted in single quotes (‘), double quotes (“), or string literals (`). This is in comparison to Java where only double quotes are allowed to enclose strings.
Strings are immutable, that is, once created, that original string cannot be edited or modified, although a new one can be created from it.
The elements of a string can be either accessed via bracket notation, similar to how it is used in arrays, or by using an inbuilt charAt()
function.