JavaScript

JavaScript

A Profound probe into JavaScript inner workings conditionals(if-else-if, switch case etc), queueing, loops, arrays; and how it handles such operations

Introduction

Did you know JavaScript was created in just 10 days? Despite that, it now powers over 98% of the web’s interactivity and other seamlessly working technologies. So what is JavaScript and how it is able to perform such operations and it’s fundamentals. Before going ahead it’s JavaScript not Javascript Java Script (with a space) is incorrect, and Javascript (lowercase "s") is considered a typo I am writing this because I have searched this before writing the article.

We will be covering a lot with bearing that in mind that whether you’re new to JavaScript or already adept at it, this article will help fill the gaps and clarify any obscurities in your understanding of JavaScript. I will be referring to JavaScript as JS. Alright, let’s begin with,

What is JavaScript?

JavaScript is a programming language used to make web pages interactive and dynamic. It’s one of the core technologies of web development, alongside HTML (for structure) and CSS (for styling).

Imagine a website as a house. HTML is like the bricks and walls that give it structure. CSS is like the paint and decorations that make it look nice. But without JavaScript, the house won't have any lights, or running water—nothing would work or move. JavaScript is what makes a website interactive. It's like adding electricity to the house. It lets you click buttons to open doors, turn on lights, or even play music.

If you take yourself who are you a human being which has flesh, bones, cells, tissues etc.., and then you have brain and heart which enables you to move your hand, brush and letting you to move your body.

Here your brain and heart is JavaScript which allows you to perform such activities

In other words - JavaScript is a programming language used to make web pages interactive, enabling things like real-time updates, animations, and dynamic content.

Tea with ECMAScript ( ES )

If you could have ever worked in JS one thing which you might have heard is ECMAScript or ES.

ECMAScript is a standard on which JavaScript is based!

It was created to ensure that different documents on JavaScript are talking about the same language.

ECMAScript Versions:

Beginning in 1997, JavaScript has evolved into many versions.

  • ECMAScript1 or ES1 was first released in 1997.

  • ECMAScript 2015 also known as ES6 was released in 2015 and a major revision to JavaScript was made.

  • The latest version of ECMAScript (JavaScript standard) is ECMAScript 2024 (ES15). It was officially approved in June 2024.

JavaScript and ECMAScript can almost be used interchangeably; JS is very liberal in what it allows.

Why JavaScript?

JavaScript is multi-paradigm language whether the work is handing asynchronous operations to OOP (Object-Oriented-Programming). It Works on the client-side (browser) and server-side (Node.js).
You can build websites, web apps, mobile apps, games, and even control IoT devices and there are thousands of libraries in the internet market out there. JS have massive community support with constant updates and new tools.


There is a survey of the most used technologies conducted by Stack Overflow, where they explored the tools and technologies that developers are currently using and those they want to use.

As you can see JavaScript has been a mainstay in the developer survey and on Stack Overflow. It has consistently ranked as the most popular programming language every year.

Additionally, the image below shows the most widely used web frameworks and technologies.

Node.js (which allows JavaScript to run on the server side) peaked in 2020 with its highest recorded usage score of 51%. While it may not be as popular now, it remains the most widely used web technology.

Ultimately, choosing JavaScript can be not only rewarding but also highly beneficial due to its versatility, large community support, and wide range of use cases—from front-end development to server-side applications

Now let’s move on to the part of how you can execute JS

Getting Started with JavaScript

How to Execute JavaScript?

JavaScript can be executed right inside one’s browser. You can open the JS console and start writing JS there.

Step1 : Right click on any webpage and then left click on inspect button

Step2: Left Click on the console

Step3: Write JS. Below here is demo of it

The below syntax( just like we follow some rules while speaking English [the grammer] we have some rules to follow while writing a JS program the set of these rules is called syntax in JS ) in console may cause havoc in brain if you are newbie to JavaScript.

Well believe me it’s is nothing really we will talk about this later in part because then you can comprehend it better. For now just see it as an alien language.

Node.js

Another way to execute JS is a runtime like Node.js which can be installed and used to run JavaScript code.

Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a web browser. It is commonly used for building server-side applications, command-line tools, and other types of scalable network programs.

To install Node.js, you can follow these steps:

  1. Download the installer: Go to the official Node.js website (https://nodejs.org/) and click the "Download" button to download the latest version of the Node.js installer.

  2. Run the installer: Double-click the downloaded installer file to start the installation process. Follow the prompts to complete the installation.

  3. Verify the installation: To verify that Node.js has been installed successfully, open a terminal or command prompt and type the following command:

Run the following command:

node -v

This should output the version number of Node.js that you have installed.

That's it! You should now have Node.js installed on your system and be able to run JavaScript code using the "node" command.

Yet another way to execute JavaScript is by inserting it inside the <script> tag of an HTML document.

JavaScript Variables

In JavaScript variables are used to store data. They are an essential part of any programming language, as they allow you to store, retrieve, and manipulate data in your programs.

There are a few different ways to declare variables in JavaScript, each with its own syntax and rules.

Consider a variable nothing but — a container that stores a value;

like when you eats your stomach stores some food

Scope

In JS scope determines where the variable is accessible. We have three main types of scope

  • Global Scope: Variables declared outside any function or block have global scope. They are accessible from anywhere in your code

  • Block Scope: Variables declared with let and const inside a block ({}) are only accessible inside that block.

  • Function Scope: Variables declared inside a function are only accessible within that function. This is also called local scope.

Declaring Variables

Like I have said earlier there are different ways to declare variables, for example

Here we assigns a value to x is 1 and we assigns it using keyword “var“ . var is global scope variable

Variable Naming Rules and Operations

JavaScript is a dynamically-typed language, which means that you don't have to specify the data type of a variable when you declare it. The data type of a variable is determined by the value that is assigned to it. For example:

Here comes an intriguing thing look at this code below

In this we are adding number1 and number2 but surprisingly output is 11. You will get to know it why this happen so[for more info refer chapter primitive datatypes and objects]

There are a few rules that you need to follow when naming variables in JavaScript:

  • Variable names can only contain letters, digits, underscores, and dollar signs.

  • Variable names cannot start with a digit.

  • Variable names are case-sensitive.

It is also a good practice to use descriptive and meaningful names for your variables, as this makes your code easier to read and understand.

Once you have declared a variable, you can use it to store and retrieve data in your program. For example:

You can also perform various operations on variables, such as mathematical calculations, division, multiplication and more
For example:

let / var / const , which one’s Great?

Now we have understand variables; what are they and their scope,

Each of these keywords has its own rules and uses, and it is important to understand the differences between them in order to write effective and maintainable code.

var

The "var" keyword is used to declare variables in JavaScript. It was introduced in the early days of the language and was the only way to declare variables for a long time. However, the "var" keyword has some limitations and has been largely replaced by the "let" and "const" keywords in modern JavaScript.

One of the main issues with "var" is that it is function-scoped, rather than block-scoped. This means that variables declared with "var" are accessible within the entire function in which they are declared, rather than just within the block of code in which they appear. This can lead to unexpected behavior and can make it difficult to reason about the scope of variables in your code

let

The let keyword was introduced in ECMAScript 6(ES6) and is used to declare variables that can be reassign later. “let“ is block scope variable and it is accessible within the code block in which they are declared.
This makes them more predictable and easier to reason about than "var" variables.
For example

As you can see if you log y outside of the if statement it is giving ReferenceError : y is not defined.
Because ‘y' is declared inside the if statement.

const

const” keyword is totally different from both the var and let. First of all it cannot be reassigned later unlike let and var. On top of that it was also introduced in ES6, const variables are also block-scoped and behave similarly to let variables in that respect.

In this example, the "PI" variable is declared with the const keyword and is assigned the value of 3.14. If you try to reassign a new value to "PI," you will get a "TypeError" because "PI" is a constant variable and cannot be changed.


Primitive Data Types

What are Primitive Data Types ?

Primitive Data Types are a set of basic data types in JavaScript.
In simplest form— they are the most basic types of data. They represent simple values that are immutable (cannot be changed) and are stored directly in the memory.

In this example, the value of "x" is changed from 10 to 20. However, this does not change the value of the primitive itself, but rather creates a new primitive with the value of 20.

Types of Primitive Data Types

There are 7 types of Primitive Data Types, they include:

  1. Numbers (e.g. 10, 3.14)

  2. Strings (e.g. "hello", 'world')

  3. Booleans (e.g. true, false)

  4. Null (a special value that represents an absence of value)

  5. Undefined (a special value that represents an uninitialized variable)

  6. Object and arrays are non primitive data types

Null vs undefined

To discern the difference between null and undefined. Think of them like this way

  • undefined is like opening a locker that has never been assigned anything—it’s empty because no one has put anything in it yet.

  • null is like opening a locker that has been deliberately emptied out—there was something inside before, but someone cleared it and left it intentionally empty.

Breaking it down:

  • undefined: "We haven’t set anything in this variable yet." (It’s uninitialized.)

  • null: "We’ve cleared this variable. It’s supposed to be empty." (It’s explicitly set to nothing.)

Objects

Objects are more complex data types in JavaScript and are used to represent real-world objects or abstract concepts. They are composed of key-value pairs, where the keys are strings and the values can be any data type (including primitives and other objects).

Think of yourself as an object, human body is also a object is way more complex also it is a real-world object human body is also flexible(it can grow),

Objects are mutable, which means that they can be changed after they are created.

For example:

In the above code a object is created with variable obj(you can give it anything; but remember rules naming variables). To add more key and value you need to separate them with a comma ’,’

In JS objects can also hold functions, nested objects and also arrays

  • Function in an object

  • Nested Object


Operators and Expressions

A Fragment of code that produces a value is called an expression.

Operators in JavaScript are symbols that perform specific operations on one or more operands (values or variables). For example, the addition operator (+) adds two operands together and the assignment operator (=) assigns a value to a variable.

There are several types of operators in JavaScript,

  1. Arithmetic Operators : used for basic math operations
OperatorDescriptionExampleResult
+Addition5+17
-Subtraction10-91
*Multiplication3×26
/Division10/25
%Modulus(Remainder)5 % 21
**Exponentiation12 ** 2144
  1. Assignment Operators: Used to assign values to variables.
OperatorExampleEquivalent To
\=x = 5Assign 5 to x
+=x +=3x = x+3
-=x -= 2x = x-3
*=x *= 2x = x * 2
/=x /= 2x = x / 2
%=x %= 2x = x % 2
  1. Comparison Operators : Use to compare values and return a boolean (true or false)
OperatorDescriptionExampleResult
==Equal to5 == '5'true
===Strict equal to5 === '5'false
!=Not equal to5 != '5'false
!==Strict not equal to5 !== '5'true
>Greater than5 > 2true
<Less than5 < 2false
>=Greater than or equal to5 >= 5true
<=Less than or equal to5 <= 5true
  1. Logical Operators: Used to combine multiple conditions.
OperatorDescriptionExample
&&Logical ANDtrue && false
!Logical NOT! true
  1. Ternary Operator: A short hand for if-else

    For example


Conditions

Overview and inner workings of (if-else & switch case)

The if statement in JavaScript is used to execute a block of code if a certain condition is met. The else clause is used to execute a block of code if the condition is not met.

Here is the basic syntax for an if statement:

The if statement evaluates the condition inside the parenthesis ()
If the condition is evaluated to true, the code inside the body of curly braces {} will execute

Here is the syntax for an if statement with an else clause:

However, it will not enter the else part.
Example:

In JS we have three types of if-else statements

  • if statement

  • if-else statement

  • if-else-if statement also known as if-else-ladder

Sometimes we might want to rechecking some conditions one by one until one matches. We use if-else-if ladder to achieve this.

The "if-else ladder" is a control structure in JavaScript that allows you to execute a different block of code depending on multiple conditions. It is called a ladder because it consists of multiple "if" and "else" statements arranged in a ladder-like fashion.

The "if-else ladder" is a useful control structure for executing different blocks of code based on multiple conditions. It can help you write more concise and maintainable code in JavaScript.

Switch Case

The switch statement in JavaScript is another control structure that allows you to execute a different block of code depending on a specific value. It is often used as an alternative to the "if-else ladder" when you have multiple conditions to check against a single value.

It is more faster and easily readable than if-else-ladder

For example:

Loops

What is a loop really is?

A loop in JavaScript is a way to repeat a block of code multiple times until a specific condition is met.

It helps avoid writing repetitive code. For example, if you want to print "Hello" 100 times, instead of writing console.log("Hello") 100 times, you can use a loop.

Inner workings of Loop

The initialization the statement is executed before the loop starts and is typically used to initialize a counter variable.

The condition is checked at the beginning of each iteration and if it is true, the loop continues. If it is false, the loop exits.

The increment/decrement/update statement is executed at the end of each iteration and is used to update the counter variable.

Here's an example of a standard for loop that counts from 1 to 10:

This loop will print the number 1 through 10 in the console

Types of Loops in JavaScript

In JavaScript we have various types of loops each has it’s own different function such as,

Common Loops

  1. For Loop: Repeats a block of code a fixed number of times

while loop – Repeats as long as the condition is true.

  1. do...while loop – Similar to whileloop, but it makes sure that the code runs at least once

    For example:

More Loops

  • for...of loop – Iterates over iterable objects (like arrays).

  • for…in loop - Iterates thorough the properties of an object


Arrays in JavaScript

After the Objects in JavaScript arrays are the most intriguing thing out there in JS .

Arrays in JavaScript are a collection of items stored in a single variable. They can hold multiple data types—numbers, strings, objects, other arrays—and are dynamic, meaning their size can change.

In other words —An array in JavaScript is a collection of elements enclosed in square brackets.

A valid array :

Inner Workflow on creating an array

The whole process of an array is radiating around this loop

In JS arrays are objects. The typesof operator on an array returns object. They can grow dynamically thus are mutable like objects. They can also have multiple data types in an array.
For example:

In JavaScript, arrays are zero-indexed, which means the first element is at index 0, the second at 1, and so on. This indexing allows direct access to elements using their position.

Array Methods in JavaScript

Array methods are always generic — they don't access any internal data of the array object. They only access the array elements through the length property and the indexed elements. This means that they can be called on array-like objects as well.
JavaScript provide us a number of built-in array methods, some of them are as follows:

  1. toString(): The .toString() method converts an array into a string, separating each element with a comma, Unlike join(separator) allows you to specify a custom separator.
    It’s useful when you want to represent an array as a simple string (e.g., for logging or displaying data).

     array.toString();
    

    It does not modifies the original array but returns a string

    Example:

  2. length: This array method returns the number of elements in array.

    NOTE: In this methods we don’t use parenthesis, unlike many others method do.

  3. push(): This method appends new element to the end of an array, and returns the new length of the array.

    This methods is used like in building a queue system or adding items to a shopping cart.

4 . pop(): Removes the last element from an array and returns it.

If the array is empty, undefined is returned and the array is not modified.

This operation is commonly used in stack-based algorithms where the "last-in, first-out" (LIFO) approach is applied.

For instance, in undo operations in text editors or browser history management, pop() efficiently retrieves the most recent action or visited page.

The pop() operation is computationally inexpensive since it only removes the last element without affecting other elements in the array.

However, frequent use of pop() in certain cases may lead to loss of important data unless the removed items are stored elsewhere for potential reuse.

5 . shift(): Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

This method is ideal for implementing first-in, first-out (FIFO) systems, such as message queues or order-processing systems in e-commerce platforms.

However, unlike pop(), the shift() method is less efficient because it requires reindexing of all remaining elements after the first one is removed.

This overhead makes shift() less performant in scenarios involving large arrays with frequent deletions.

For better performance, consider using linked lists or other data structures when dealing with massive datasets.

6 . unshift(): This method in JavaScript is used to add an element to the beginning of an array.

It returns the new length of the array

7 . slice() - This method is used to extract a portion of an array.

For example:

The slice() method returns a shallow copy of a portion of an array, without modifying the original array.

This makes it an excellent choice for tasks like paginating data or creating temporary subsets for analysis.

The method takes two arguments: start (inclusive) and end (exclusive), allowing precise control over the extracted portion.

8 . splice() - This method is used to add or remove elements from an array

9 . sort(): The sort() method sorts the elements of an array in place and returns the sorted array.

By default, it converts elements to strings and sorts them in ascending order based on Unicode values.

For numeric or custom sorting, a compare function is required.

For example: Sorting the list of pricing in Ecommerce-application,

10 . reverse(): Reversing the Order of Elements

The reverse() method reverses the elements of an array in place, modifying the original array.

It’s useful for tasks like displaying items in reverse chronological order or reversing sequences for specific algorithms.

For example : Displaying the latest posts first

11 . filter(): This method filters a given array which passes the test(condition), and returns a new array(filtered)

filter() method takes a callback function as its argument, which is called on each element in the array.

It’s a non-destructive method, ideal for extracting data based on conditions.

For example: Filtering Active Users in a System

  1. reduce(): The reduce() method executes a reducer function on each element of the array, resulting in a single accumulated value. It’s one of the most powerful array methods, capable of handling tasks like summing values, flattening arrays, or building complex objects.

    It takes a callback function as its argument, which is called on each element in the array.

    The callback function takes two arguments, the accumulator and the current element, and returns the new value for the accumulator.

For example calculation the total revenue from an Array on Transactions

13 . map(): The map method is used to create a new array with the result of a callback function called on each element in the original array.

The callback function takes one argument, the current element, and returns the new value for that element.

For example, the following code will return an array of each element multiplied by 2:

It’s commonly used for data transformation, such as converting formats, applying calculations, or generating UI elements.

Another example is converting an Array of Prices from USD to INR

It does not modify the original array

Loops with Arrays

Now moving onto the last section of this article— loops with arrays.

While working in JavaScript one of the most important data structures is the array, which is a collection of elements. When working with arrays, it is often necessary to iterate through each element in the array, which is where loops come in.

for loop:

The for loop is a fundamental looping structure that provides full control over the iteration process.
The for loop uses a counter variable that is incremented on each iteration.

For example:

The for loop is ideal for scenarios that require precise control over iteration, especially when you need to access both the index and value of each array element.

for.. each loop:

This method is a more concise way to iterate through an array. The forEach method takes a callback function as its argument, which is called on each element in the array.

For example, the following code will print out each element in the array:

It’s especially useful when you only care about the values, not their positions.

for.. of loop:

This is a more recent addition to JavaScript, and it is the most concise way to iterate through an array. It allows you to iterate through the elements of an array without having to access the index, and it works with any iterable object, not just arrays.

For example, the following code will print out each element in the array:

It is important to note that when you are iterating through an array using a for loop and you plan to change the array during iteration you should use a for loop with a separate counter variable.

That’s all !

A Profound probe into JavaScript inner workings conditionals(if-else-if, switch case etc), queueing, loops, arrays; and how it handles such operations


Conclusion

JavaScript is a high-level, interpreted programming language primarily used to make web pages interactive. It enables dynamic content like interactive forms, animations, real-time updates, and more.
ES(also known as ECMAScript) is standard on which JS is based. We have several ways to run JS, “.js” is the extension. Nowadays it used in for both the frontend and server-side development.

  • A variable in JS is a container that stores a value.

  • Each variable has it’s scope which determines where the variable is accessible. Once the variable is declared we can store it and can retrieve data from it

  • JavaScript has a number of Data Types they are a piece of data that tells a computer system how to interpret its value

  • An object in JavaScript is a data structure used to represent or store real-world objects. They are mutable. They stores data as key-value pairs, where each key is a unique identifier for the associated value.

  • Objects can also hold nested functions, arrays and even objects.

  • Expressions are combinations of values, variables, and operators that produce a result.

  • JavaScript operators are special symbols used in scripts to perform operations on operands, such as arithmetic calculations, logical comparisons, or value assignments.

  • Conditions in JavaScript allow us to control the flow of a program by executing different blocks of code based on specific conditions.

  • For loops are a common control flow structure in programming that allows you to repeat a block of code a specific number of times.

  • Arrays in JavaScript are a collection of items stored in a single variable.

  • In JS, loops are used to repeatedly execute a block of code, and arrays are used to store multiple values in a single variable. Combining loops with arrays allows you to iterate over the elements of an array and perform operations on each element.