0% found this document useful (0 votes)
2K views

Documentation: Interpreted Language Client-Side Language

Uploaded by

sehan3061
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

Documentation: Interpreted Language Client-Side Language

Uploaded by

sehan3061
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

31 August 2024

Documentation

(note:this link may get updaded in future)

JavaScript is a high-level, dynamic programming language commonly used for creating


interactive effects within web browsers. It is one of the core technologies of the World Wide
Web, alongside HTML and CSS, and allows developers to build complex features on websites,
including interactive forms, animations, and real-time content updates.

Here are some key characteristics of JavaScript:

1. Interpreted Language: JavaScript code is executed by the browser's JavaScript engine,


typically without needing a prior compilation step.

2. Client-Side Language: JavaScript is primarily used on the client side (i.e., within a
user's web browser), although it can also be used on the server side through
environments like Node.js.

3. Event-Driven: JavaScript code often responds to user actions (like clicks or keystrokes)
or other events (like page loading or timers).

4. Dynamic Typing: Variables in JavaScript are not bound to a specific data type, which
allows for greater flexibility but also requires careful management of data types.

5. Prototype-Based Object Orientation: JavaScript uses prototypes instead of classical


inheritance models, which means that objects can directly inherit from other objects.

6. Cross-Platform: JavaScript code can run on almost any device that has a web browser,
making it a versatile language for web development.

7. Highly Popular: JavaScript is one of the most widely used programming languages in
the world, with a large community and a wealth of libraries and frameworks (like
React.js, Angular, and Vue.js) that extend its capabilities.

JavaScript is essential for modern web development, enabling the creation of dynamic and
interactive web experiences.

VARIABLES:

In JavaScript, let, var, and const are all used to declare variables, but they differ in their behavior
and usage

1. var

• Definition: var is the oldest way to declare variables in JavaScript. It has been part of the
language since its inception.

• Scope: var is function-scoped, meaning it is only accessible within the function in which
it is declared. If declared outside any function, it becomes a global variable.
• Reassignment and Redeclaration: Variables declared with var can be reassigned and
redeclared within the same scope.

console.log(x); // undefined due to hoisting

var x = 10;

console.log(x); // 10

var x = 20; // Redeclaration is allowed

console.log(x); // 20

2. let

• Definition: let is used to declare block-scoped variables, meaning the variable is only
accessible within the block ({}) where it is defined.

• Scope: let is block-scoped. This means it is only accessible within the block, statement,
or expression where it is used

• Reassignment and Redeclaration: Variables declared with let can be reassigned but
cannot be redeclared within the same scope.

console.log(y); // ReferenceError: Cannot access 'y' before initialization

let y = 10;

console.log(y); // 10

y = 20; // Reassignment is allowed

console.log(y); // 20

let y = 30; // SyntaxError: Identifier 'y' has already been declared

3. const

• Definition: const is used to declare variables that are constant, meaning their values
cannot be reassigned once set.

• Scope: Like let, const is block-scoped.

• Reassignment and Redeclaration: Variables declared with const cannot be reassigned


or redeclared. However, if the const variable is an object or array, its properties or
elements can be modified.
console.log(z); // ReferenceError: Cannot access 'z' before initialization

const z = 10;

console.log(z); // 10

z = 20; // TypeError: Assignment to constant variable.

const obj = { a: 1 };

obj.a = 2; // Allowed because the object itself is not reassigned

console.log(obj.a); // 2

Summary

• var: Function-scoped, hoisted with undefined, can be redeclared and reassigned.

• let: Block-scoped, hoisted but not initialized, can be reassigned but not redeclared.

• const: Block-scoped, hoisted but not initialized, cannot be reassigned or redeclared


(although the contents of objects/arrays can be modified).

note:in JavaScript we can define a variables without required key world. But it was not
recommended to use

example:

input:

d = "cpp";

console.table(d);

output:

cpp

OUTPUT IN JAVASCRIPT:

• output in table:

The console.table() method in JavaScript is a useful way to display data in a table format in the
browser's developer console. It helps to visualize data structures like arrays and objects in a
more organized and readable manner.

console.table(data);
• data: This is the parameter you pass to console.table(). It can be an array or an object.

How It Works

When you use console.table(), the method takes the data you provide (an array or object) and
creates a table where:

• For Arrays: Each element in the array becomes a row in the table. If the elements are
objects, the properties of these objects become the columns of the table.

• For Objects: Each property of the object becomes a row in the table, with the property
name and value shown in separate columns.

Example with an Array of Objects

const users = [

{ id: 1, name: 'Alice', age: 30 },

{ id: 2, name: 'Bob', age: 25 },

{ id: 3, name: 'Charlie', age: 35 }

];

console.table(users);

output:

┌─────────┬────┬──────────┬─────┐

│ (index) │ id │ name │ age │

├─────────┼────┼──────────┼─────┤

│ 0 │ 1 │ 'Alice' │ 30 │

│ 1 │ 2 │ 'Bob' │ 25 │

│ 2 │ 3 │ 'Charlie'│ 35 │

└─────────┴────┴──────────┴─────┘

Example with an Object

const user = {

id: 1,

name: 'Alice',

age: 30

};
console.table(user);

output:

┌─────────┬────────────┐

│ (index) │ Values │

├─────────┼────────────┤

│ id │ 1 │

│ name │ 'Alice' │

│ age │ 30 │

└─────────┴────────────┘

Key Points

• Column Headers: If the data is an array of objects, the keys of the first object are used
as column headers. If it’s an object, the property names become the row index.

• Indices: For arrays, the table will include an index column by default, showing the
position of each element in the array.

• Readability: console.table() makes it easier to read and analyze complex data


structures compared to using console.log().

Limitations

• Depth: console.table() only goes one level deep. If you have nested objects or arrays,
they will be represented as [object Object] or similar.

• Not Suitable for Very Large Data Sets: While it's great for small to medium-sized data,
using console.table() for very large arrays or objects can clutter the console and make it
harder to navigate.

Summary

console.table() is a powerful tool for developers when they need to quickly visualize and debug
data structures like arrays and objects in an organized table format directly in the console.

DATA TYPES:

JavaScript has several built-in data types that can be categorized into two main types:

primitive and non-primitive (or reference) data types

1. Primitive Data Types

Primitive data types are the most basic data types in JavaScript. They are immutable, meaning
that their values cannot be changed once created. Each primitive value is stored directly in the
memory location that the variable accesses.
a. String

• Definition: Represents textual data, enclosed in single ('), double ("), or backticks (`).

• Example:

let name = 'Alice';

b. Number

• Definition: Represents both integer and floating-point numbers.

• Special Values: Includes Infinity, -Infinity, and NaN (Not-a-Number).

• Example:

let age = 30;

let temperature = 25.5;

c. Boolean

• Definition: Represents a logical entity and can have two values: true or false.

• Example:

let isStudent = true;

d. Undefined

• Definition: A variable that has been declared but has not been assigned a value is
undefined.

• Example:

let x;

console.log(x);

// output:undefined

e. Null

• Definition: Represents the intentional absence of any object value. It is often used to
indicate that a variable should have no value.

• Example:

let y = null;

console.log(x);
//output:null

f. Symbol

• Definition: Introduced in ECMAScript 6 (ES6), Symbol is a unique and immutable


primitive value used as the key of object properties.

• Example:

let y = Symbol("description");

console.log(y);

//output:Symbol(description)

g. BigInt

• Definition: Introduced in ECMAScript 2020 (ES11), BigInt is used to represent integers


that are too large to be represented by the Number type.

• Example:

let bigNumber = BigInt(1234567890123456789012345678901234567890n);

console.log(bigNumber);

//output:1234567890123456789012345678901234567890n

datatype-sumarry.js:

sourcesource

// Primitive

// 7 types : String, Number, Boolearn, null, undefined, Symbol, BigInt

const score = 100

const scoreValue = 100.3

const isLoggedIn = false

const outsideTemp = null

let userEmail;
const id = Symbol('123')

const anotherId = Symbol('123')

console.log(id === anotherId);

// const bigNumber = 3456543576654356754n

// Reference (Non primitive)

// Array, Objects, Functions

const heros = ["shaktiman", "naagraj", "doga"];

let myObj = {

name: "hitesh",

age: 22,

const myFunction = function(){

console.log("Hello world");

console.log(typeof anotherId);

// https://262.ecma-international.org/5.1/#sec-11.4.3

DATATYPE CONVERSION:
Data type conversion in JavaScript, also known as type coercion, refers to the process of
converting a value from one data type to another. JavaScript is a loosely typed language, which
means it allows you to perform operations on values of different types, sometimes
automatically converting (coercing) one type into another to make the operation work. There are
two main types of type conversion:

1. Implicit Conversion (Type Coercion)

2. Explicit Conversion (Type Casting)

1. Implicit Conversion (Type Coercion)

Implicit conversion occurs when JavaScript automatically converts data types as needed,
typically during operations involving different types.

Examples:

• String + Number: When you use the + operator with a string and a number, the number
is converted to a string.

• String - Number: When you use the - operator with a string and a number, the string is
converted to a number (if possible).

• Boolean to Number: In a numeric context, true is converted to 1 and false is converted


to 0.

• Null to Number: null is converted to 0 in a numeric context.

• Undefined to NaN: undefined is converted to NaN when used in a numeric context.

2. Explicit Conversion (Type Casting)

Explicit conversion is when you manually convert a value from one type to another using built-in
JavaScript functions.

Examples:

• String to Number: You can convert a string to a number using Number(), parseInt(), or
parseFloat().

• Number to String: You can convert a number to a string using String() or .toString().

• Boolean to String: You can convert a boolean to a string using String().

• String to Boolean: Any non-empty string is converted to true, and an empty string ("") is
converted to false.

• Number to Boolean: Any non-zero number is converted to true, and 0 is converted to


false.

Special Cases

• NaN: NaN (Not-a-Number) is a special number value that represents an invalid number.
If you try to convert NaN to a string, it results in "NaN".

• null and undefined:


o null converts to "null" when converted to a string, and 0 when converted to a
number.

o undefined converts to "undefined" when converted to a string, and NaN when


converted to a number.

Summary

• Implicit Conversion: Happens automatically during operations (e.g., "5" + 1 results in


"51").

• Explicit Conversion: You manually convert types using functions like Number(), String(),
Boolean(), parseInt(), etc.

Understanding how and when JavaScript converts data types can help you avoid unexpected
behavior in your code.

STACK AND HEAP MEMORY:

BASIC:

In JavaScript, memory management is handled by two main structures: the stack and the heap.

Stack Memory in JavaScript

Stack memory is a region of memory that stores data in a Last In, First Out (LIFO) manner. It's
used for storing:

1. Primitive values (like numbers, strings, booleans, null, undefined, etc.).

2. Function call context (local variables, function arguments, and the current instruction
to be executed).

Key Characteristics of Stack Memory:

• Fast access: Data is stored and retrieved in a fixed, sequential order, making access
very fast.

• Fixed size: The stack size is fixed, and it is smaller in comparison to the heap.

• Automatic memory management: When a function is called, a new stack frame is


created to store its local variables and function arguments. When the function
completes, the stack frame is automatically popped off, freeing the memory.

Heap memory is a region of memory used for dynamic memory allocation, where JavaScript
stores objects, arrays, and functions. Unlike stack memory, heap memory is not organized
sequentially; it allows objects to be stored anywhere in memory, making it flexible for allocating
and freeing memory dynamically.

it is used for non premitive data type

not very fast

_________________________________________updation needed
NEW CONCATINATION SYNTAX:

In JavaScript, backtick concatenation refers to using template literals for string interpolation
and concatenation. Template literals are enclosed by backticks (`) and allow you to embed
expressions directly within a string using the ${} syntax.

Using Backticks for String Concatenation

Template literals offer a more readable and flexible way to concatenate strings compared to
traditional concatenation using the + operator.

Example of Backtick Concatenation:

const firstName = "John";

const lastName = "Doe";

const age = 30;

// Using backticks for concatenation

const greeting = `Hello, my name is ${firstName} ${lastName} and I am ${age} years old.`;

console.log(greeting); // Output: Hello, my name is John Doe and I am 30 years old.

Key Features of Backtick Concatenation:

1. String Interpolation: You can embed variables or expressions directly into the string
without breaking it.

const price = 100;

const tax = 0.15;

const total = `The total price is $${price + (price * tax)}`;

console.log(total); // Output: The total price is $115

2.Multiline Strings: Backticks allow for multiline strings without needing to use newline
characters (\n).

const multiLine = `This is a string

that spans across

multiple lines.`;

console.log(multiLine);
3.Embedded Expressions: You can include any JavaScript expression within ${}.

const a = 5;

const b = 10;

console.log(`The sum of ${a} and ${b} is ${a + b}.`); // Output: The sum of 5 and 10 is 15.

Benefits of Using Backticks

• Improved Readability: Makes the code easier to read and understand, especially when
combining multiple variables or expressions.

• Flexibility: Supports multi-line strings and expressions seamlessly.

• Less Error-Prone: Reduces the need for explicit concatenation operators (+), which can
lead to errors in complex expressions.

DATE AND TIME:

THIS TOPIC IN JS REQUIRED MORE PROJECT BASED EXECUTION AND PROJECT BASED
LEARNING EXAMPLE AND SCINARIO BASED EXAMPLES

_____________________________________________________LEARNING IN PROGRESS

ARRAY:

An array in JavaScript is a data structure that stores a collection of elements (values or objects)
under a single variable name. These elements can be of any type, including numbers, strings,
objects, or even other arrays (multi-dimensional arrays).

Key Features of Arrays in JavaScript:

1. Indexed: Each element in an array has a numeric index, starting from 0.

2. Dynamic: JavaScript arrays can dynamically grow or shrink in size.

3. Heterogeneous: An array can store different types of data (e.g., strings, numbers,
objects) in a single array.

ARRAY FUNCTIONS:

OBJECTS:
FUNCTIONS:

Functions in JavaScript are fundamental building blocks that allow you to encapsulate reusable
code, perform specific tasks, and return values. They are objects themselves and can be
assigned to variables, passed as arguments, and returned from other functions.

Types of Functions in JavaScript

1. Function Declaration

2. Function Expression

3. Arrow Function (ES6)

4. Anonymous Function

5. Immediately Invoked Function Expression (IIFE)

6. Higher-Order Functions

7. Constructor Function

8. Generator Function

1. Function Declarations:

A function declaration defines a function with a specific name. It can be called before it is
defined due to hoisting.

// Function Declaration

function greet(name) {

return `Hello, ${name}!`;

console.log(greet("Alice")); // Output: Hello, Alice!

Key Points:

• The function keyword is used to declare a function.

• Functions can be called from anywhere in the code, even before they are defined (due to
hoisting).

2. Function Expressions:
A function expression defines a function as a part of a larger expression, like assigning a
function to a variable. It is not hoisted, so it must be defined before it is called.

// Function Expression

const greet = function(name) {

return `Hello, ${name}!`;

};

console.log(greet("Bob")); // Output: Hello, Bob!

Key Points:

• Functions are defined anonymously (without a name) and assigned to a variable.

• They are not hoisted, so they cannot be called before they are defined.

3. Arrow Functions:

Arrow functions provide a shorter syntax for writing function expressions. They do not have their
own this, arguments, or prototype, which makes them particularly suitable for non-method
functions.

javascript

Copy code

// Arrow Function

const greet = (name) => `Hello, ${name}!`;

console.log(greet("Charlie")); // Output: Hello, Charlie

4. Anonymous Functions:

Anonymous functions are functions without a name. They are often used as arguments to other
functions or in places where the function is used only once.

javascript

Copy code

// Anonymous Function

setTimeout(function() {
console.log("This is an anonymous function!");

}, 1000);

Key Points:

• They are not stored in memory by name.

• Commonly used for short-lived tasks like event handlers or callbacks.

5. Immediately Invoked Function Expressions (IIFE):

An IIFE is a function that is executed immediately after it is defined. It helps to avoid polluting
the global namespace and is often used to create a new scope.

javascript

Copy code

// IIFE

(function() {

console.log("This function runs immediately!");

})();

Key Points:

• Wrapped in parentheses () to define the function expression.

• Immediately invoked with another ().

6. Generator Functions:

Generator functions allow you to define an iterative algorithm by writing a single function whose
execution is not continuous. They are defined using the function* syntax.

javascript

Copy code

// Generator Function

function* generateSequence() {

yield 1;

yield 2;

yield 3;

const generator = generateSequence();


console.log(generator.next().value); // Output: 1

console.log(generator.next().value); // Output: 2

console.log(generator.next().value); // Output: 3

Key Points:

• Use function* syntax.

• yield keyword is used to pause and resume the function's execution.

Key Characteristics of Functions:

1. Parameters and Arguments:

o Parameters are variables listed as part of the function's definition.

o Arguments are the values provided to the function when it is invoked.

2. Return Statement:

o Functions can return a value using the return statement. If no return statement
is used, the function returns undefined.

3. Default Parameters:

o Functions can have default parameter values.

4. Rest Parameters:

o Functions can accept a variable number of arguments using the ... syntax.

5. Higher-Order Functions:

o Functions that take other functions as arguments or return functions as their


result.

Use Cases for Functions in JavaScript:

• Reusability: Write once, use many times.

• Abstraction: Encapsulate complex logic.

• Organization: Break down code into smaller, manageable pieces.

• Callbacks: Pass functions as arguments for asynchronous operations.

scope level and mini hoisting in js

ChatGPT said:

ChatGPT

Scope in JavaScript
In JavaScript, scope determines the visibility and accessibility of variables and functions. There
are different types of scopes in JavaScript:

1. Global Scope

2. Local Scope (Function Scope)

3. Block Scope

Let's explore each of these in detail.

1. Global Scope

• Variables declared outside any function or block are in the global scope.

• They are accessible from anywhere in the code.

Example:

javascript

Copy code

var globalVar = "I'm a global variable";

function display() {

console.log(globalVar); // Accessible here

display(); // Output: "I'm a global variable"

console.log(globalVar); // Accessible here as well

2. Local Scope (Function Scope)

• Variables declared inside a function are in the local scope of that function.

• They are not accessible from outside the function.

Example:

javascript

Copy code

function display() {

var localVar = "I'm a local variable";

console.log(localVar); // Accessible inside the function

}
display(); // Output: "I'm a local variable"

console.log(localVar); // Error: localVar is not defined

3. Block Scope

• Introduced in ES6 with let and const, block scope confines variables to the nearest
block (i.e., code within {}).

• Block scope does not apply to var, which is function-scoped, not block-scoped.

Example:

javascript

Copy code

if (true) {

let blockScopedVar = "I'm block-scoped";

console.log(blockScopedVar); // Accessible inside the block

console.log(blockScopedVar); // Error: blockScopedVar is not defined

if (true) {

var functionScopedVar = "I'm function-scoped";

console.log(functionScopedVar); // Accessible inside the block

console.log(functionScopedVar); // Accessible outside the block due to function scope

Hoisting in JavaScript

Hoisting is JavaScript's default behavior of moving declarations (variables and functions) to the
top of their containing scope during the compile phase. Only the declarations are hoisted, not
the initializations.

Variable Hoisting:

• var Hoisting:
o Variables declared with var are hoisted to the top of their function or global
scope.

o However, their initialization (if any) remains in place, resulting in undefined if


accessed before the initialization.

Example with var:

javascript

Copy code

console.log(hoistedVar); // Output: undefined

var hoistedVar = "I'm hoisted";

console.log(hoistedVar); // Output: "I'm hoisted"

• let and const Hoisting:

o Variables declared with let and const are also hoisted but are not initialized.
They are in a "temporal dead zone" (TDZ) from the start of the block until the
declaration is encountered.

o Accessing them before the declaration results in a ReferenceError.

Example with let and const:

javascript

Copy code

console.log(letVar); // ReferenceError: Cannot access 'letVar' before initialization

let letVar = "I'm block-scoped";

console.log(letVar); // Output: "I'm block-scoped"

Function Hoisting:

• Function Declarations:

o Function declarations are fully hoisted to the top of their scope, meaning you
can call them before their declaration.

Example:

javascript

Copy code

hoistedFunction(); // Output: "I'm hoisted"

function hoistedFunction() {
console.log("I'm hoisted");

• Function Expressions:

o Functions defined using expressions (like assigning them to a variable) are not
hoisted like declarations. They behave like variables and follow the same
hoisting rules.

Example with Function Expression:

javascript

Copy code

hoistedFunction(); // TypeError: hoistedFunction is not a function

var hoistedFunction = function() {

console.log("I'm not fully hoisted");

};

Mini Hoisting in JavaScript

Mini hoisting refers to the limited hoisting that occurs within block scopes or smaller contexts,
where JavaScript hoists declarations only within the scope in which they are defined.

For example, if you declare a variable inside a block, it will only be hoisted to the top of that
block, not the entire function or script.

Mini Hoisting with let and const:

javascript

Copy code

function example() {

console.log(x); // ReferenceError: x is not defined

if (true) {

let x = 10;

console.log(x); // Output: 10

console.log(x); // ReferenceError: x is not defined

}
example();

Explanation:

• The variable x is block-scoped. It is only hoisted to the top of the block (inside the if
statement) where it is defined, not to the top of the function.

Mini Hoisting with Functions Inside Blocks:

When you define a function inside a block, the function is hoisted only to the top of that block.

javascript

Copy code

if (true) {

function miniHoistedFunc() {

console.log("I'm hoisted inside this block");

miniHoistedFunc(); // ReferenceError: miniHoistedFunc is not defined outside of the block

Explanation:

• The function miniHoistedFunc is hoisted to the top of the block (if block), but not
outside it.

Key Takeaways:

• Scope determines where variables and functions are accessible.

• Global scope variables are accessible throughout the entire script.

• Local scope variables are accessible only within functions.

• Block scope variables (let and const) are accessible only within their block.

• Hoisting allows variable and function declarations to be used before they are defined.

• Mini hoisting pertains to limited hoisting behavior within specific scopes like blocks.

Would you like to know more about any of these concepts in detail?

Control Flow in JavaScript


Control flow refers to the order in which individual statements, instructions, or function calls
are executed or evaluated in a program. JavaScript, like most programming languages, provides
various constructs to control the flow of execution based on different conditions or repetitive
tasks.

Types of Control Flow Constructs in JavaScript:

1. Conditional Statements

o if statement

o if...else statement

o else if ladder

o switch statement

2. Loops

o for loop

o while loop

o do...while loop

o for...of loop

o for...in loop

3. Exception Handling

o try...catch

o finally

o throw

Let's go through each of these control flow constructs with examples.

1. Conditional Statements

Conditional statements control the flow of execution based on specified conditions.

if Statement

Executes a block of code if a specified condition is true.

Syntax:

javascript

Copy code

if (condition) {

// Code to execute if condition is true

}
Example:

javascript

Copy code

const num = 10;

if (num > 5) {

console.log("Number is greater than 5.");

// Output: Number is greater than 5.

if...else Statement

Executes one block of code if a condition is true, and another block if it is false.

Syntax:

javascript

Copy code

if (condition) {

// Code to execute if condition is true

} else {

// Code to execute if condition is false

Example:

javascript

Copy code

const num = 3;

if (num > 5) {

console.log("Number is greater than 5.");

} else {

console.log("Number is not greater than 5.");

}
// Output: Number is not greater than 5.

else if Ladder

Allows multiple conditions to be checked in sequence. The first true condition's block is
executed.

Syntax:

javascript

Copy code

if (condition1) {

// Code if condition1 is true

} else if (condition2) {

// Code if condition2 is true

} else {

// Code if none of the above conditions are true

Example:

javascript

Copy code

const num = 7;

if (num > 10) {

console.log("Number is greater than 10.");

} else if (num > 5) {

console.log("Number is greater than 5 but less than or equal to 10.");

} else {

console.log("Number is 5 or less.");

// Output: Number is greater than 5 but less than or equal to 10.

switch Statement
Evaluates an expression and executes the block of code corresponding to the matching case
value. It is useful when multiple possible values for a variable are handled differently.

Syntax:

javascript

Copy code

switch (expression) {

case value1:

// Code if expression === value1

break;

case value2:

// Code if expression === value2

break;

default:

// Code if no cases match

Example:

javascript

Copy code

const fruit = "apple";

switch (fruit) {

case "banana":

console.log("Banana is yellow.");

break;

case "apple":

console.log("Apple is red.");

break;

default:

console.log("Fruit not found.");

}
// Output: Apple is red.

2. Loops

Loops are used to execute a block of code repeatedly as long as a specified condition is true.

for Loop

The for loop is used to run a block of code a specific number of times.

Syntax:

javascript

Copy code

for (initialization; condition; increment) {

// Code to execute

Example:

javascript

Copy code

for (let i = 0; i < 5; i++) {

console.log(i);

// Output: 0, 1, 2, 3, 4

while Loop

The while loop repeats a block of code as long as the specified condition is true.

Syntax:

javascript

Copy code

while (condition) {

// Code to execute

Example:
javascript

Copy code

let i = 0;

while (i < 5) {

console.log(i);

i++;

// Output: 0, 1, 2, 3, 4

do...while Loop

The do...while loop is similar to the while loop, except it executes the block of code at least once
before checking the condition.

Syntax:

javascript

Copy code

do {

// Code to execute

} while (condition);

Example:

javascript

Copy code

let i = 0;

do {

console.log(i);

i++;

} while (i < 5);

// Output: 0, 1, 2, 3, 4

for...of Loop

The for...of loop iterates over iterable objects (like arrays, strings, etc.), allowing you to access
the values directly.
Syntax:

javascript

Copy code

for (const element of iterable) {

// Code to execute with each element

Example:

javascript

Copy code

const array = [1, 2, 3, 4, 5];

for (const num of array) {

console.log(num);

// Output: 1, 2, 3, 4, 5

for...in Loop

The for...in loop iterates over the properties of an object.

Syntax:

javascript

Copy code

for (const key in object) {

// Code to execute with each key

Example:

javascript

Copy code

const person = { name: "Alice", age: 25 };


for (const key in person) {

console.log(`${key}: ${person[key]}`);

// Output:

// name: Alice

// age: 25

3. Exception Handling

Exception handling is used to handle errors or unexpected conditions in your program.

try...catch Block

Executes code within the try block, and if an error occurs, the catch block handles it.

Syntax:

javascript

Copy code

try {

// Code that may throw an error

} catch (error) {

// Code to handle the error

Example:

javascript

Copy code

try {

let result = 10 / 0; // This will not throw an error, but you might check for errors like division by
zero

console.log(result);

} catch (error) {

console.log("An error occurred:", error.message);

}
finally Block

The finally block executes code after try and catch blocks, regardless of whether an exception
occurred or not.

Syntax:

javascript

Copy code

try {

// Code that may throw an error

} catch (error) {

// Code to handle the error

} finally {

// Code that runs regardless of the outcome

Example:

javascript

Copy code

try {

let result = 10 / 0;

console.log(result);

} catch (error) {

console.log("An error occurred:", error.message);

} finally {

console.log("This runs regardless of the outcome.");

// Output:

// Infinity

// This runs regardless of the outcome.

throw Statement

The throw statement allows you to create custom errors. You can throw exceptions when
certain conditions are met.
Syntax:

javascript

Copy code

throw expression;

Example:

javascript

Copy code

const age = 15;

try {

if (age < 18) {

throw new Error("You must be 18 or older.");

console.log("Access granted.");

} catch (error) {

console.log("Error:", error.message);

// Output: Error: You must be 18 or older.

Summary of Control Flow in JavaScript:

• Conditional Statements (if, else if, else, switch) control code execution based on
different conditions.

• Loops (for, while, do...while, for...of, for...in) allow repetitive execution of code blocks.

• Exception Handling (try...catch, finally, throw) manages errors and exceptions in your
code.

Truthy and Falsy Values in JavaScript

In JavaScript, values can be categorized as either truthy or falsy depending on how they are
evaluated in a Boolean context (such as in an if statement or a loop condition).
1. Falsy Values

A falsy value is one that translates to false when evaluated in a Boolean context. There are
exactly six falsy values in JavaScript:

1. false — The Boolean false itself.

2. 0 — The number zero.

3. -0 — Negative zero.

4. "" or '' — An empty string.

5. null — The absence of any value.

6. undefined — A variable that has not been assigned a value.

7. NaN — Not-a-Number, typically the result of an invalid mathematical operation.

Example of Falsy Values:

javascript

Copy code

if (false) {

console.log("This won't run");

if (0) {

console.log("This won't run");

if ("") {

console.log("This won't run");

if (null) {

console.log("This won't run");

if (undefined) {

console.log("This won't run");


}

if (NaN) {

console.log("This won't run");

Since all these values are falsy, none of the console.log statements will execute.

2. Truthy Values

A truthy value is any value that is not falsy. In other words, a truthy value is any value that
translates to true when evaluated in a Boolean context.

Example of Truthy Values:

• Non-zero numbers: 1, -1, 3.14, etc.

• Non-empty strings: "hello", 'world', " ", etc.

• Objects and arrays: {}, [].

• Functions: function() {}, etc.

• Any other value that is not one of the six falsy values.

Example of Truthy Values:

javascript

Copy code

if (true) {

console.log("This will run");

if (1) {

console.log("This will run");

if ("hello") {

console.log("This will run");

}
if ([]) {

console.log("This will run");

if ({}) {

console.log("This will run");

if (function() {}) {

console.log("This will run");

All the above values are truthy, so all the console.log statements will execute.

Practical Use of Truthy and Falsy Values

Truthy and falsy values are often used to simplify condition checks.

Example: Checking if a Value Exists:

javascript

Copy code

const username = "";

if (username) {

console.log("Username is defined and not empty.");

} else {

console.log("Username is either undefined or empty.");

// Output: Username is either undefined or empty.

Since an empty string ("") is a falsy value, the condition if (username) evaluates to false, and the
else block is executed.

Short-Circuit Evaluation:

You can also use truthy and falsy values with logical operators (&&, ||) for concise expressions.
Example:

javascript

Copy code

let defaultName = "Guest";

let userName = null;

let displayName = userName || defaultName;

console.log(displayName); // Output: "Guest"

In this example:

• The || operator returns the first truthy value. Since userName is null (falsy), defaultName
is chosen.

Double Negation to Convert to Boolean:

Sometimes, you may need to explicitly convert a value to its Boolean equivalent using the !!
(double negation) operator.

Example:

javascript

Copy code

const value = "Hello";

console.log(!!value); // Output: true

const emptyValue = "";

console.log(!!emptyValue); // Output: false

Summary:

• Falsy values: false, 0, -0, "", null, undefined, NaN.

• Truthy values: All other values.

• Use truthy and falsy checks for simpler conditionals and expressions in JavaScript.

Nullish Coalescing Operator (??) in JavaScript


The Nullish Coalescing Operator (??) is a logical operator in JavaScript that returns the right-
hand operand when the left-hand operand is null or undefined; otherwise, it returns the left-
hand operand.

This operator is particularly useful for providing default values when dealing with null or
undefined values.

Syntax:

javascript

Copy code

let result = leftOperand ?? rightOperand;

• leftOperand: The value to check for null or undefined.

• rightOperand: The default value to use if leftOperand is null or undefined.

How It Works:

The ?? operator checks if the left-hand operand is null or undefined. If it is, the operator returns
the right-hand operand. Otherwise, it returns the left-hand operand.

Example:

javascript

Copy code

let name = null;

let defaultName = "Guest";

let displayName = name ?? defaultName;

console.log(displayName); // Output: "Guest"

In this example:

• name is null, so the ?? operator returns the value of defaultName ("Guest").

Difference Between ?? and || (Logical OR Operator):

The || operator returns the right-hand operand if the left-hand operand is falsy (i.e., one of false,
0, "", null, undefined, NaN). However, the ?? operator only returns the right-hand operand if the
left-hand operand is null or undefined. This makes ?? more suitable for cases where you want
to distinguish between false, 0, "", and null/undefined.

Example Comparing ?? and ||:

javascript
Copy code

let userCount = 0;

// Using the logical OR operator (||)

let count1 = userCount || 5;

console.log(count1); // Output: 5 (since 0 is a falsy value)

// Using the nullish coalescing operator (??)

let count2 = userCount ?? 5;

console.log(count2); // Output: 0 (since 0 is not null or undefined)

Practical Use Cases:

1. Providing Default Values:

javascript

Copy code

function greetUser(userName) {

let greeting = `Hello, ${userName ?? "Guest"}!`;

console.log(greeting);

greetUser("Alice"); // Output: Hello, Alice!

greetUser(null); // Output: Hello, Guest!

greetUser(undefined); // Output: Hello, Guest!

2. Handling Configuration Values:

You can use ?? to handle default configuration values for functions or components.

javascript

Copy code

let config = {

maxItems: 0,

theme: null
};

let maxItems = config.maxItems ?? 10; // `maxItems` will be 0 because it is not null or


undefined

let theme = config.theme ?? "dark"; // `theme` will be "dark" because `null` is considered a
nullish value

console.log(maxItems); // Output: 0

console.log(theme); // Output: "dark"

3. Reading User Input or API Responses:

javascript

Copy code

let userInput = ""; // User provided an empty string

let inputValue = userInput ?? "Default Value";

console.log(inputValue); // Output: "" (because "" is not null or undefined)

Note on Operator Precedence:

The ?? operator has a lower precedence than most other operators (like . for member access or
[] for array indexing). It is evaluated before the = (assignment operator) but after most
arithmetic and logical operators. Parentheses can be used to explicitly define the order of
evaluation if needed.

Using ?? with Other Operators:

If you use the ?? operator with the logical AND (&&) or logical OR (||) operators, you may need to
use parentheses due to precedence rules.

Example:

javascript

Copy code

let a = null;

let b = 5;

let result = (a ?? 10) && b; // Output: 5

console.log(result);
Summary:

• ?? (Nullish Coalescing Operator) returns the right-hand operand only when the left-
hand operand is null or undefined.

• It is useful for setting default values without overriding legitimate values like false, 0, or
"".

• More precise than || (Logical OR) in cases where false, 0, or empty strings are valid
inputs.

You might also like