# JavaScript Part 1: Foundational Concepts & Code Execution Flow

<details data-node-type="hn-details-summary">
<summary>Prerequisite to go with that article</summary>
<p>I create this article by assuming you had already learn or reads bellow topics.</p><ul><li><p>What is Internet? What is Web and Websites?</p></li><li><p>Basic understanding of how browser works?</p></li><li><p>Basic Understanding about HTML &amp; CSS</p></li></ul><p>If you don't about about them but want to learn JavaScript. Don't worry you can understand them by just spending few days for learn about these concepts.</p>
</details>

## Introduction to JavaScript

### What is JavaScript

JavaScript is a High Level, Dynamic Programming Language. Means you don't need to write complex code to work with core hardware like CPU or Memory Management. No need to define data types of the variables before using. JavaScript handle all these at run time. It is the core technology used into the World Wide Web along with HTML & CSS.

*   HTML is a markup language used to defined structure of web page.
    
*   CSS is a styling language used for adding styles on web page.
    
*   JavaScript is used to add interactions and logic on the web page.
    

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/6352631e-0686-4396-b524-107db1170953.png align="center")

### Brief History of JavaScript

JavaScript was created by a Software Engineer Brendan Eich. He worked at Netscape Communicator. He was given a task to created a lightweight language for the Netscape Navigator Browser for adding interactions on web pages. He created it in just 10 days with code name Mocha.

Netscape published it in September 1995 with Beta version of Netscape Browser as LiveScript. Later it was officially released in December 1995 with collaboration of Sun MicroSystems. They re-brand it as JavaScript to catch the popularity hype of Java.

After official release Netscape organisation submit JavaScript to ECMA. Requested to standardise it across different browsers. So they can prevent competitors browser for creating fragmented, incompatible version of JavaScript. It results a ECMAScript manage the JavaScript versions.

After a decade, in 2005 a technique introduced called AJAX (Asynchronous JavaScript and XML). Which allow web pages to make request and load content dynamically in the background. Before it, if user submit a form page was reloads to submit the user data to servers leads slow user experience. AJAX makes the JavaScript a complete language for Frontend Language for Websites.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/782dbf8a-d905-464d-977d-c70430ac495c.png align="center")

### Overview of JavaScript Versions

As we know JavaScript versions are managed by the ECMAScript. Each version of JavaScript is tracked by its ES Number like ES6.

*   **Foundation ES1-ES3:** These are the initial versions of JavaScript released between 1997 to 1999. These version established the foundation of language by introducing - core syntax, regular express and exceptional handling. From them ES3 version had become the baseline version.
    
*   **Stabilization (ES5):** ES4 version was totally failure it rejected by the community and never released officially. After that ES5 released in 2009 which focused on safety and utility of the language. It introduced strict mode for catching silent failures, native JSON support for serialising, and Getters & Setters for object property encapsulation.
    
*   **Modernization (ES6 / ES2015):** Also known as ES2015. It was introduce to completely modernised JavaScript by adding some most important features like `let, const` over `var` for declaring variables, arrow functions, and native support of OOPs syntax, Promises and `import - export` for code splitting.
    
*   **Annual Updates (ES2016 - Present)**: To avoid the 6-year gap and massive feature dump between ES5 and ES6, the TC39 committee adopted a rolling annual release schedule. Features are now proposed, tested, and added incrementally each year, ensuring continuous, predictable, and non-disruptive language evolution.
    

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/c96e8d94-a6a1-4840-a9d9-3b6df147a58a.png align="center")

### How to run JavaScript

JavaScript needs a "home" (a runtime environment) to work and talk to the outside world. There are two main homes for it:

*   **The Browser:** This is JavaScript's original home. It is great at changing how web pages look and saving basic website data. However, it is kept inside a secure "sandbox," meaning it is completely blocked from accessing your actual computer's hard drive or system files.
    
*   **The Server (Computers):** Tools like Node.js, Deno, or Bun allow JavaScript to run directly on a computer instead of a web browser. Here, JavaScript can act like a traditional program—reading and writing files on the hard drive and controlling the system. However, because it's not in a browser, it doesn't know how to interact with web page visuals.
    

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/b614e53e-9a33-4726-b415-dc7f9cb6654a.png align="center")

How you actually run the code depends on the environment you are using:

*   **In the Browser:** You can do this in two ways. You can type code directly into the browser's built-in console for instant results. Or, you can attach a JavaScript file (ending in `.js`) to a website's HTML code so it runs when the webpage loads.
    
*   **On the Server:** First, you have to download and install a tool like Node.js on your computer. Once installed, you can type code line-by-line into your computer's terminal (like a command prompt) to see it work instantly. Alternatively, you can save your code in a `.js` file and tell your computer to run the whole file by typing a command like `node filename.js`.
    

* * *

## Understanding Variables

### What is Variables

A variable is like a labeled container used to hold items. When you declare a variable, you are creating this container and putting a label on it so you know what kind of data you are storing inside.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/cb085618-eb9e-48a9-b22e-3dae5127b820.png align="center")

### Variable Declaration with `var`

`var` is the old way of creating variables in JavaScript. With `var`, you can change the value of your variable at any time, and you can even create a completely new variable with the exact same name without the program crashing. However, because it can cause confusing and unpredictable bugs, developers are advised not to use it anymore.

```javascript
// 1. Using the variable BEFORE it is declared
console.log(myName); // Output: undefined

// 2. Declaring the variable with 'var'
var myName = "Anoop";
console.log(myName); // Output: "Anoop"

// 3. Re-declaring the same variable name with 'var' (No crash!)
var myName = "Sumit";
console.log(myName); // Output: "Sumit"
```

### Variable Declaration with `let` & `const`

Both `let` and `const` are the modern, safer ways to create variables in JavaScript. Unlike the older `var` method, both of these will protect your code from bugs by throwing an error if you accidentally try to create two variables with the exact same name.

The main difference between them is whether the data inside is allowed to change:

*   **Use** `let` when you know the value will change later in your program. You can create the container empty and update the data inside it whenever you need to.
    
*   **Use** `const` for containers whose contents must *never* change. When you create a `const` variable, you must put something inside it immediately, and you can never replace or update those contents.
    

```javascript
// Declaring with 'let' (Value can change)
let currentScore = 10;
console.log(currentScore); // Output: 10

// Reassigning is allowed
currentScore = 15; 
console.log(currentScore); // Output: 15

// Redeclaring the SAME variable throws an error!
// let currentScore = 20; // UNCOMMENT TO SEE: SyntaxError: Identifier 'currentScore' has already been declared

// Declaring with 'const' (Value is locked)
const maximumScore = 100;
console.log(maximumScore); // Output: 100

// Reassigning is NOT allowed
// maximumScore = 150; // UNCOMMENT TO SEE: TypeError: Assignment to constant variable.

// Must be initialized immediately
// const minimumScore; // UNCOMMENT TO SEE: SyntaxError: Missing initializer in const declaration
```

### Identifier Naming Rules

JavaScript follow strict rules for creating variables or identifiers. For naming variables you must need to follow these rules unless you gets errors.

*   **Accepted Characters**: You can use letters, number, underscore `_`, and dollar symbols `&` only.
    
*   **Starting Character**: You cannot start names with numbers.
    
*   **Case Sensitive**: JavaScript is case sensitive means names like `username`, `Username`, and `USERNAME` are treated as different names.
    
*   **Reserve Keywords**: You cannot use keywords already used by JavaScript like `for`, `let`, `class`, `function` etc.
    

There are some best practises for naming followed by developers. If your not following these rules it will not giving any error.

*   **Descriptive Name**: Always use name which provide description like `userName`, `isLoggedin`, `protectedRoute` etc.
    
*   **Naming conventions**: Use naming conventions like camelCase, and PascalCase.
    

* * *

## All About Data Types

Latest ECMAscript standards dictates that JavaScript contains exactly eight types of data divided into seven primitives and one non-primitive. JavaScript is a dynamically typed language which means one variables can hold any type of data in their entire life cycle without explicit type declaration.

### Primitives Data Types

Primitives are the most basic data types in the JavaScript. These are the immutable means you can not alter them.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/bc7897ce-a446-49b3-aa15-813ed8e9e976.png align="center")

#### 1\. String

If you need to store text inside your variable you need to put it inside single or double quotes. It tells JS that you want to work with textual data. In ES6 new way of creating JS was introduced with back ticks which allow to span string into multiple lines or insert variable directly into string.

```javascript
// 1. Normal String using singel or double quotes
let simpleWord = 'Hello';
let name = "Alice";

// 2. Template Literals using backticks
let templateWord = `Hello`;

// Difference 1: Multi-line Text
// Normal strings require a special character (\n) to create a new line.
let normalMultiLine = "This is line one.\nThis is line two.";

// Template literals respect physical line breaks. You just press Enter.
let templateMultiLine = `This is line one.
This is line two.`;

// Difference B: Putting Variables Inside Text (Interpolation)
// Template literals use ${} to securely inject another variable right into the sentence.
const name = "Anoop"
let welcomeMessage = `Hello ${name}, welcome to the team!`;
```

#### 2\. Number

JavaScript treat any integer or fractional numbers as Number Datatype. JavaScript also consider these three values `+Infinity`, `-Infinity`, and `NaN` (Not a Number) as number.

```javascript
// 1. Standard Numbers (Integers and Floating-Point)
const integerValue = 42;
const floatValue = 3.14159;

// 2. Special Numbers Values
const positiveInf = Infinity;
const negativeInf = -Infinity;
const nan = NaN
```

#### 3\. Bigint

Used for handling numbers exceeding the maximum safe integer range. You can create big int number by appending `n` at end of integer like `43n`.

```javascript
// Creating BigInts
const bigIntLiteral = 9007199254740991n;

// Pro-tip: Pass large numbers as strings to the constructor to avoid precision loss before creation
const bigIntConstructor = BigInt("90071992547409923456789");
```

#### 4\. Boolean

It represents a logical entity with exactly two possible values: `true` and `false`.

```javascript
const isUserLoggedIn = true;
const isPremiumMember = false;
```

#### 5\. Undefined

It is a special value used in JavaScript for representing absence of value by the JavaScript. When ever you are not assigning a value to variable JavaScript automatically assigned `undefined` value to it.

```javascript
// When a variable is declared but not assigned a value, JS implicitly assigns it 'undefined'.
let userEmail;
console.log(userEmail); // undefined
```

#### 6\. Null

It is also a special value used like `undefined` representing absence of value. But it used by the developer to assign variable when they wants to mark variable empty.

```javascript
// We assign null to explicitly say: "This variable is meant to hold an object/value, 
// but it is currently intentionally empty."
let currentUser = null; 
```

#### 7\. Symbol

It use used for represent guaranteed unique values - means when you create symbol it guaranteed that it always generate unique values. You an not create symbol directly you need to use `Symbol()` method.

```javascript
const sym1 = Symbol();
const sym2 = Symbol("id"); // "id" is the description
const sym3 = Symbol("id");
```

### Non Primitive Data Types

Non primitives are used to represent complex data structures by using primitives data types. These are mutable means you can alter them easily.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/4f36b7c7-d2a1-4cee-96cb-9a6920dc4169.png align="center")

#### 1\. Object

It can be created using key value pairs where key must be string and values can be any data types. Object can contain nested object also. You can create objects by wrap these key value pairs with curly braces `{}`.

```javascript
// Creating an Object (Using Object Literal syntax)
const developer = {
    firstName: "Sarah",
    role: "Frontend Engineer",
}

// Accessing Properties
console.log(developer.role);           // Dot notation (Standard and preferred)
console.log(developer["firstName"]);   // Bracket notation (Used for dynamic keys)

// Modifying and Adding Properties
developer.role = "Senior Engineer";    // Updating an existing property
developer.location = "Remote";         // Adding a brand new property
```

#### 2\. Array

It is another complex data structure used to store multiple values in a singe ordered list. A common way to creating array using square bracket `[]` and placing comma separated values. It allows to access these values using indices (start from 0) with square bracket following by variable name.

```javascript
// Creating an Array (Array Literal Syntax)
const techStack = ["JavaScript", "React", "Node.js"];

// Mixed Data Types
// Unlike strictly typed languages, JS arrays can hold any mix of values.
const mixedArray = [42, "Hello", true, { name: "Alice" }, [1, 2, 3]];

// Accessing Elements (Zero-based indexing)
console.log(techStack[0]); // "JavaScript" (First element)
console.log(techStack[techStack.length - 1]); // "Node.js" (Last element)

// Modifying Elements and Size
techStack[1] = "TypeScript"; // Replaces "React" with "TypeScript"
techStack.push("GraphQL");   // Adds a new element to the end of the array
console.log(techStack.length); // 4
```

#### 3\. Function

In JavaScript, a function is a special type of data. Just like you can store a String or a Number inside a variable, **you can store an entire function inside a variable**. Because JavaScript treats functions as regular values, you can pass them around in your code, give them to other functions, or save them to use later.

```javascript
// Normal Data Types (Strings and Numbers)
let myName = "Alice";
let myAge = 25;

// Function as a Data Type
// Look carefully! We are storing the function INSIDE a variable, 
// exactly like we did with the string and number above.
let sayHello = function() {
    console.log("Hello there!");
};

// Using the data
// We call the variable name and add () to run the code stored inside it.
sayHello(); // Outputs: "Hello there!"
```

* * *

## Operators and Expressions

### Conditional Operator

It is also known as Ternary Operator because it accepts three operands. Those three operands are separated using two distinct symbols `?` and `:`.

*   **The Condition** It is the first operand evaluated as boolean and that value decides which operand is returned.
    
*   **Expression if True**: The second operand is returned when condition evaluates to `true`.
    
*   **Expression if False**: The last operand is returned when condition evaluates to `false`.
    

```javascript
const userAge = 20;

// The entire expression evaluates and simplifies to a single string value
const admissionStatus = (userAge >= 18) ? "Allowed Entry" : "Access Denied";

console.log(admissionStatus); // Outputs: "Allowed Entry"
```

### Unary Operators

It performs an action on exactly one variable or values. The core Unary operators are:

#### 1\. Unary Plus `(+)` and Negation `(-)`

Those used to represent negative or positive number values. Unary plus operator also used to convert any string or boolean values to its corresponding number values.

```javascript
console.log(+"43") // 43
console.log(-"4343") // -4343
console.log(+true) // 1
console.log(-false) // -0
console.log(+"hello") // NaN
```

#### 2\. Increment `(++)` and Decrement `(--)`

Use to increment or decrement provided values by 1. These are used in to way with numbers. As prefix - putting before to the number changes the value first then return it. As postfix = putting after the number return it first then change the value.

```javascript
let a = 5;
let b = ++a;
console.log(a, b) // a becomes 6, b gets 6 (Prefix)

let x = 5;
let y = x--;
console.log(x, y) // y gets 5, x then becomes 6 (Postfix)
```

#### 3\. Logical Not `(!)` or Double Not `(!!)`

Those are use to flip the boolean type or forcefully convert any data type to its raw boolean form. Logical Not - flip once or convert any data to its flipped boolean form. Double Not - flip twice or convert any data to its correct boolean form.

```javascript
console.log(!true) // false
console.log(!!false) // false

console.log(!"any") // false
console.log(!"any") // true
```

#### 4\. `typeof` and `delete`

*   `typeof` operator evaluates data type of any value or variables and return it as string.
    
*   `delete` operator delete object keys permanently.
    

```javascript
const car = { make: "Ford", model: "Mustang" };
console.log(typeof car) // "object"

delete car.model;
console.log(car) // // car is now just { make: "Ford" }
```

### Arithmetic Operators

These operators used to perform basic mathematical operations.

#### 1\. `(+)` Addition

Perform the sum operation between two numbers.

```javascript
let sum = 10 + 5;
console.log("Addition (10 + 5):", sum); // Output: 15
```

#### 2\. `(-)` Subtraction

Find the difference between two numbers.

```javascript
let difference = 10 - 5;
console.log("Subtraction (10 - 5):", difference); // Output: 5
```

#### 3\. `(*)` Multiplication

Multiply first number with second number.

```javascript
let product = 10 * 5;
console.log("Multiplication (10 * 5):", product); // Output: 50
```

#### 4\. `(/)` Division

Divide first number with second and return the division of them. It can returns floating points if necessary.

```javascript
let quotient = 10 / 4;
console.log("Division (10 / 4):", quotient); // Output: 2.5
```

#### 5\. `(%)` Modulo or Remainder

Returns the remainder left over after performing the division.

```javascript
let remainder = 10 % 3;
console.log("Modulus (10 % 3):", remainder); // Output: 1 (3 goes into 10 three times, 1 left over)
```

#### 6\. `(**)` Exponentiation

Raise the first operand to the power of the second operand.

```javascript
let power = 2 ** 3;
console.log("Exponentiation (2 ** 3):", power); // Output: 8 (2 * 2 * 2)
```

### Assignment Operators

These operators used to assign or update values stored into the variables.

#### 1\. `(=)` Assignment

Assign right side value to the left side variable.

```javascript
let x = 10;
console.log("Assignment:", x); // Output: 10
```

#### 2\. `(+=)` Addition Assignment

Adds right side value to the value stored in left side variable and reassign it into.

```javascript
let a = 10;
a += 5; // Equivalent to: a = a + 5
console.log("Addition Assignment:", a); // Output: 15
```

#### 3\. `(-=)` Subtraction Assignment

Find the difference between right side value and value stored in left side variable. Reassign this difference back to the variable.

```javascript
let b = 10;
b -= 3; // Equivalent to: b = b - 3
console.log("Subtraction Assignment:", b); // Output: 7
```

#### 4\. `(*=)` Multiplication Assignment

Multiply right side value with value stored in left side variable and reassign it into.

```javascript
let c = 10;
c *= 2; // Equivalent to: c = c * 2
console.log("Multiplication Assignment:", c); // Output: 20
```

#### 5\. `(/=)` Division Assignment

Divide value stored in variable by the right side value and reassign the result.

```javascript
let d = 10;
d /= 4; // Equivalent to: d = d / 4
console.log("Division Assignment:", d); // Output: 2.5
```

### Comparison Operators

These operators used to perform comparison between tow operands and always results boolean values.

#### 1\. `(==)` Loose Equality

It compare two values by their equality. It returns `true` if the values are equal, otherwise returns `false`. If the values are of different data type then one or both are automatically converted one or both into common data type before comparing.

```javascript
console.log(5 == "5");   // true  (string "5" converts to number 5)
console.log(10 == 10);   // true 
console.log(5 == 6);    // false
```

#### 2\. `(===)` Strict Equality

It compares two values for its strict equality by ensuring both the data type and values are exactly same. It returns `true` if the both values identical in value and types, otherwise returns `false`.

```javascript
console.log(5 === "5");  // false (different data types: number vs string)
console.log(5 === 5);    // true  (same type and value)
```

#### 3\. `(!=)` Loose Inequality

It compare two values for its inequality. It returns `true` if values are not equal, otherwise return `false`. If the values are different data types the it automatically converts one or both into common data type before comparing.

```javascript
console.log(5 != "5");   // false (coerced values are identical)
console.log(5 != 6);     // true  (values are different)
```

#### 4\. `(!==)` Strict Equality

It compares two values for its inequality by ensuring both values and type are evaluated. It returns `true` if the both values are different in either value or type, otherwise it returns `false`.

```javascript
console.log(5 !== "5");  // true  (types are different)
console.log(5 !== 5);    // false (both value and type are identical)
```

#### 5\. `(>)` Greater Than

It returns `true` if left side value is greater to the right side value, otherwise it return `false`.

```javascript
console.log(10 > 5);     // true 
console.log(5 > 10);     // false
console.log(5 > 5);      // false
```

#### 6\. `(<)` Less Than

It return `true` if the left side value is lesser to the right side value, otherwise it return `false`.

```javascript
console.log(3 < 8);      // true  
console.log(8 < 3);      // false 
console.log(3 < 3);      // false
```

#### 7\. `(>=)` Greater Than and Equal To

It returns `true` if the left side value is greater or equal to the right side value, otherwise it return `false`.

```javascript
console.log(10 >= 5);    // true  
console.log(5 >= 5);     // true 
console.log(2 >= 5);     // false
```

#### 8\. `(<=)` Less Than and Equal To

It return `true` if the left side value is lesser or equal to the right side value, otherwise it returns `false`

```javascript
console.log(4 <= 9);     // true  
console.log(4 <= 4);     // true 
console.log(9 <= 4);     // false 
```

### String Operators

These are used to combine and manipulate text values. The most common string operators are String Concatenation and Assignment Concatenation operators.

#### 1\. `(+)` String Concatenation

It use to merge two or more string values and returns a single combined string value.

```javascript
let greeting = "Hello, " + "World!"; 
console.log(greeting); // Outputs: "Hello, World!"
```

#### 2\. `(+=)` Assignment String Concatenation

It is the shorthand of add a string on the end of the existing string variable.

```javascript
let message = "JavaScript is ";
message += "awesome!"; 
console.log(message); // Outputs: "JavaScript is awesome!"
```

### Logical Operators

These operators are used to combine or modify boolean values and control the flow of the program.

#### 1\. `(&&)` Logical AND

Returns `true` only if the both operands are `true`. Either operands are `false` it returns `false`.

```javascript
console.log(true && true) // true
console.log(false && true) // false

const userHasPaid = true;

userHasPaid && console.log("Premium access unlocked."); 
// Outputs: Premium access unlocked.
```

#### 2\. `(||)` Logical OR

Returns `true` if at least one of the operands are `true`. It only return `false` if both operands are `false`.

```javascript
console.log(true || false) // true
console.log(false || false) // false

const savedUsername = ""; // Falsy value

const displayName = savedUsername || "Guest";
console.log(displayName)
```

#### 3\. `(!)` Logical NOT

Invert the boolean values, it turn `true` into `false` and `false` into `true`.

```javascript
console.log(!true) // false
console.log(!false) // true

const searchResults = ["item1", "item2"];

const hasResults = !!searchResults.length;
console.log(hasResults); 
```

#### 4\. `(??)` Nullish Coalescing

It returns the right hand side operand if the left hand side operand is either `null` or `undefined`, otherwise it return left hand side operand.

```javascript
const userVolumeSetting = 0; // 0 is a valid setting, but falsy

const finalVolume = userVolumeSetting ?? 50;
console.log(finalVolume); // 0
```

### Expressions

A piece of code which evaluated into a single value is an expression. Every time you are combining variables, values, and operators you are creating a expression.

In JavaScript operands are evaluated from left to right side. Every operators inside expression are follow BODMAS Rule.

An Expression must have two types of items, operators and operands:

```javascript
// Anatomy of Expression
// Operand    Operator    Operand    Evaluation
      10         +           20           30
    "5055"       +           10         505510
      100        -         "1000"        -900
```

* * *

## Type Casting

When one type of data is converted into another type which is called type casting or conversion. JavaScript handle it in two ways implicit and explicit.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/c2f8c9e2-134f-4a34-bbe1-8b44ee2bf73b.png align="center")

### **Implicit Type Casting (Type Coercion)**

JavaScript is so forgiving language, when you give expression with mismatched data types. JavaScript automatically convert to same types to make sense. This self converting called implicit type casting or type coercion.

#### Coercion to String

When using addition operator `+` and expression have string type operand. Instead of performing addition it perform concatenation between operands by implicit type casting other types into string.

```javascript
console.log("100" + 10 ) // 10010
console.log(10 + 20 + "20" ) // 3020 -> 30 + "20"
```

#### Coercion to Number

using other arithmetic operator excluding addition `+` converting mismatched values into `number` and perform operations. If value is not a valid number like "hello" it will converted into `NaN`.

```javascript
console.log("100" - 20);        // 80
console.log("50" * 2 - 50);    // 50
console.log("20" * 10 + 50);   // 250
console.log("hello" * 10);     // NaN
```

#### Coercion to Loos Equality

comparing different values using loos equality operator `==` also result after implicit type casting.

```javascript
console.log(50 == "50");        // true
console.log(false != "true");   // true
```

### **Explicit Type Casting (Type Conversion)**

Explicit type casting is performed by the developers using some builtin methods provided by the JavaScript itself.

#### Conversion to String

Use `String()` or `toString()` built in methods to convert other types into string.

```javascript
console.log(String(550));       // "550"
console.log(false.toString());  // "false"
```

#### Conversion to Number

Use `Number()`, `parseInt()` or `parseFloat()` methods to perform explicit `number` conversion.

```javascript
console.log(Number("440"));         // 440
console.log(parseInt(true));        // NaN (Note: JavaScript parseInt(true) actually returns NaN, not 1)
console.log(parseInt("hello"));     // NaN
console.log(parseInt(433.33343));   // 433
```

#### Conversion to Boolean

Use `Boolean()` to determine truthy and falsy values. Values whose boolean conversion are `true` which are truthy and whose conversion are `false` is falsy values. There are some limited falsy values remains are truthy values.

**Falsy Values are**: `false 0 -0 0n null undefined "" NaN`

```javascript
console.log(Boolean(null));          // false
console.log(Boolean(""));            // false
console.log(Boolean("hello world")); // true
console.log(Boolean(2005));          // true
```

* * *

## Conditional Statements

By default JavaScript has top to bottom control flow. Means every program start executing from top and end at bottom. Conditional statements are provide a way to execute a certain block of code based on specific conditions evaluated which evaluated into `true`.

### `if...else` Statements

There are three keywords we used to write conditional statements `if`, `else if` and, `else`. In which `if` can be used alone but `else if` and `else` need to used with `if` unless code throw Syntax Error.

With `if` we put condition expression within parentheses `(condition)` which determine whether or not to execute code block wrapped by curly braces `{code block}`

```javascript
let profileCompletion = 100;

if (profileCompletion === 100) {
    console.log("Profile setup is complete!");
}

// "Profile setup is complete!" printed on the console when the profileCompletion === 100 evaluated into the true.
```

If you want to execute a code block on every time when `if` code block is not executed. You need to add `else` statement beneath `if` statement. Keep remember `else` cannot be use alone it needed to use with `if` statement.

```javascript
et cartTotal = 45;
let accountBalance = 30;

if (accountBalance >= cartTotal) {
    console.log("Transaction successful.");
} else {
    console.log("Insufficient funds. Please top up your balance.");
}

// else block is executed and "Insufficient funds. Please top up your balance." printed on the screen when the if block is not executed.
```

Whenever you needed to check multiple conditions and executed different code blocks based on these conditions. You need to use `else if` ladder. It is used between `if` and `else` statements, you can used as many as you needed `else if` statements. But keep remember it can not be used alone or after the `else` statements. Like `if` statement, `else if` also required a conditions.

```javascript
let speed = 75;

if (speed > 80) {
    console.log("Reckless driving! Heavy fine applies.");
} else if (speed > 60) {
    console.log("Speeding. Moderate fine applies.");
} else if (speed >= 40) {
    console.log("Driving at a safe, legal speed.");
} else {
    console.log("Driving too slow for the highway flow.");
}

// First else if block executed when speed > 60 evaluated into true after the if block falls. Second else if block executed when speed >= 40 evaluated into true after the first else if block fails. else block is executed when both else if blocks are fails.
```

### `switch...case` Statements

`switch` use a single condition or value to match against list of exact target values. Each target value called `case`, every `case` have code blocks which executed if `case` matched. After one matching control directly move to the next `case` if their `break` keyword not used.

> `break` keyword used inside the `case` to move the control bellow the entire `switch` statement.

If you want to execute a certain block of code if any of them `case` not matched. You need to use `default` keyword which act like a `else` block.

```javascript
let trafficLight = "yellow";

switch (trafficLight) {
  case "red":
    console.log("Stop immediately.");
    break;
  case "yellow":
    console.log("Prepare to stop.");
    break;
  case "green":
    console.log("Proceed or continue driving.");
    break;
  default:
    console.log("Invalid traffic light color.");
}

// Output: Prepare to stop.
```

* * *

## Loops and Iterations

Loops are used to repeatedly executes program by using certain condition. A single execution flow in the loop is an iteration.

### `for` Loop

This loop is used when you know the number of iterations needed to perform. It use initialisation, condition and the condition updates in a single raw separated by semicolon `;`.

```javascript
for (let i = 1; i <= 5; i++) {
  console.log("Iteration number: " + i);
}

/* Execution Flow:
1. initialisation let i = 1 are performed at once.

2. condition i <= 5 is checked every time before the code block execution.

3. condition update (increment) i++ is performed every time just after the code execution.
*/
```

### `while` Loop

This is used when you do not know the number of iterations. In that you need to manually handle condition updates and initialisation. Handling conditions updates in wrong way leads trapped in infinite loop.

```javascript
let i = 1;

while (i <= 5) {
  console.log("Iteration number: " + i);
  i++;
}

/* Execution Flow:

1. Condition initialisation handled manually let i = 1 once before loop.

2. Condition updates handled manually i++ in own order but within loop only.

3. Condition checks every times after the code execution.

*/
```

### `do...while` Loop

It's kind of `while` loop but its a exit controlled loop. In there code block is executed before the condition check, which means it allow code block to execute without checking the condition once at the beginning. It preferred to use when you needed the code must be run at least once.

```javascript
let i = 1;

do {
  console.log("Iteration number: " + i);
  i++;
} while (i <= 5);

/* Execution Flow:

1. condition variable initialised once before the loop let i = 1

2. code executed and condition updates

3. condition checks every times after code execution
*/
```

### `break` and `continue` Keywords

JavaScript provides a built-in keywords to alter the execution flow of loop by stopping entire loop or skipping single iteration it.

#### `break` Keyword

When ever loop encounter `break` keyword it terminate loop instantly and move the control to beneath the loops statement.

```javascript
for (let i = 1; i <= 10; i++) {
  if (i === 6) {
    break; // Stops the loop immediately
  }
  console.log("Iteration number: " + i);
}
```

#### `continue` Keyword

When `continue` keyword encountered within the loop it stops the rest of the code execution within current iteration and move the control to next iteration without stopping the entire loop.

```javascript
let i = 1;

while (i <= 5) {
  if (i === 3) {
    continue; // Skips the rest of this iteration
  }
  console.log("Iteration number: " + i);
  i++;
}
```

### `for...of` Loop

It is used for iterate over the iterable objects. It provide a direct access to each value in the sequence without needing a index counter. It is a good option for iterating over array, string, map or other iterable data structures.

```javascript
const fruits = ['apple', 'banana', 'orange'];

for (const fruit of fruits) {
    console.log(fruit); 
}
// Output:
// apple
// banana
// orange
```

### `for...in` Loop

It is designed for iterating over the attributes (key) on an Objects.

```javascript
const user = { name: 'Alice', age: 25, role: 'Admin' };

for (const key in user) {
    console.log(`${key}: ${user[key]}`); // Access value via bracket notation
}
// Output:
// name: Alice
// age: 25
// role: Admin
```

* * *

## All About Functions

Functions are the block of code used to perform a specific task. It make you to write code once and use it anywhere. It make you programs organized, efficient and easier to debug.

### Function Declaration

It is a traditional way of creating a function it tells JavaScript about function name, its parameters and code it should executes.

To declare function, you use `function` keyword following by name you want to give it. A sets of parentheses and curly brace contains code block.

```javascript
function greetUser() {
  console.log("Hello, welcome to our website!");
}

// Calling (or invoking) the function
greetUser(); // Output: Hello, welcome to our website!
```

#### Parameters Or Arguments

Parameters are the placeholder variable created inside parentheses of the function declaration. It holds the values you passed when you call it. You can define as many parameters as you want.

Arguments are the actual values you passed to function during function call.

```javascript
// 'firstName' and 'lastName' are parameters
function greetPersonalized(firstName, lastName) {
  console.log("Hello " + firstName + " " + lastName + "!");
}

// "John" and "Doe" are the arguments passed into the parameters
greetPersonalized("John", "Doe"); // Output: Hello John Doe!
greetPersonalized("Jane", "Smith"); // Output: Hello Jane Smith!
```

#### `return` keyword

While `console.log()` was a good for printing output, but functions need to be returned values to rest of the code so it can be used later.

`return` keyword perform two task. It returns the result of the function back to location where it is called and immediately stop the function execution. The code defined after the `return` keyword never executed.

```javascript
function addNumbers(num1, num2) {
  let sum = num1 + num2;
  return sum; // Sends the value of 'sum' back to the caller
  
  console.log("This will never print because it is after the return keyword.");
}

// We can store the returned value in a variable
let total = addNumbers(5, 10);
console.log("The total is: " + total); // Output: The total is: 15
```

### Default & Rest Parameters

Default parameters and Rest parameters are the modern features which makes the function highly flexible in input handling.

#### Default Parameters

It allow to define a default values of the parameters in declaration. When any argument are not passed the default value assigned to it. Default values are only triggers when arguments are missing or explicitly `undefined` is passed.

```javascript
// Setting a default value of "Guest" for the name parameter
function welcomeUser(name = "Guest") {
    return `Hello, ${name}!`;
}

console.log(welcomeUser("Alice")); // Hello, Alice!
console.log(welcomeUser());        // Hello, Guest!

// Best practice: Always use default parameters at the end of parameters list.
```

#### Rest Parameters

It allow you to create a function handle any numbers of arguments. It created by just putting `...` dots (rest operator) in front of parameter name. It automatically collect all these arguments within parameter variable as array.

You can only use rest parameter as either as single parameter or at the end of parameter list.

```javascript
// Gathering all passed numbers into an array named 'numbers'
function sumAll(...numbers) {
    let total = 0;
    for (let num of numbers) {
        total += num;
    }
    return total;
}

console.log(sumAll(1, 2));       // 3
console.log(sumAll(1, 2, 3, 4)); // 10

// You can use it for collecting all remaining arguments by just putting at the end of the arguments list. Keep remember you can only use one rest parameter with in a function.
```

### Function Expression and Anonymous Function

#### Function Expression

It allow to store functions within a variable and use it as a first class object means you can use it like other normal variables calling it later using variable name, passing or returning as value to functions.

```javascript
// This whole line is a function expression
const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(3, 4)); // 12
```

#### Anonymous Function

When function created without name its called anonymous function. Generally it stored into variables so we can use it later. Keep remember you can not declare anonymous function as standalone function.

```javascript
// The part to the right of the "=" is the anonymous function
function() {
  console.log("I have no name!");
}
```

### Arrow Function

It is the modern alternative of the traditional function expression introduced at ES6 2015 version of JavaScript. It is little bit a different to the traditional functions in handling scopes (learning later) and `this` binding.

#### 1\. With Parentheses

Parentheses and curly braces are used.

```javascript
const sum = (a, b)=>{ return a + b}

console.log(sum(5, 10)) // 15
```

#### 2\. Implicit Return

when function body is to short like inline expression then you can remove the curly braces and `return` keyword.

```javascript
const sum = (a, b)=> a + b

console.log(sum(5, 10)) // 15
```

#### 3\. Without Parentheses

you can also remove the parentheses if there are only single parameter.

```javascript
const square = a => a**2

console.log(square(2)) // 4
```

#### 4\. Without Parameters

if there are no parameters then adding empty parentheses is necessary.

```javascript
const greet = ()=> "Hello Ji"

console.log(greet()) // Hello Ji
```

#### 5\. With Objects

when you want to return a object without `return` keyword. You need to wrap the whole object within parentheses. So the JavaScript not confuse with Object curly braces as function body.

```javascript
const getUser = ()=>({name: "Anoop", role: "dev"})

console.log(getUser()) // {name: "Anoop", role: "dev"}
```

### **IIFEs (Immediately Invoked Function Expressions)**

As its named describe, in JavaScript IFFEs are automatically executed just after its definition. It used avoid to global namespace pollution.

The structure of IIFEs are made using two pairs of parentheses. First pair used to making function definition expression and second pair is used to immediately invoke function.

```javascript
// Creating with Normal Function
// Douglas Crockford’s Syntax

(function() {
    console.log("Crockford style");
}());

// Creatig with Arrow Function

(() => {
    console.log("Arrow IIFE runs!");
})();
```

* * *

## Scopes and Hoisting

In JavaScript scopes are the area where variables and function lives, Hoisting is the mechanism of allocating memory to declaration before execution process.

### Scopes

There are major three types of scopes JavaScript uses for controlling variables and function visibility and accessibility within a program.

#### 1\. Global Scope

Variable and Function visible to every where inside your script is global scoped. Declaring variables and functions outside of any function and block are global scoped.

```javascript
const globalVar = "i'm global variable"

console.log(globalVar) // i'm global variable

if(true){
    console.log(globalVar)
}

function testScope(){
console.log(globalVar)
}

tetScope()
```

#### 2\. Function Scope

Variable and function only accessible inside a function which is function scoped. Declaring variable with `var` keyword is function scoped.

```javascript
function testScope(){
    var funVar = "i'm function scoped variable"
}

console.log(funVar) // Error
```

#### 3\. Block Scope

Variable and function only accessible inside a curly braces `{}` block which is block scoped. Declaring variable and function with `let` and `const` are block scoped.

```javascript
if(true){
const blockVar = "i'm block scoped variable"
console.log(blockVar)
}

console.log(blockVar) // Error
```

### Hoisting

It is the mechanism in the JavaScript where it allocates the memory for the variables and function declarations. JavaScript executes code in two phases:

1.  Scanning Phase: In that phase it allocate memory for the declared variables (not assignments) and stores functions in memory.
    
2.  Execution Phase: In that phase it actually executes code.
    

Remember that assigning value to variables and calling functions are part of Execution Phase.

#### 1\. Hoisting with `var`

Variables declared with `var` hoisted with `undefined` value, that is why accessing `var` variable before its declaration gives `undefined` value.

```javascript
console.log(greet) // undefined

var greet = "Hello sir"

console.log(greet) // Hello sir
```

#### 2\. Hoisting with `let` and `const`

Variables declared with `let` and `const` also hoisted with `undefined` But these are moved to the restricted area called Temporal Dead Zone (TDZ) to prevent early access. That is why accessing these variable before its declaration throws error.

```javascript
console.log(roll, name) // error

const roll = 48304803
const name = "anoop"

console.log(roll, name) // 48304803 anoop
```

#### 3\. Hoisting with Function

Function declared with `function` keyword are also hoisted so you can also access them before its actual declaration.

```javascript
greet("anoop")

function greet (name) {

console.log("Hello" + name)

}
```

#### 4\. Hoisting with Function Expression

Function expressions are not hoisted which means if you try to call arrow function or function which is assigned to variable also gives error.

```javascript
sayHi() // Error
sayGoodBy("anoop") // Error

const sayHi = ()=>console.log("Hi User")

const sayGoodBy = function (name){
console.log("Good By" + name)
}

sayHi() // Hi User
sayGoodBy("anoop") // Good By anoop
```

* * *

## Introduction to Exceptional Handling

Exceptional handling allow you to mange runtime errors with in a program so it runs smoothly without unexpected crashing. It allow to anticipate part of your code that might fails like wrong user input or broken network request and provides a way to executes fallback code.

*   `try` keyword used for defining a block contains code for try which might we fails.
    
*   `catch` keyword for the fallback code block executed when error occur in `try` block. Every error from try are directly available in it.
    
*   `finally` keyword create a block which executed every time when one of the above is executed. Commonly used for cleanup code.
    

Ensure any of these blocks can't used alone or wrong order. `try...catch` must used together but `finally` block is optional but always placed beneath of `catch` block.

`throw` keyword used to raise or create a custom errors.

```javascript
function checkAge(input){

try{
    console.log("Starting verification...");

    if(input < 0) throw Error("Input can not be negative")
    if(input > 100) throw Error("Invalid input")

    console.log("Access granted. Enjoy the site!");
} catch (error){

    // This code only runs if something goes wrong above
    console.error("Verification failed: " + error.message);

 } finally {

    // This code ALWAYS runs, no matter what
    console.log("Verification process finished.");

}

}


// Scenario 1: Triggers a custom error (Invalid input)
checkAge(101); 
// Output:
// Starting verification...
// Verification failed: Invalid input
// Verification process finished.

// Scenario 2: Runs perfectly
checkAge(21);
```

When error occur inside the `try` block the JavaScript create a Error Object with the occurred error and pass it to the `catch` block. You can simply access that Error Object within `catch` parameter. This error contains three major properties we need look:

*   `name`: it is the actual type of the error which occur like `TypeError`, `Reference Error` or base `Error`.
    
*   `message`: a human readable format which describe what the error is or why it occur.
    
*   `stack`: its generally known as stack traces its provide the detailed location of the error from where it raised or generated.
    

* * *

## Code Execution Flow

To understand how JavaScript code processed you need to understand how the JavaScript engine work.

### JavaScript Engine

JavaScript engine is a specialised program used for translating high level human understandable JavaScript text into low level code which computer understand and executes.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/c27a851a-efd0-4108-81ed-0f6897472fef.png align="center")

Each organisation created their own engine like:

*   V8 created by google to power chrome and chromium based browser like Edge.
    
*   SpiderMonkey created by mozilla for firefox.
    
*   JavaScriptCore created by Apple to power up safari browser.
    

To executes JavaScript code these engine use a hybrid process called JiT (Just In Time) compilation. To understand code execution flow you need to know its major components and what they do:

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/56380a1d-aa6d-4c7b-9bc7-8677c0e85ea7.png align="center")

1.  **Parser**: it reads the code and break down into small chunks called tokens. Then these tokens used to make a tree like structure called AST (Abstract Syntax Tree)
    
2.  **Interpreter**: it interpret that tree line by line and translate into low level machine code.
    
3.  **Profiler**: In the interpreting process the profiler monitors every code for the code which is repeated like loops or functions. It mark that repeated code as Hot Code when encounter.
    
4.  **Compiler**: When hot code marked which is transferred to compiler. It converts that code into a highly optimised machine code. It swapped with its hot code when it used again.
    

### Code Execution Flow

When JavaScript code converted into AST and hands on to the interpreter. The interpreter executes code into two phases

#### 1\. Memory Creation Phase

It is also known as variables environment phase because in that phase engine prepare and initialise memory for storing variables and functions.

This memory divided into two parts:

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/afb43c73-3c61-4f99-93c8-cee5924c802d.png align="center")

1.  **Stack Memory**: Because it is strictly ordered, fixed and fast in nature so it used for storing primitives and references pointed in heap.
    
2.  **Heap Memory**: Its unordered, dynamic and slow comparing to stack it like a big pool of memory. It used for storing complex data structures and functions.
    

After that, engine creates Global Execution Context - its like a block of memory inside a stack we called it Stack Frame. It is the entry point where the code execution starts.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/5b1aa5ff-e2e1-4265-b0c5-9e4db7963179.png align="center")

Then it scan the provided code and allocate a memory for the variables and functions. This process also known as Hoisting.

Variables containing primitives and function get stack memory from GEC Stack Frame. Non-primitives (complex data structures) get the memory from heap memory pool and its references stored into the GEC Stack Frame for accessing them.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/98deee12-3546-435e-9432-7fbc5dd26e1e.png align="center")

#### 2\. Code Execution Phase

In that phase, first it allocate a Main Execution Thread - its like a pointer which move from top to bottom on code and execute them line by line. To the Global Execution Context. From their Main Execution Thread starts executing code from top to bottom.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/03913404-3ad7-41d9-8d0a-e02b48e73ff1.png align="center")

When the Execution Thread encounter the variable assignments it stores value to memory. For functions or primitives values it stored them into the current Execution Context Stack Frame memory. Non primitive data structures are stored into the Heap Memory Pool and its references stored into the current Execution Context Stack Frame memory.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/f8ff8b2d-0f02-4049-9b76-273126eb4f83.png align="center")

Whenever it encounter the function call. It create a new Execution Context known as Function (Local) Execution Context and put it top of the Global Execution Context in the Stack.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/ff1d0e82-7fb9-45ca-ac6a-9fec562159e2.png align="center")

The Memory creation and Execution Phase repeated for that also. But it use the already initialised Stack & Heap Memory and Main Execution Thread, not initialised new one. Then Execution Thread move to that Context and execute its code line by line. When `return` Keyword encountered It stops execution and jump back to the place previous location with returned value.

After the return the whole Stack Frame for that Execution Context is wiped out from the memory with its variables, if not reachable.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/9b2c72e5-15b8-429f-b57d-f442c6c072b0.png align="center")

If multiple function are called the new Function Execution Context is created for each function. These placed into the stack memory in LIFO (Last in First Out) order. The Main Thread follow the function calls and its resolution flow.

![](https://cdn.hashnode.com/uploads/covers/69b0e9bfabc0d95001c1bb23/f5d7708d-174a-47a9-8eaa-1028d44f531a.png align="center")

When the Global Execution Context Frame is completely executed. The all data is deleted from memory and acquired memory released for other application uses.

* * *
