0% found this document useful (0 votes)
9 views31 pages

Javascript

The document provides an overview of JavaScript's primitive data types, functions, arrays, and execution contexts. It explains key concepts such as ES6, first-class functions, and the differences between var and let. Additionally, it covers JavaScript's execution model, including hoisting and the stack vs. heap memory management.

Uploaded by

pmritunjay9555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views31 pages

Javascript

The document provides an overview of JavaScript's primitive data types, functions, arrays, and execution contexts. It explains key concepts such as ES6, first-class functions, and the differences between var and let. Additionally, it covers JavaScript's execution model, including hoisting and the stack vs. heap memory management.

Uploaded by

pmritunjay9555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Sure!

Here's a list of primitive data types in JavaScript:

✅ Primitive Data Types in JavaScript (7 total):


1. number – Numeric values (integers and floats)
Example: 42, 3.14, -7
2. string – Text values
Example: "hello", 'world'
3. boolean – Logical values
Example: true, false
4. undefined – A variable declared but not assigned
Example: let x; → x === undefined
5. null – Represents intentional absence of any value
Example: let y = null;
6. symbol – Unique, immutable identifier (introduced in ES6)
Example: Symbol('id')
7. bigint – Arbitrarily large integers (introduced in ES2020)
Example: 12345678901234567890n

✅ What is ES6 in JavaScript?


ES6 stands for ECMAScript 6, also known as ECMAScript 2015.
It is the 6th version of the ECMAScript standard, which defines how
JavaScript works.
Term When Used What It Means
During function A placeholder variable in the
Parameter
definition function declaration
The actual value you pass to the
Argument During function call
function
function greet(name) { // 'name' is a parameter
console.log("Hello " + name);
}

greet("Mritunjay"); // "Mritunjay" is an argument passed to the


parameter
javascript ke function me kuch bhi aa sakta hai kuch bhi return ho sakta
hai
Ek hi function Boolean bhi return kar rah hai aur string bhi
ARRAY
Javascript me ek hi array me multiple datatype daal sakte hai
Awesome, Mritunjay! Since you've just learned about arrays in
JavaScript, here's a short, clean revision note covering:
 The basics
 What you've learned
 Extra useful functions

✅ JavaScript Arrays – Quick Revision Notes


🔹 What is an Array?
 A list-like object used to store multiple values in a single
variable.
 Can hold mixed data types.
let arr = [1, "JS", true, null, [4, 5]];
🔹 Basic Array Functions:
📌 push()
 Adds an element to the end
arr.push("new");
📌 unshift()
 Adds an element to the beginning
arr.unshift("start");
📌 pop()
 Removes the last element
arr.pop();
📌 shift()
 Removes the first element
arr.shift();

🔹 slice(start, end)
 Returns a shallow copy of selected elements (non-destructive)
arr.slice(1, 3); // Gets elements at index 1 and 2
🔹 splice(start, deleteCount, item1, item2, …)
 Modifies the array by adding/removing elements
arr.splice(2, 1, "inserted"); // Replace 1 item at index 2

🔹 Additional Useful Array Functions:


📌 includes(value)
 Checks if the array contains a value
arr.includes("JS"); // true
📌 indexOf(value)
 Returns the first index of the value, or -1 if not found
arr.indexOf("JS"); // e.g., 1
📌 join(separator)
 Joins all elements into a string
arr.join("-"); // "1-JS-true"
📌 reverse()
 Reverses the array in-place
arr.reverse();
📌 concat(arr2)
 Returns a new array combining both
let newArr = arr.concat([6, 7]);
📌 forEach()
 Executes a function for each element
arr.forEach(el => console.log(el));
📌 map()
 Transforms each element and returns a new array
let squared = arr.map(x => x * x);

🧠 Bonus: Array Check


Array.isArray(arr); // true

JAVASCRIPT INTERVIEW SERIES


JavaScript runs inside browsers via engines like V8 (Chrome) or
SpiderMonkey (Firefox). To run JavaScript outside the browser (like
server-side), we use a runtime like Node.js, which uses the V8 engine.
Similar to how Java requires a JVM, JavaScript requires a runtime
environment like Node.js for execution outside the browser.
Feature Compiled Language Interpreted Language
Translates entire code to
How it Translates and runs line by
machine code before
works line during execution
execution
C, C++, Java (with JVM), JavaScript, Python, PHP,
Examples
Rust Ruby
Usually slower, as
Execution Usually faster, as it's pre-
translation happens during
Speed compiled
runtime
Error Errors found at compile
Errors found at runtime
Detection time
Generates a binary or No separate file — code
Output
executable file runs directly
JavaScript and Python are interpreted, but internally use Just-In-Time
(JIT) Compilation for speed — meaning they compile parts of code
during runtime to improve performance.

✔️JavaScript is based on ECMAScript. The name "JavaScript" is


trademarked by Oracle due to historical reasons, but the two languages
(Java and JavaScript) are completely different.
 JavaScript is an implementation of a standard called
ECMAScript.
 ECMAScript is defined and maintained by ECMA International,
specifically TC39 (Technical Committee 39).
 So, JavaScript follows ECMAScript rules and syntax.

Who Owns the Name "JavaScript"?


 The name "JavaScript" is trademarked by Oracle, because:
o Sun Microsystems (original developers of Java) partnered
with Netscape during JavaScript's early days.
o Later, Oracle acquired Sun Microsystems — and with it, the
trademark rights.
✅ So yes — the name "JavaScript" is owned by Oracle, but the
language itself is open and governed by the ECMAScript standard.
Vanilla JavaScript refers to plain, pure JavaScript — the core
language without any frameworks, libraries, or plugins.
JavaScript frameworks aren't just for optimization —
they also offer structure, tools, and shortcuts to make building large,
complex applications faster and more maintainable.
JSX stands for JavaScript XML.
It lets you write HTML-like syntax inside JavaScript code — which
React then transforms into JavaScript calls under the hood.
We mean:
 You write JSX like:
jsx
Copy code
<h1>Hello</h1>
 But behind the scenes (i.e., "under the hood"), it gets converted
into:
js
Copy code
React.createElement('h1', null, 'Hello');
You don’t need to worry about the exact transformation — React (with
Babel) handles it for you.

Babel is a JavaScript compiler that mainly does two important things:


1. Converts JSX into regular JavaScript
2. Transpiles modern JS (ES6+) into older JS (ES5) so it works in
all browsers

Great question! Let's clearly explain both statements with examples in


the context of JavaScript.

✅ 1. "Functions are first-class citizens" (in JavaScript)


This means that functions in JavaScript are treated like any other
value — such as numbers, strings, or objects.
🔹 What Can You Do With First-Class Functions?
You can:
 Assign a function to a variable
 Pass a function as an argument to another function
 Return a function from another function
 Store functions in arrays or objects

✅ Example 1: Assigning a function to a variable


const greet = function() {
console.log("Hello!");
};
greet(); // ✅ works just like any other variable

✅ Example 2: Passing a function as an argument


function sayHi() {
console.log("Hi!");
}

function callFunction(fn) {
fn(); // ✅ calling the passed-in function
}

callFunction(sayHi); // Outputs: Hi!

✅ Example 3: Returning a function from another function


function outer() {
return function() {
console.log("Inner function");
};
}

const innerFunc = outer(); // outer() returns a function


innerFunc(); // Outputs: Inner function

✅ 2. "Functions are treated as variables"


This just emphasizes part of the first idea:
In JavaScript, you can store a function in a variable, just like any other
value.
✅ Example:
let add = function(x, y) {
return x + y;
};

console.log(add(2, 3)); // 5
You can assign, reassign, or pass add just like a number or string.

🧠 Summary:
Statement Meaning in JS
Functions can be passed around like any other
Functions are first-class
value
Functions are like You can assign, store, and manipulate them as
variables values

Let me know if you want to explore higher-order functions or arrow


functions next!
What is a Callback?
A callback is a function passed as an argument to another function,
so that it can be called later (after some task completes).
Absolutely! Here's a well-structured and easy-to-understand summary
notes of everything you've learned in this session:

✅ JavaScript Function Concepts – Summary Notes


1️⃣ Function Expression
 A function can be assigned to a variable.
const greet = function() {
console.log("Hello!");
};
greet(); // Output: Hello!
 This is called a function expression, and the function can be
anonymous (no name).

2️⃣ Functions are First-Class Citizens


 Functions in JavaScript are treated just like any other value.
 You can:
o Assign functions to variables
o Pass them as arguments
o Return them from other functions
✅ This flexibility makes functions "first-class citizens" in JavaScript.

3️⃣ Functions are Treated as Variables


 Since functions are values, they can be stored in variables and used
just like data.
let sayHi = function() {
console.log("Hi!");
};
sayHi(); // Output: Hi!

4️⃣ Arrow Functions


 A shorter way to write function expressions, introduced in ES6.
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
 Arrow functions:
o Are concise
o Do not have their own this, arguments, or super
o Often used in React, callbacks, etc.

5️⃣ IIFE (Immediately Invoked Function Expression)


 A function that runs immediately after it is defined.
 Useful for avoiding variable pollution or creating private scopes.
(function() {
console.log("I run on my own!");
})(); // Output: I run on my own!

6️⃣ Passing Functions as Arguments


 You can pass a function as an argument to another function.
 This is called a callback.
function greet(name, callback) {
console.log("Hello " + name);
callback();
}

greet("Mritunjay", () => console.log("Goodbye!"));


// Output: Hello Mritunjay
// Goodbye!

7️⃣ Returning Functions from Functions


 You can return a function from another function, creating higher-
order functions.
function outer() {
return function inner() {
console.log("I'm returned from outer!");
};
}

const result = outer();


result(); // Output: I'm returned from outer!
🧠 Final Thoughts:
JavaScript gives you powerful ways to work with functions. By treating
functions like values, you can:
 Create modular code
 Build callbacks and event handlers
 Write expressive, clean logic using arrow functions and IIFEs
 Take full advantage of asynchronous and functional programming

Let me know if you'd like this in PDF or printable format, or if you


want quick exercises based on these concepts!
This is the object node.js gives
You're on the right track! Let's clarify and clean up your understanding a
bit to make it more accurate and structured.

✅ JavaScript Execution Context (EC) — Clean Explanation


JavaScript doesn't have a main() function like C or Java. Instead, it runs
in execution contexts, which determine how and where the code is
executed.

🔹 1. Types of Execution Contexts


There are two main types:
1. Global Execution Context (GEC)
2. Function Execution Context (FEC)

🔹 2. Global Execution Context (GEC)


This is the default context where the JavaScript code starts execution.
Features:
 Created before any code runs.
 Creates two things:
o A global object
o A special variable this
Depending on the environment:
Environment Global Object this in Global Context
Browser window window
Node.js global {} (empty object)

🔹 3. What is Global Code?


Any code that is not inside a function or block is global code.
Example:
console.log("This is global code");
function greet() {
console.log("This is inside a function");
}
 console.log("This is global code") → Part of global execution
context
 greet() function body → Executes in a function execution context

🔹 4. Execution Stack
As the JS engine runs code, it maintains a stack (called the call stack)
of execution contexts:
 First, Global Execution Context is pushed.
 Then, when a function is called, its Function Execution Context
is pushed.
 When the function finishes, it is popped off.
✅ Summary (Your Text, Refined)
JavaScript doesn’t have a main() function. It uses execution contexts to
run code.
Global Execution Context (GEC) is created when the script starts.
It contains two things:
 A global object (e.g., window in browsers, global in Node.js)
 A this binding (this === window in browsers, {} in Node.js
modules)
Any code not inside a function is global code and runs in the global
execution context.

✔️Everything outside functions → Global Execution Context


✔️Everything inside a function → its own Function Execution
Context (created per call)

Hoisting means that declarations (not initializations) of variables and


functions are moved to the top of their execution context (global or
function) during the creation phase, before the code actually runs.
Temporal Dead Zone (TDZ) is the time between the hoisting of a let or
const variable and its actual declaration when you cannot access the
variable.
Even though the variable is hoisted, it's not initialized, and accessing it
before the declaration line results in a ReferenceError.

For Function Declarations:


js
Copy code
function greet() {
console.log("Hello");
}
🔧 During Creation Phase:
 The function name greet is hoisted to the top of the scope.
 Its entire function body is also hoisted (not just the name).
 So, you can call it before its declaration in code.
Yaha pe entire function hoist ho jata naaki sirf naam

Har declaration pe heap me memor alocate hogi aur real har update pe
latest memory in heap point Karega
Real() kahi bhi call karo -> output you both are wasted hi ayega
Stack vs Heap in JavaScript
🔹 Aspect 🧱 Stack 🧠 Heap
📦 Used For Function calls, primitives Objects, arrays, functions
🧭 Structure LIFO (Last In, First Out) Unstructured
⏳ Lifetime Short (per function call) Long (until garbage collected)
⚡ Speed Very fast Slower than stack
🧹 Cleanup Auto (when function ends) Managed by Garbage Collector

✅ Quick Example:
js
Copy code
let x = 10; // x in stack
let obj = { name: "Jay" }; // obj ref in stack, value in heap
In JavaScript, both var and let are used to declare variables, but they
have important differences in terms of scope, hoisting, and re-
declaration. Here's a clear comparison:

🔹 1. Scope
 var → Function-scoped
 let → Block-scoped
function testVar() {
if (true) {
var x = 10;
}
console.log(x); // ✅ Works: 10 (function scope)
}

function testLet() {
if (true) {
let y = 20;
}
console.log(y); // ❌ Error: y is not defined (block scope)
}

🔹 2. Hoisting
 var is hoisted and initialized as undefined.
 let is hoisted but not initialized (in Temporal Dead Zone until
declared).
console.log(a); // ✅ undefined
var a = 5;

console.log(b); // ❌ ReferenceError: Cannot access 'b' before


initialization
let b = 10;

🔹 3. Re-declaration
 var allows re-declaration in the same scope.
 let does not allow re-declaration in the same scope.
var x = 1;
var x = 2; // ✅ Works
let y = 1;
let y = 2; // ❌ SyntaxError: Identifier 'y' has already been declared

🔹 4. Global Object Property


 var variables declared in the global scope become properties of the
window object.
 let variables do not become window properties.
var a = 100;
let b = 200;

console.log(window.a); // ✅ 100
console.log(window.b); // ❌ undefined

✅ Summary Table
Feature var let
Scope Function Block
Yes, initialized to Yes, but in TDZ (error if accessed
Hoisting
undefined before)
Re-
Allowed Not allowed
declaration
Global Object Becomes property Doesn’t become property

🔚 When to Use?
Use let (or const for constants) instead of var in modern JavaScript to
avoid bugs related to hoisting and scoping.
Let me know if you'd like a visual example with code blocks or browser
behavior!

Upar wala global execution context hai


Jab fn call hoga to function execution context Banega
Global and This uska alag hoga
Varname iska alag allocate hoga

First ka answer->10,10 hoga


Second ka answer ->undef,20 hoga
Agar function ke andar var declare nahi karenge to since global pass hua
tha to 10 le lega

Scope in JavaScript is the area of the code where a variable is


accessible (can be read or written).
Line number 7 var ko fun me search Karega, nahi milega to uske bahar
jayega (yaha mil jayega 10) , agar yaha bhi nhai mila to uske bhi bahar
jaega…agar hoga hi nhai kuch to error aa jayega

Scope Chain Behavior Summary


JavaScript uses lexical scoping, so a variable is looked up:
1. In the current function scope
2. Then outer function scope (if nested)
3. Then the global scope
4. If not found → ReferenceError
Question hai->
Line number8 10 print hoga ya line number 8 20 print hoga

Js lexically scoped hota hai islie jaha declartation hoti hai uske bahar ka
lega yani number 8 10 print hoga
Naa ki number 8 20
kyonki jaha call hota hai usko scope nahi dekhte
Lexical scoping means functions access variables based on where
they are declared, not where they are called.
Blue arow downside is goinh lexically outside
1. Scope Chain (Most Likely What You Mean)
The scope chain is the process by which JavaScript resolves variable
lookups — by moving outward through lexical scopes.
🔁 You can think of it like a "scope resolution cycle":
1. Look in the current function/block.
2. If not found, go to the outer scope.
3. Repeat until global scope is reached.
4. If still not found → ReferenceError.

You might also like