JavaScript RoadMap - Fundamentals of JavaScript - Part 1

JavaScript RoadMap - Fundamentals of JavaScript - Part 1

Introduction

If you are new to JavaScript, Welcome mate! 🤜🤛 this series will take you from the basics of JavaScript to advanced concepts. And, if you already know JavaScript, this series will be a good brush up for your skills, so follow along.

Also, If you have any queries throughout this series, feel free to DM me on my Twitter account, I will be happy to help you to the best of my ability. So, make sure you follow me on Twitter, I will be posting all my updates there, along with other useful information.

OK, enough of this chit-chat, let's dive right into the actual stuff 🏄

What is JavaScript?

Before we get started knowing how things work in JavaScript, how we create variables, blah blah blah... we need to know “What is JavaScript?

So, if we go with the technical definition of JavaScript, it says:

“JavaScript is a High-Level, Object-Oriented, Multi-Paradigm programming language”

That’s it, let's move to the next section. Just kidding...

To understand the actual meaning of this definition, let's break down the three fancy words there and see what they mean, which will give us clarity of the definition.

  • High-Level:

By High-Level it means when we are writing our code in JavaScript we don’t have to worry about complex stuff like memory management, garbage collection, etc. We can focus on core stuff which is writing our logic without worrying about all that stuff.

  • Object-Oriented:

Object-Oriented means most kinds of data we will be storing will be in the form of objects. Objects make a lot of sense when we talk about storing real-world information in our program. You will be seeing objects for storing data quite a lot in JavaScript.

  • Multi-Paradigm:

JavaScript is a very cool language, it is very liberal in terms of programming style. In other programming languages, there are some strict sets of rules like expression should end with a semi-colon or code should be intended in a certain manner, etc. JavaScript, on the other hand, gives you a free hand, you can use a semi-colon or not, it's up to you. However, there are some best practices you should follow. You will get all those as you get familiar with the language.

Role of JavaScript in Web Development

The front-end of all web applications is made up of three components: HTML, CSS, and JavaScript.

HTML is responsible for the content we see on the page. CSS makes all the content presentable and JavaScript makes the content interactive.

Think it this way, you meet a person, he/she looks really beautiful/handsome but does not interact at all. You cannot talk to that person, cannot hang out, nothing interactive, just they look good.

Do you think just because that person looks good, you will like his/her company? I am damn sure you won’t.

That’s what HTML and CSS do. they make a web page look pleasing, but JavaScript makes it alive.

These days, we have so many frameworks like React, Angular, React Native, and many others, all of these are built on top of JavaScript. With the help of these frameworks, we can build powerful web applications much quicker but in the end, it's all JavaScript. This is the reason, why you should learn JavaScript, these frameworks can be replaced but not JavaScript.

Hang on tight, we are catching up the pace now🏎️

Fundamentals of JavaScript - Part 1

Now, you have an idea about JavaScript and how important it is in the Web Development world. Now is the time to get into the technical details of JavaScript. Understanding the fundamentals is very essential before we move on to the complex stuff. This section will be focused on providing you with all the necessary fundamentals for the language which you will be using from the beginning and throughout your journey in JavaScript.

I have divided the Fundamentals into two parts. In Part 1, we will discuss smaller but important things, of JavaScript but also will be helpful for general programming as well.

In Part 2, we will discuss the topics which are more specific to JavaScript, and you will be using them every day as a JavaScript Developer. The next blog of this series will cover Part 2. In this blog, we will understand Part 1 of Fundamentals of JavaScript.

Let's get started 🚀

Data Types in JavaScript

Data types define the kind of data it is capable of storing. The data in programming languages are categorized into a few different kinds and data types tell which data should be placed where. It organizes the storage of data according to the category of data.

JavaScript stores values in mainly two types, one is in form of Objects, and the rest are called Primitive data types.

  • Object Data Type:

Objects are data types that allow you to store the collection of data. Data stored in an object is in form of key, and value pair.

//person object
let person = {
    name : 'Damon'
};

Note: All data types that store the collection of data comes under object data type (e.g. Arrays, Maps, etc.)

  • Primitive Data Types:

There are mainly 5 primitive data types in JavaScript that you will be using in your code. We don’t need to get deep into each as you will understand these when you practice.

So, let's see what are these primitive data types and what are they used for.

  • Number → Floating point numbers 👉 Used for decimal and integers
let age = 160;
  • String → Sequence of characters 👉 Used for text
let name = 'Stefan';
  • Boolean → Logical type that can be only either true or false 👉 Used in conditional statements
let immortal = true;
  • Undefined → Value is taken by a variable that is not yet defined.
let children;
// if you log children variable you will get 'undefined'
  • Null → Empty value
let reality = null;
// null is an empty type of value

Variables - let, const, and var

Variables are the containers that we use to store values, that will be useful to perform some operations later in the program.

To use a variable you first need to create it or say declare it. To do so in JavaScript we have three keywords, which are reserved to create variables. Let’s see these three types of variable declaration in detail.

  • let :

You have seen this let keyword in the above section of data types, we have used the let keyword to declare variables, but how exactly does it work?

When you declare a variable using let, you are declaring a variable which then you can initialize with a value and you can use that variable name to access the value.

let name = "Damon";
console.log(name);

// Output: Damon

Also, if you want to change the value of that variable at a later point in time, that is possible too.

From the above example, if we change the value and console log the variable name, it will give us an updated name in the output.

name = "Matt";
console.log(name);

//Output: Matt

This is called a mutation, remember this term, you will be seeing this a lot in JavaScript.

let allows us to create a mutable variable, i.e. we can change its value of it at a later stage.

Due to this reason, you can even create variables without initializing them. You can assign the value later.

let name;
name = "Stefan";
console.log(name);

//Output: Stefan
  • const :

When we declare a variable using the const keyword we want to create an immutable variable, i.e. its value cannot be changed later. The declaration of a variable is the same as we have seen in let.

const name = "Matt";
console.log(name);

//Output: Matt

If you try to mutate the value as we did in let, it will throw an error. It won’t allow it to mutate.

name = "Damon";
console.log(name);

//Output: TypeError: Assignment to constant variable

Also, due to this, you have to initialize the value at the time of declaration only.

const name = "Stefan";
// This is allowed for const

const name;
name = "Stefan";
//This is not allowed, will get error in this case.
  • var:

We have seen let and const, these were introduced in the ES6 update of JavaScript which we call modern JavaScript. Before, this ES6 update, variables are created using the var keyword.

“var” works similar to variables created using “let”. So, the question is if it was similar what is the need for “let”.

The main difference is var is a functional scope, whereas let is a block scope.

function testFunc() {
    let greeting = "Hello ";

    if(greeting === "Hello ") {
        var name1 = "Damon";
        let name2 = "Stefan";
    }

    console.log(greeting+name1);  //Output: Hello Damon
    console.log(greeting+name2);  //Output: ReferenceError
 }

The reason for introducing “let” is because the functional scope is confusing with “var” and was one of the main sources of bugs in JavaScript.

Also, Hoisting occurs in the case of “var”, however, hoisting does not occur in the case of “let” and “const”.

Basic Operators in JavaScript you should know

If you search the documentation for JavaScript or any other place specifically for operators in JavaScript, you will be overwhelmed with the list of operators available.

However, there are few operators which we use quite often and I believe knowing about them well enough is much more important than knowing all operators.

Also, you can look up documentation anytime later as per your need for any specific thing you are looking for.

For now, we will focus on the main operators which we use a lot in our regular JavaScript development, and instead, of explaining them in a theory, I think it's better to see them in code. That will give you a better idea of the usage and how these operators work.

  • Math Operators:
//Math Operators
let currentYear = 2022;

let myAge = currentYear - 1997; // Minus operator for subtracting values

let multiply =  myAge * 2; //Multiply operator 

let powerOff = 2**3; // This is Exponential operator,
                    // internally it is performing 2 * 2 * 2

let divide = 10/2; // Division operator, 
                  //also note that it will give values in decimal

let result = typeof(myAge); // this is also used a lot, it return the data type of
                // variable passed to it, in our case it will retur "number"

let addition = myAge + 2; // This operator does more than addition in JavaScript
              // In case of number it perform addition

let name = "Anurag";
conole.log(myAge + " " + name); // In case of string it perform concatenation
            // i.e. it join two strings
  • Assignment Operator:
//Assignment Operator

let name = "Matt"; //assign a string to variable
let x = 10;        // assign a number to a varible
let sum = x + 5;   // assign operation result to a variable

// "=" is called an assignment operator, it assigns a value to a variable.

//let's see some variation of it that will be handy for you
let x += 15;  // x = x + 15 = 25
let x *= 4;   // x = x * 4 = 100
let x++;      // x = x + 1;
let x--;      // x = x - 1;
  • Comparison Operator:
//Comparison Operator
//The result of the comparison operator is a boolea value i.e. True or False
let x = 10;
let y = 15;

console.log(x < y); // less than operator
console.log(x <= y); // less than or equal to operator
console.log(x > y); // greater than operator
console.log(x >= y); // greater than or equal to operator

// You can even compare expression too
console.log(x + 5 > y - 5); // this is possible because of Operator precedence
                                                        // We will see that in next section
  • Equality Operators:

In JavaScript, we have two types of equality operators, one is the “Strict equality operator” and another one is called the “Loose equality operator”. The result of the Equality operator is a Boolean value

//Strict Equality
x === y // it checks values as well as data type of the two values

//Loose Equality
x == y  //it only checks for values and not Data types

//Example
10 === '10'  // this will return false as values are matching but not data type

10 == '10'  //However, this will return true as it only check values not data type

Equality operators are used mostly in the condition statements, like in “If-else” statements. We will see this in detail as we move forward. For now, just remember, Strict Equality checks for values as well as data type, whereas, Loose equality checks for only values.

There is one more operator called the “Ternary Operator”, but before that, we need to know how condition statements work. In programming, everything is connected, you cannot just know one concept and start coding, it's a combination of the interdependent concepts. You need to know how these concepts work together before starting to code.

Conditional Statement : if-else

Conditional statements are used whenever you need to perform certain actions depending on the current state of the program. We may need to perform different actions depending on the state of the program, there is when conditional statements come into the picture.

How conditional statement works?

A conditional statement works on boolean logic. Whatever, the condition we provide, the result of it is always a Boolean value i.e. True or False and the conditional statement acts according to the result of the condition.

To write this logic, we use the if-else statement provided in JavaScript.

if(x===y) {  // Condition that needs to be checked
    console.log("x is equal to y");   // run if condition result is true
}else {
    console.log("x is not equal to y"); // run if condition result is false
}

The condition that needs to be checked comes in the parenthesis after “if” and if the result of the condition is true, the logic or statements we have written inside if block is executed, however, if the condition result is false, the logic or statements inside the else block is executed.

We can even write nested if-else statements and chain if-else to check from multiple possibilities.

//Nested if-else

if(x===y) {  // Condition that needs to be checked
    if(x > 10){
      console.log("x is greater than 10");   // run if condition result is true
    }else {
      console.log("x is not greater than 10");
  }
}else {
    console.log("x is not equal to y"); // run if condition result is false
}

//Chained if-else

if(x>10){
    //perform some action
} else if(x>5) {
    //perform some action
}else {
    //perform some action
}

As you see the conditions we have provided, always result in Boolean results. But what if we provide some other value than these, like a single string or a number or even a variable, will it work? 🤔

The answer is yes, when we pass some other values like a String or a number or a variable, JavaScript converts that to a Boolean value, explicitly, this phenomenon of converting data type automatically by JavaScript is called Type Coercion.

if("Anurag") {
    console.log("this is considers as true");
}

But, how does JavaScript decide what is true and what is false in such cases?

Well, JavaScript has two types of values which are called Truthy and Falsy values.

What are Truthy & Falsy values?

In JavaScript, there are 5 falsy values : 0 (zero), “” (empty string), undefined, null, and NaN (Not a Number), all values other than these 5 are considered as truthy values.

So, when we pass any other values than the expressions which do not return a Boolean result by default, JavaScript performs Type Coercion according to the truthy and falsy values we have seen above and executes the if-else block accordingly.

Now, that you know how conditional statements work in JavaScript, let's see one more operator we left earlier, the operator is called “Ternary Operator or Conditional Operator”.

Ternary Operator or Condition Operator

The ternary operator works similar to if-else statements and is used a lot as an alternative to if-else statements. In cases where we have to perform simple operations, we can use the Ternary operator and structure our logic in a single line.

x === y ? console.log("x is equal to y") : console.log("x is not equal to y");
//Expression     execute if True                 execute if false

The Ternary operator is created using two symbols: “?” and “:”

Let’s see how to structure the Ternary operator in three simple steps:

  1. The expression which needs to be evaluated comes first, in our case it is the “x === y” followed by the “?” symbol
  2. The expression/statement that should be executed if the expression in point 1 comes true, will be written after the “?” symbol. The executable statement/expression is followed by the “:” symbol.
  3. If the expression in point 1 results in false, the statement/expression, in that case, will come after the “:” symbol

As you can see we have written the logic we have seen in the if-else section, we have written it in a concise way with the help of the Ternary operator.

Ternary Operator is really handy, in case of condition assignment. When we want to assign some value to a variable based on some condition, using the Ternary operator makes a lot of sense, as we can do it in a single line, since the assignment is not a complex operation.

let greaterValue = x > y ? x : y;

Here, from the above code, we have assigned the “greaterValue” variable with the help of the Ternary operator. We are comparing x and y and whichever has a greater value of two, that value will be assigned to the “greaterValue” variable. You will be doing such operations a lot when writing bigger programs.

So far, we have seen two ways to perform operations according to a certain condition. We have seen when we pass a single value as a String, number, or variable it is converted to a boolean value by Type Coercion and evaluated accordingly.

What if instead of evaluating boolean, we want to check the actual value of that String, number, or variable? 🤔

Let’s see how to handle this situation in the next section.

Switch Statement

As we have seen the problem with if-else and ternary operators they perform Type Coercion and evaluate according to truthy and falsy values. But sometimes, we need to check the actual value of expression we have passed.

That is where the switch statement comes into the picture. Let’s see how the Switch statement works.

const name = "Anurag";
switch(name) {
    case "Damon":
     console.log("He is a Vampire!");
     break;
    case "Matt":
        console.log("He is a policeman!");
      break;
    case "Anurag":
      console.log("He is a JavaScript Developer!");
      break;
  default:
      console.log("He is a lovely Human being!");
    break;
}

//Output: He is a JavaScript Developer!

The switch statement starts with the “switch” keyword followed by the expression in parenthesis that needs to be checked.

Another component in the switch statement in “case”, is where we define different possible values of the expression followed by a colon ”:”. Below the case, we write our logic that is according to the different values possible.

Each case ends with the “break” keyword. This is optional, however, it is recommended to put a break after each case, otherwise, all the cases will be executed until it gets to the break or end of the switch block.

There is one more component i.e. “default”, the statement after the default is executed if none of the cases matches the expression passed to the switch.

Now, that you have got the idea of all the conditional checks we use in JavaScript along with the data types, variables, and different operators, there is one last thing left for this Fundamental part 1 which is really important and useful for many coding challenges and interviews.

Let’s dive into the last section for the Fundamentals Part 1 🪂

Strings and Template Literals

Strings are the sequences of characters that represent the text value. You are seeing Strings used from the beginning. You have seen a single line explaining Strings in the Data Type section, but there is a lot more to Strings.

Strings are one of the most important topics in JavaScript, you will see a lot of questions coming from this topic in your coding challenges and interviews.

Some of the most common operations performed Strings are length, indexOf(), substring(), chatAt().

I highly recommend clicking the link and checking the documentation of each of these methods. It won’t be possible to cover those here in this article.

Creation of Strings:

Till now we have seen one way of creating a String which is assigning a variable with a sequence of characters in double or single quotes.

Let’s see another way to create Strings using the String() constructor and how they are different.

let str1 = "This is a simple String";
let str2 = new String("This is a String object");

The difference between the two is that if you check the data type of both the strings, the first string will be of string type whereas the second string will be an object. Both, ways of creating strings can be used interchangeably in most situations.

Comparisons of Strings:

In most languages we have specific functions to compare two Strings, in JavaScript, we can use simple comparison operators, like less than (<), greater than (>), and equal to (==) to compare two Strings.

// function to compare String without case sensitivity 
function compareString(str1, str2) {
  return str1.toUpperCase() === str2.toUpperCase();
}

Check the JavaScript documentation of Strings for more details on Strings and its various methods of it.

Now, you know a lot about Strings and some of their common methods. You will be able to work with strings and some string manipulation operations. However, there is one last thing related to Strings that will help to create dynamic Strings a lot easier.

Let’s see what is “Template Literals”

Template Literals:

Template Literals or what some developers call Template Strings are most commonly used to create strings that contain some placeholders. These placeholders are embedded in the Sting using a format i.e. the expression is enclosed in curly braces which along with the dollar sign placed in front of it.

The Template Literals are enclosed in backtick (`). Let’s see the structure with the help of an example.

let type = "Template Literal";

let template = `This is sample string of ${type}`;

console.log(template);
//Output: This is  sample string of Templte Literal

The main advantage of using Template Literals is that it makes the code much more readable.

Let’s see a simple example to understand it.

//using normal strings
let a = 10;
let b = 20;
console.log("Sum of a and b is "+(a+b)+" and Difference of a and b is "+(a-b)+"..." )

//output: Sum of a and b is 30 and Difference of a and b is 10...

//using Template Literals
let a = 10;
let b = 20;
console.log(`Sum of a and b is ${a+b} and Difference of a and b is ${a-b}...` )

//output: Sum of a and b is 30 and Difference of a and b is 10...

As you can observe, the result of both the approach is the same, but the Template Literals are much cleaner, and easy to write and maintain.

The placeholder ${expression} not only replaces the string but is capable of doing the operation and replacing that part of the string using the operation result.

With this advantage, you can write simple logic in the String itself, as we did above. Even, you can have nested Template Literals using this approach, but that is something you can explore yourself once you are comfortable working with it.

There is more advanced stuff you can do with Template Literals but from my experience, you won’t be needing that as of now. That will definitely be overwhelming for you.

For now, just remember to use Template Literals where you need to embed some expression in the string that’s it.

Conclusion

Huh!!! That was all about the Fundamentals of JavaScript - Part 1. I have tried to cover as much information as possible right from scratch to help you get started in JavaScript from the ground up, but at the same time, I have tried not to overwhelm you with the information that you won’t need right now.

You will definitely learn a lot as we move forward, using these concepts that you just learned along with some more advanced stuff we use in JavaScript.

This article was focused on getting theoretical knowledge of JavaScript. In the next article, Fundamentals of JavaScript - Part 2 we will dive into the practical stuff of JavaScript like Functions, Arrays, etc.

Just reading these articles won’t take you anywhere, you need to apply that and see the concepts in action yourself.

I recommend the code I have included in this article you can try it in any online JavaScript compiler, and see the working yourself.

If you are interested in JavaScript, React, and more Front-end related tips and useful information, follow me on Twitter @anuragmathews08

That’s it from me, I wish you all the best in your learning journey.

Let’s grow together 🤝

Happy Coding!

Bye-bye!!! 👋

Reference

Did you find this article valuable?

Support Anurag Mathews by becoming a sponsor. Any amount is appreciated!