Documentation: Interpreted Language Client-Side Language
Documentation: Interpreted Language Client-Side Language
Documentation
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.
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.
var x = 10;
console.log(x); // 10
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.
let y = 10;
console.log(y); // 10
console.log(y); // 20
3. const
• Definition: const is used to declare variables that are constant, meaning their values
cannot be reassigned once set.
const z = 10;
console.log(z); // 10
const obj = { a: 1 };
console.log(obj.a); // 2
Summary
• let: Block-scoped, hoisted but not initialized, can be reassigned but not redeclared.
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.
const users = [
];
console.table(users);
output:
┌─────────┬────┬──────────┬─────┐
├─────────┼────┼──────────┼─────┤
│ 0 │ 1 │ 'Alice' │ 30 │
│ 1 │ 2 │ 'Bob' │ 25 │
│ 2 │ 3 │ 'Charlie'│ 35 │
└─────────┴────┴──────────┴─────┘
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.
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 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:
b. Number
• Example:
c. Boolean
• Definition: Represents a logical entity and can have two values: true or false.
• Example:
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
• Example:
let y = Symbol("description");
console.log(y);
//output:Symbol(description)
g. BigInt
• Example:
console.log(bigNumber);
//output:1234567890123456789012345678901234567890n
datatype-sumarry.js:
sourcesource
// Primitive
let userEmail;
const id = Symbol('123')
let myObj = {
name: "hitesh",
age: 22,
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:
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).
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().
• String to Boolean: Any non-empty string is converted to true, and an empty string ("") 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".
Summary
• 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.
BASIC:
In JavaScript, memory management is handled by two main structures: the stack and the heap.
Stack memory is a region of memory that stores data in a Last In, First Out (LIFO) manner. It's
used for storing:
2. Function call context (local variables, function arguments, and the current instruction
to be executed).
• 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.
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.
_________________________________________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.
Template literals offer a more readable and flexible way to concatenate strings compared to
traditional concatenation using the + operator.
const greeting = `Hello, my name is ${firstName} ${lastName} and I am ${age} years old.`;
1. String Interpolation: You can embed variables or expressions directly into the string
without breaking it.
2.Multiline Strings: Backticks allow for multiline strings without needing to use newline
characters (\n).
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.
• Improved Readability: Makes the code easier to read and understand, especially when
combining multiple variables or expressions.
• Less Error-Prone: Reduces the need for explicit concatenation operators (+), which can
lead to errors in complex expressions.
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).
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.
1. Function Declaration
2. Function Expression
4. Anonymous Function
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) {
Key Points:
• 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
};
Key Points:
• 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
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:
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() {
})();
Key Points:
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;
console.log(generator.next().value); // Output: 2
console.log(generator.next().value); // Output: 3
Key Points:
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:
4. Rest Parameters:
o Functions can accept a variable number of arguments using the ... syntax.
5. Higher-Order Functions:
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
3. Block Scope
1. Global Scope
• Variables declared outside any function or block are in the global scope.
Example:
javascript
Copy code
function display() {
• Variables declared inside a function are in the local scope of that function.
Example:
javascript
Copy code
function display() {
}
display(); // Output: "I'm a local variable"
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) {
if (true) {
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.
javascript
Copy code
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.
javascript
Copy code
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
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.
javascript
Copy code
};
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.
javascript
Copy code
function example() {
if (true) {
let x = 10;
console.log(x); // Output: 10
}
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.
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() {
Explanation:
• The function miniHoistedFunc is hoisted to the top of the block (if block), but not
outside it.
Key Takeaways:
• 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?
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
1. Conditional Statements
if Statement
Syntax:
javascript
Copy code
if (condition) {
}
Example:
javascript
Copy code
if (num > 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) {
} else {
Example:
javascript
Copy code
const num = 3;
if (num > 5) {
} else {
}
// 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) {
} else if (condition2) {
} else {
Example:
javascript
Copy code
const num = 7;
} else {
console.log("Number is 5 or less.");
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:
break;
case value2:
break;
default:
Example:
javascript
Copy code
switch (fruit) {
case "banana":
console.log("Banana is yellow.");
break;
case "apple":
console.log("Apple is red.");
break;
default:
}
// 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
// Code to execute
Example:
javascript
Copy code
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++;
// 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
Example:
javascript
Copy code
console.log(num);
// Output: 1, 2, 3, 4, 5
for...in Loop
Syntax:
javascript
Copy code
Example:
javascript
Copy code
console.log(`${key}: ${person[key]}`);
// Output:
// name: Alice
// age: 25
3. Exception Handling
try...catch Block
Executes code within the try block, and if an error occurs, the catch block handles it.
Syntax:
javascript
Copy code
try {
} catch (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) {
}
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 {
} catch (error) {
} finally {
Example:
javascript
Copy code
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
} finally {
// Output:
// Infinity
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
try {
console.log("Access granted.");
} catch (error) {
console.log("Error:", error.message);
• 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.
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:
3. -0 — Negative zero.
javascript
Copy code
if (false) {
if (0) {
if ("") {
if (null) {
if (undefined) {
if (NaN) {
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.
• Any other value that is not one of the six falsy values.
javascript
Copy code
if (true) {
if (1) {
if ("hello") {
}
if ([]) {
if ({}) {
if (function() {}) {
All the above values are truthy, so all the console.log statements will execute.
Truthy and falsy values are often used to simplify condition checks.
javascript
Copy code
if (username) {
} else {
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
In this example:
• The || operator returns the first truthy value. Since userName is null (falsy), defaultName
is chosen.
Sometimes, you may need to explicitly convert a value to its Boolean equivalent using the !!
(double negation) operator.
Example:
javascript
Copy code
Summary:
• Use truthy and falsy checks for simpler conditionals and expressions in JavaScript.
This operator is particularly useful for providing default values when dealing with null or
undefined values.
Syntax:
javascript
Copy code
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
In this example:
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.
javascript
Copy code
let userCount = 0;
javascript
Copy code
function greetUser(userName) {
console.log(greeting);
You can use ?? to handle default configuration values for functions or components.
javascript
Copy code
let config = {
maxItems: 0,
theme: null
};
let theme = config.theme ?? "dark"; // `theme` will be "dark" because `null` is considered a
nullish value
console.log(maxItems); // Output: 0
javascript
Copy code
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.
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;
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.