Ticker

6/recent/ticker-posts

Javascript part one: whosgeek

history_of_js

Javascript part one: whosgeek


/** 

1995: Brendan Eich at Netscape created a scripting language in 10 days.

Original Names:

First name called Mocha.

Renamed to LiveScript.

Finally named JavaScript for marketing, as Java was popular, but Java and JavaScript are unrelated.

-----------------------------------------------------------------------------------------------------

Browser Wars:

Netscape used JavaScript.

Microsoft’s Internet Explorer copied features and created JScript.


EcmaScript:

To standardize scripting across browsers, Ecma International (founded 1996) created EcmaScript.

JavaScript + Ecma rules = EcmaScript.

Key versions:

ES1 (1997): First version.

ES5 (2009): Added new features.

ES6 (2015): Major update, also called Modern JavaScript.

Since 2015, new features are released yearly by the TC39 committee

LOGICAL QUESTION 

Convert String to Number:

Add a plus sign (+) before a string.

Example: let str = "169"; console.log(typeof (+str)); → Outputs number.

---------------------------------------------------------------------------------------------


Convert Number to String:

Add an empty string ("") to a number.

Example: let num = 10; console.log(typeof (num + "")); → Outputs string.

---------------------------------------------------------------------------------------------


Strings in JavaScript

Strings store text (words, sentences) and use zero-based indexing (first character is at index 0).

Examples:

let str = "pro"; 

(stores "pro").


Common String Methods:

trim(): Removes extra spaces.

slice(): Extracts part of a string.

charAt(): Gets a character at a specific index.

toString(): Converts to string.

concat(): Joins strings.

substring(): Extracts part of a string.

indexOf(): Finds the position of a substring.

toUpperCase(): Converts to uppercase.

lastIndexOf(): Finds the last position of a substring.

toLowerCase(): Converts to lowercase.

--------------------------------------------------------------------------------


Undefined and Null

Undefined:

Returned when:

1.) A variable is declared but not assigned a value.

2.) Accessing a non-existing object's property.

3.) Accessing an array's element out of bounds.

Example:

 let str;

  console.log(str);  → Outputs undefined.

---------------------------------------------------------------------------------

Null:

Means "no value" and is explicitly assigned value .

Type of null is object.

Treated as false in conditions.

Example: 

let val = null;

 console.log(typeof val); 

 → Outputs object.

---------------------------------------------------------------------------------


BigInt

Purpose: Handles large numbers beyond 2^53 - 1 (JavaScript’s safe integer limit).

Declaration:

Add n to a number: let num = 9816543219865252772n;.

Use BigInt(): let num = BigInt(9816543219865252772);.

Note: bigint Does not support decimal values.

--------------------------------------------------------------------------------------------

Methods in Objects

A function inside an object is called a method.

Example:

const person = {

  name: "Alex",

  age: 21,

  about: function() {

    console.log(`My name is ${this.name}`);

  }

};


person.about(); // Outputs "My name is Alex"

-----------------------------------------------------------------------

------------------------------------------------------------------------------

Prototypes

Prototypes allow us to add properties or methods to an object constructor, making them available to all instances created from that constructor.

Example:

function Person() {

  this.name = "John";

  this.age = 23;

}

Person.prototype.greet = function() {

  console.log(`Hi, I'm ${this.name}`);

};

const person = new Person();

person.greet(); // Outputs "Hi, I'm John"

--------------------------------------------------------------------------------------------

How it works:

Person is a constructor function.

Person.prototype.greet adds the 'greet' method to the Person prototype.

All instances of Person (like person) inherit the 'greet' method via the prototype chain.

Calling person.greet() accesses this.name from the instance, outputting "Hi, I'm John".

Prototypes are shared across all instances, making them memory-efficient for methods.

-------------------------------------------------------------------


The new Keyword

Purpose: Creates a new object from a constructor function.

Steps:

-> Creates a new empty object.

-> Sets the object’s prototype.

-> Points 'this' to the new object.

-> Executes the constructor function with this.

-> Returns the new object.

*/

/**

// const  a2 = 10;

// function f() {

//     a2 = 9

//     console.log(a2)//assignment to constant variable

// }

// f();


//a constant variable a2 and initializes it with the value of 10. Then, it defines a function f that attempts to reassign a new value of 9 to a2. However, when f is executed, it throws an error "assignment to constant variable" because a2 is a constant variable and cannot be reassigned a new value.


// In JavaScript, 'const' is a keyword used to declare a variable whose value cannot be reassigned once it has been initialized. 

// This behavior is different from variables declared with var or let, which can be reassigned new values.


// In this case, since a2 is a constant variable, any attempt to modify its value after it has been initialized will result in an error being thrown at runtime. The error message "assignment to constant variable" indicates that we are attempting to modify a constant variable, which is not allowed.

-------------------------------------------------------------------------------------------------------------------


// const  a2 = 10; 90

// function f() {

//    let a2 = 9

//     console.log(a2)//9

// }

// f();

////////////////////////////////////////////////////////////////////

// let a2 = 10;

// function f() {

//     a2 = 9  

//     console.log(a2)//9

// }

// f();

// console.log(a2,"aaaaa")//9

////////////////////////////////////////////////////////////////

let  a2 = 10;

function f(a2) {

    a2 = 9  

    console.log(a2)//9

}

f(a2);

console.log(a2,"2222222222222")//  10  

// //========================================

a = {}

const b = { key: "b" }

const c = { key: "n" }

const d = { n: 3 }

a[b] = 98

console.log(a )//{ '[object Object]': 98 }

console.log(JSON.stringify(a) ) // {"[object Object]":98} 

console.log(a[b] ) // 98

console.log(a,)//   // { '[object Object]': 98 }

a[c] = 123

console.log(a )//   // { '[object Object]': 123 }

a[d] = 6

console.log(a)//  // { '[object Object]': 6 }

a['e'] = 1

a[{ d: 'update' }] = 31

a[{}] = 32

console.log(a[b]) //   //32 

console.log(a) //     { '[object Object]': 32, e: 1 } 

---------------------------------------------------------------------------------------


let string1 = '324e-1'

string1 = Number(string1)

console.log(string1, "ng1")//    32.4 

// '324e-1' is in scientific notation, meaning:          // 324 × 10⁻¹ = 32.4

// ------------------------------------------------------------------------------------------

//setinterval 

//setinterval, settimeout ki tarh hee h .

/**

 * settimout hamare function ko call kr rha tha kuch time baad 

 */

console.log('script start');

setInterval(() => {

  let sum = 0

  // for (let i = 10; i >= 0; i--) {

  //     sum += i

  // }

  // console.log('setinterval===', sum)

  while (sum < 10) {

    sum++

  };

  sum++

  // console.log("setinterval", Math.floor(Math.random() * 10));

}, 1000);

console.log('after script')

--------------------------------------------------------------------------

let kl = 4

function so() {

  console.log(kl) // Cannot access 'kl' before initialization

  let kl = 9

}

// so()


//callback understand 

function task1(caalback) {

  console.log('function 1 is done')

  caalback()

};

task1(() => {

  console.log("2nd function is print")

});


//e.g3 on callback ==================


// function addTwoNumber(num1, num2, onsuccess, onfailure) {

//     console.log(`there is two num which we add ${num1},${num2}`)

//     if (typeof num1 === 'number' && typeof num2 === 'number') {

//         onsuccess(num1, num2)

//     } else {

//         onfailure()

//     }

// }


// function onsuccess(number1, number2) {

//     console.log(number1 + number2)

// }

// function onfailure() {

//     console.log('wrong input')

//     console.log('invalid input ')

// }

// addTwoNumber(2, '3', onsuccess, onfailure)

//e.g4======================================= same question


// addTwoNumber(2, 3, (number1, number2) => {

//     console.log(number1 + number2, 'onsuccess print ')

// }, () => {

//     console.log('wrong input')

//     console.log('invalid input ')

// });

// -------------------------------------------------------------------

//synchronous programmig vs asynchronous programming


//synchronous programming 

// console.log('beforee loop')

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

  // console.log("inside", i)

}


// console.log('after loop')

//j.s is synchronous programming and single threaded.

//line by line execute code .

//===================================


//asynchronus programming

/** 

 * first take a look at set time out function

 * set time out ek function lega as a input and saath mai lega time 

 * ye function kitni der baad run krana h 

 */

// console.log('script-start')

function start() {

  console.log('hello world,inside setitmeout =====')

}

setTimeout(start, 2000)

// console.log('script-end')


//e.g.2.============== settime out with 0 sec

// console.log('strart file ')

// setTimeout(() => { console.log('hello,settimeout with zero second') }, 0)

// console.log("befre looping")

//====================

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

  // console.log('inside for-loop', i)

}

// console.log("after settimenot")

//analyse

/**

 * first line execute, then j.s. ko nhi pta settimeout ke baare mai

 *  to ye browser ke pass bhj dega 

 * browser ke pass rhega aur execute krke result return kr dega. 

 * 0 second baad 

 but js next line pr move krega aur execute krega aaage ka code browser wala return last mai print hoga 

 */

//------------------------------------------------------------------------------------------------------------


let promise1 = new Promise((resolve, reject) => {

  setTimeout(() => {

    resolve('promise resolve');

  }, 2000);

});

// console.log('inbetween promise');

async function sol(req, res) {

  let arr = await promise1

  console.log(arr)

  console.log('promise after')

};

// sol()


for (var i = 0; i < 3; i++) { //change var -> let, const

  // change let ,var const  

}

// console.log( i)// 3

//--------------------------------------------------------------

for (let i = 0; i < 3; i++) { //

  // change let ,var const  

}

// console.log( i)// 3

//-----------------------------------------------------------------------------------------

// for (const i = 0; i < 3; i++) { //

//   // change let, var const  

// }

//---------------------------------------------------------

// console.log( i)// assignment to constant variable

//=======parameter destructuring --------------

// Parameter destructuring in JavaScript allows the unpacking of properties from objects or elements from arrays directly within a function's parameter list

let obj = {

  "name": "alex",

  age: 12,

  address: 'delhi'

};

function sol2({ name, age }) {

  console.log(name, '===name')//alex ===name

  console.log(age)  //12

};

// sol2(obj)

//============set========

let set2 = new Set()

// A JavaScript Set is a collection of unique values-> that means no duplicates allowed. A Set can hold any value of any data type.

// ⚙️ Common Methods: 

// add ->   Adds a new value     mySet.add(10)

// get-> 

// has-> Checks if value exists

// delete ->Removes a value

// clear -> Removes all values

// size -> Returns number of items 


set2.add('e0ee')

set2.add('wjengwigw')

let t3 = { name: 'ram' }

set2.add(t3)

// set2.clear()     // clear property : to clear the set 

//  set2.delete("eeeeeeeeee")//'delete property' : specific element to delete 

let result = set2.has("e0ee")// 'has' 'property' tell the element exist or not 

let result1 = set2.has(t3)// 'has property' tell the element exist or not 

// console.log(result, "WSDCVBVCD", result1, "resultg22222")//true WSDCVBVCD true resultg22222

// console.log('=====  ==============') 

// console.log(set2, "BBBBBB")// Set(3) { 'e0ee', 'wjengwigw', { name: 'ram' } } 

arr = [...set2];

// console.log(arr, 'XSWEDC')// [ 'e0ee', 'wjengwigw', { name: 'ram' } ]


let WHat_is_Javascript;

/*

JavaScript is a scripting (programming) language used in client side that allows us (developers) to make web pages interactive.***

 A scripting language is a kind of programming language that is used to automate the execution of operations in a runtime environment. 

JavaScript is an object-based scripting language, meaning it uses objects to represent data and functionality,

JavaScript is also cross-platform, which means it can be run on any device that has a web browser,

JavaScript follow synchronous pattern

JavaScript code is a single thread, which means that code can only do one task at a time


Dynamic Typing ****

JavaScript is dynamically typed, which means: we don’t need to mention the type of a variable.

A variable can hold any type of value, and it can change later.


let x = 10;           // x is a number

x = "Hello";         // now x is a string

x = [1, 2, 3];      // now x is an array

x = { name: "JS" } // now x is an object

*/

let rem;

let Rem;


let JAVASCRIPT_CASE_SENSITIVE_LANGUAGE


/**

 Is JavaScript a case-sensitive language?

Yes, JavaScript is a case sensitive language.

It means uppercase and lowercase letters are treated as different.

let name = "John";

let Name = "Doe";

console.log(name); // John

console.log(Name); // Doe

 */

console.log(true + true) //2 

console.log(true + false) //1 

/*

  ------------------------------------------------------------------------------------------------------------

  Q: Why JavaScript is known as a lightweight programming language ?

  JavaScript is considered a lightweight language due to its low CPU usage, minimalist syntax, ease of implementation.    

 and it was originally designed to run in browsers with minimal resource demands. It executes client-side tasks (like DOM manipulation) without requiring heavy computation. 

  ------------------------------------------------------------------------------------------------------------


Q: Is JavaScript compiled or interpreted? 

A: JavaScript is primarily interpreted, but modern engines use Just-In-Time (JIT) compilation, so it is technically both. It starts by interpreting and then compiles frequently used code to machine code at runtime for better performance.


🚀 Modern JS Engines (Compiled Just-in-Time - JIT)

Modern engines use Just-in-Time (JIT) compilation to make JavaScript run faster.


Instead of just interpreting code line-by-line (slow), JIT compiles JavaScript into machine code right before execution.

------------------------------------------------------------------------

JIT Compiler: A JIT compiler converts code into byte code first. Then, at runtime, it changes the byte code into machine - readable code, which makes the program run faster.

--------------------------------------------------------------------------------------------

*/

/** 

Why is JavaScript interpreted not compiled?

 JavaScript is compiled or interpreted depends on the environment in which it is run. If it runs in older browsers, it's interpreted. If it runs in modern browsers, it's compiled. 

 What is an Interpreted Programming Language?

 Originally, JavaScript was interpreted, meaning the browser read and executed the code line-by-line at runtime.

*/

let ADVANTAGES_OF_USING_JAVASCRIPT;

/*

 Light Weight Scripting Language******

means js is made for data handling at the browser (only) & due to its low CPU usage, minimalist syntax, and ease of implementation.

--> Server interaction is less. 

-->  Feedback to the visitors is immediate . 

--> Interactivity is high .

--> Interfaces are rich .

--> Speed. Client-side JavaScript is very fast because it can be run immediately within the client-side browser. 

Simplicity. JavaScript is relatively simple to learn and implement.


   The biggest advantage of JavaScript having ability to support all modern browsers and produce an equivalent result.

-> JavaScript is use to create dynamic and interactive websites. JavaScript can be used to manipulate the content and styling of a web page, add interactivity through event handling, and communicate with web servers to update content without requiring a full page refresh.

---------------------------------------------------------------------------------------------------------

*/

let feature_of_js

/*

🌟 Core Features of JavaScript:

✅ Lightweight and Interpreted

JavaScript is a lightweight language and runs directly in the browser. No need to compile manually.

✅ Dynamic Typing

we don’t need to declare variable types (like int, string, etc.).

Example:

let x = 10;  // number  

x = "Hello"; // now it's a string

✅ Object-Oriented

JavaScript supports objects, classes (ES6), inheritance, etc.

✅ Event-Driven Programming

It's perfect for reacting to user actions like clicks, keypress, form submission.

✅ Functional Programming

Functions are first-class citizens. we can assign functions to variables, pass them as arguments, and return function from other functions.

✅ Prototype-based Inheritance

Instead of class-based inheritance (like Java or C++), JavaScript uses prototypes.

✅ Asynchronous and Single-threaded

JavaScript uses an event loop and callbacks, promises, and async/await to handle async code (like API calls) in a non-blocking way.

✅ Runs Everywhere (Cross-platform)

JS runs on browsers, mobile, desktop (with Electron), and servers (Node.js).

✅ Rich Standard Library.

Lots of built-in methods for arrays, strings, objects, dates, math, etc.

✅ Browser Integration.

JavaScript can directly manipulate the DOM, handle events, interact with browser APIs (like localStorage, fetch, etc.)

*/

let DISADVANTAGES_OF_JS = {

}

/*

No support for multithreading. 

No support for multiprocessing. 

Reading and writing of files is not allowed

---------------------------------------------------------------------------------------------------------

 A programming language is a type of computer language that has set of instructions for communicating with computers. 

 the programming languages that are compiled first before running, scripting languages do not compile the file and execute the file without being compiled.

 ******************************************************************************

 */

/*

Question: “Is JavaScript a programming language or a scripting language?”

Answer: JavaScript is both. It began as a scripting language for web browsers, automating tasks like DOM manipulation. But with modern features (e.g., ES6-> classes, modules), it’s a full programming language we used everywhere from front-end to back-end development (e.g., with Node.js).

----------------------------------------------------------------------------------------


JavaScript is a programming language. explain 

Yes, JavaScript is a programming language that is used ((primarily)) for web development, but can also be used for other purposes such as server-side programming, desktop applications, and mobile app development. 

-----------------------------------------------------------------------------------------


❓ Why is JavaScript single-threaded?

JavaScript was designed to be single-threaded because of its main job in the browser: interact with the DOM (the web page).  

*/

let event_loop

/*

🔷 Event Loop is the mechanism that makes asynchronous programming possible in JS.

🔷 Node.js uses JavaScript + Event Loop to build fast, scalable, non-blocking server-side applications.

-----------------------------------------------------------------------------------------

JavaScript uses single-threaded, non-blocking model with an event loop to handle concurrency without multiple threads.

The event loop manages the execution of code, handling tasks like DOM events, timers (setTimeout), and asynchronous operations (e.g., fetching data with fetch).))

---------------------------------------------------------------------------

How it works:

JavaScript has a call stack (where code executes), a task queue (for pending tasks), and a web API (for async operations like timers or HTTP requests).


When an async operation (e.g., setTimeout) is encountered, it’s sent away (offloaded)  to the web API. Once the operation is ready, its callback is placed in the task queue.

The event loop continuously checks the call stack. If the stack is empty, it takes the next task from the queue and pushes to the stack for execution.

---------------------------------------------------------------------------------------

console.log("Start");

setTimeout(() => console.log("Timeout"), 0);

console.log("End");

0

Output: Start, End, Timeout

-------------------------------------------------------------------------------------------------

---example---------------------------------------------

console.log("1");


setTimeout(() => {

  console.log("2");

}, 1000);

console.log("3");

----------------------------------------------------------------------------

🧠 1. Call Stack (Main Execution)

This is where code is executed line by line.

console.log("1") → goes into the stack → runs → pops out.

setTimeout(...) → goes into the stack → passed to Web APIs → pops out.

console.log("3") → runs next.


So the stack looks like:

| console.log("1") | → done

| setTimeout(...)  | → passed to Web API

| console.log("3") | → done


🌐 2. Web APIs

Web APIs are provided by the browser (or Node) to handle asynchronous stuff outside the main thread.

---------------------------------------------------------------------------------------------------

In our case:

setTimeout(() => console.log("2"), 1000)

Web API starts a timer in the background.

Once 1000ms is over, this callback run:

() => console.log("2")


---------------------------------------------------------------------------------------------------------

🗂️ 3. Callback Queue (aka Task Queue or Message Queue)

After the timer ends, the callback is added to this queue.

But it will not run immediately.

Instead, it waits until the Call Stack is empty.


🔁 4. Event Loop 

The Event Loop keeps checking:

“Is the call stack empty?”

If yes, it picks the next task from the Callback Queue and pushes into the Call Stack to execute.


So here:

After console.log("3") finishes, the call stack becomes empty.

Event Loop picks () => console.log("2") and runs it.

-------------------------------------------------------------------------

Microtask Queue (Priority Queue)

The Microtask Queue has higher priority than the Callback Queue. It contains:

Promises (.then(), .catch())

Mutation Observers

process.nextTick() (Node.js only)

-------------------------------------------------------------------------

Execution Context

An Execution Context is the environment where JavaScript code is executed. It consists of

Global Execution Context (GEC) – Created when the JavaScript file runs.

Function Execution Context (FEC) – Created when a function is invoked.

Example:

console.log("Start");

function greet() {

  console.log("Hello");

}

greet(); // Function Execution Context created

console.log("End");

Execution Order:


Global Execution Context (GEC) is created.

console.log("Start") runs.

Function greet() is called → New Function Execution Context (FEC) is created.

Inside greet(), console.log("Hello") runs.

Function context is destroyed, and control returns to the global context.

console.log("End") runs.

**********************************************************************************************


Difference: Micro vs Macro Task

Microtask → Promise.then, process.nextTick → runs immediately after current task.

Macrotask → setTimeout, setInterval → runs after microtasks are done.

**********************************************************************************************

*/


Post a Comment

0 Comments