Skip to main content

Javascript concepts

Q1: What is hoisting ?

Variables and methods are hoisted in js which mean their declaration goes on top of the code mean when you console.log the value of variable before it initialize with any data ,it show its undefined value.

var a;

console.log(a) //undefine

a = 12;

console.log(a) // 12

console.log(b) // you will get an error b is not defind.

Q3:What are data-types ?

There are to type of data in js

1 ) primitive

number, string, boolean, null, undefined are primitive data types. 

 2) References

References => (), [], {}

Definition in urdu: Asi koe bhi value jisko copy krne pr real copy nhi hota. Blke os mein value ka reference pass ho jata hai, ose hum reference value bolte hain.

Or jiska copy krne pr real copy ho jae wo primtive value hoti hai.

Let say we have an array

let a = [1,2,3];

let b = a;

when you pop value from array 'a' than the value also not exist in array 'b' bcz 'b' are taking/using/having array/data of array 'a'

a.pop();

console.log(a) // [1,2]

console.log(b) // [1,2]

Note: Always remind brackets data always a reference data  for other variables. 

Q4:What are functions ?

Function is a piece of code that use for special purpose/task and use again and again when we need it.

Why we use functions ?

a) To organized code. b) for re-useability. c) use any time any where in your script. d) function a task specific e.g calculate age of user.

Arguments: Jo data function function ko pass/ send krte hain.

parameter: Jo variable argument data ko receive krte han ya jo argument ki value ko hold krte han.

push, pop, unshift, shift and splice methods.

push(): to add value in an array we use push method

e.g a = [1,2,3,4];

a.push(5) // 1,2,3,4,5

pop(): To remove last value from array.

a.pop(); // 1,2,3

Unshift(): To add value at start of an array.

Shift(): To remove value from the start of an array.

splice(): To remove value from specific index of an array

Syntex:

array.splice(index,number of values to remove);

a.splic(2,1);

Q5:Var, let and const concept.

There are two versions of JS

a) ES5 b) ES6

ES5 is an old version and variable are declared with var key-word.

ES6 is an advance/new/latest version of JS and let and const are introduce in this version with meaningful purpose.

Now what are their purpose

var: var is a function scoped mean it can be access and use inside function, where it declared.

example:

function abc(){

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

        console.log(i); //0 1 2 3 4

    }

    console.log(i) // 5

}

See we can use/access 'i' from outside of the for loop.

var adds itself to window object

let: let is a braces/bracket scoped mean the variable we defined with let inside the any brackets its scope is only in that place, not outside of the bracket.

example: If you change i declaration with let than you got and error i is not define.

const: It is also braces scoped.

let and const doesn't add itself to window object.

Q6:What is Window Object?

Browser features that provided by window object. what does it mean ? JS not have some feature but it use/support those features that features belongs to browser and browser window object provides thos feature and JS use them.

What are those features ?

alert, console.log, prompt, confirm, setTimeInterval, localStorage, screening, scrolling, document are many more,

just write window and hit enter in console and see those features.

Important point

var variable window mein stroe ho jata ha 

var a = 12;

write window in console and hit enter 

you will find a with data 12 in there.

But let not allowed that, it not store in window, it protect the data as well.


Q7:What is Browser Context Api ?

Browser provide you three types of things.

a)  window b) stack c) heap memory

Let talk about Stack:

Stack is the mechanism of script/code execution and keep track of function calls.

what does it mean?

Call Stack is the way for javascript engin to keep its place/position in code that call multiple functions. It has the information of what function is currently executing and what function is qgoing to be execute within that function.

javascript call stack manage the execution context.

Execution context: Execution context is a container called call stack which execute the code inside function. Execution context is created when we call any function. There three main things in that 1) variables 2) functions 3) lexical environment. 

1) Global execution context.

2) Function execution context.

Call stack work based on LIFO (Last in first out).

Global execution context: when you execute script. javascript engin call Global execution context and push it on top of the call stack.

Function execution context: when function call javascript engin call Function execution contxt and pushes it to top of the call stack and execute the function.

Reference link: https://www.javascripttutorial.net/javascript-call-stack/

Lexical environment: It hold the information of what to implement or what to not. It hold the information of scope and scope chain of variables and function.

Heap Memory

All variables data. intermediate data (data in calculations) are stored in heap memory.

Q8:How to copy reference values?

    Last time we see when we copy array 'a' inside b than if we pop some value it also remove from array 'a'. bcz it array 'a' was reference to b variable

to over come this problem what we do, we use spread operator

syntex: [...a]

let say a=[1,2,3,4,5];

now b = [...a];

b.pop // 1234

console.log(a); // 12345

see array 'a' is same as it was before. Same thing we can do with objects.

Q9 truthy and falsy in js?

Normally we consider true and false or any condition result consider truthy and falsy but it is not like so.

Falsy: 0, false, undefined, null, NaN, document.all return false value.

truthy: Other than obove return true value.

e.g 

if(3){

    //this part will execute bcz it return true and 3 is not from falsy values.

}else{

}

Loops in js

forEach loop:

whenever you want to iterate over array elements.

syntex

a = [1,2,3,4,5,6];

a.forEach(function(item){

    console.log(item+2);

})

forIn loop:

To iterate over object, we use forIn loop.

var obj = {

    name: 'adnan',

    age: 24,

    city: 'Lahore'

}

obj.for(var key in obj){

    console.log(key, obj[key]);

}

Q9: what are callback function?

In asynchronouse javascript, asa code to bad mein chlta ha, lekin kb chlta ha ye callback function btata hai javascript ko.

e.g: setTimeOut(function(){

    console.log('adnan');

},2000);

take above code as an example and understand its working. Ye aik asa code hai jo 2 second bad run hoga or hum ise aik fu nction de rhe han to 2 second k bad chlega, isse call back function bolte hain.

 Q10:What is First Class Function?

JS mein aik concept hai jis mein hum aik function ko variable mein store kr skte hani as an value and we can also pass it as and argument to any function.

var a = function(){};

function abc(a){

    a();

}

abc(function(){console.log('hello adnan');});

Q11: How arrays made behind the scene?

var arr = [1,2,3,4];

This is an array but this is not actual array. How?

when you write typeOf(arr); // object

typeOf({}); // object

It is it object, because JS convert it to array.

Both are objects right ? But how we know which one is array and which is object?

Array.isArray([]); // true

Array.isArray({}); // false

Q12: How we can make negative index in array?

var arr = [1,2,3,4,5];

arr[-4] = 234;

console.log(arr); // [1,2,3,4,5,-4:234];

Note: JS convert array to Object.

Q13: Remove item from object?

var a = {

    name: 'adnan',

    age: 26

}

delete a.age;

Q14: async/await concept and its working.

Async/await is the way to work with asynchronous code in javascript that make use feel like synchronous code.

Wait a minute what is async and sync code what is the difference between them?

a) Synchronous

Synchronous code execute in linear way, step by step. What does it mean?

It mean when one process/program/code execute than rest of the code execute. We also know that js code execute from top to bottom.

example code:

console.log("Step 1");

console.log("Step 2");

console.log("Step 3");

see when step one execute than step 2 will  execute mean rest of the program will have to wait for first program to finish.

In above example step 1 and 3 will be executed first, than step 2 execute when its promise resolve. 

b) Asynchronous

Asynchronous code allows operation to perform independently from the main program(Initiator).It doesn't block the execution of code/program if one operation is not finish yet. It continue executing other tasks/operations.

When asynchronous task completed than a callback, promise, async/await handle the results. 

Example code:

console.log("Step 1");

setTimeout(() => {

  console.log("Async Step 2");

}, 2000);

console.log("Step 3");

Example code:

<script>

// Imagine this function simulates fetching data from a server.

function fetchData() {

  return new Promise((resolve) => {

    setTimeout(() => {

      resolve("Data fetched!");

    }, 2000); // Simulating a delay of 2 seconds

  });

}

// Using async/await to fetch data

async function fetchDataAsync() {

  console.log("Fetching data...");

  const data = await fetchData(); // This line waits for the promise to resolve.

  console.log('promise return: '+data);

  console.log("Data fetched and processed!");

}


fetchDataAsync();

console.log("Continuing with other tasks...");

</script>

Note: Asynchronous take crucial amount of time such as network requests/third party api calls, server file reading etc. So javascript provides mechanism like callback, promise, async/await to handle asynchronous operations. 

Q15:What is callback function?

Callback function in javascript is an function that is send as an argument to an other function that is intended(purpose) to execute later. They are commonly use in Asynchronous javascript.

Example code:

<script>

function doSomething(callback) {

  console.log("Doing something...");

  // Simulate a delay or asynchronous operation

  setTimeout(() => {

    console.log("Operation completed.");

    callback(); // Execute the callback function

  }, 2000);

}


function callbackFunction() {

  console.log("Callback function executed.");

}


doSomething(callbackFunction);

console.log("Continuing with other tasks...");

</script> 

Advanced concept in javascript.

1. Higher order function (HOF)

A function which accept an other function as a argument/parameter called higher order function.

Or 

A function which return another function.

Example:

forEach() function always take another function inside it so it is higher order function.

<script>
        var arr = [1,2,3,4,5,6];
        arr.forEach(function(value,index){
            console.log('index: '+ index);
            console.log('value: '+ value);
        });
</script>

2. Constructor functions

Constructor functions is a way to create, initialize objects. They are like blueprints/templates for creating objects of a specific type.

What does it mean i don't understand.

A type of function which contain some properties. These properties can be same or different for their objects.

Properties can be declare with this keyword.

This function can be act like a class which ha same type of variable but different data.

Whenever we call this function we use new keyword and it return an object which contain all properties and method of that constructor function.

Note: By default when we use this keyword we refer to window because it is the object of window and we can access features of browser.

Q: Why we use constructor function?

When we have multiple elements/items with same but sometime different properties data than we use constructor function.

Example code:

<script>
        // simple example
        function saanchaOfBiscuit(){
            this.width = 12;
            this.height = 22;
            this.color = "Brown";
            this.taste = "Pineapple";
        }
        var  bis1 = new saanchaOfBiscuit();
        var  bis2 = new saanchaOfBiscuit();
       

        // Some Real example
        function Person(name, age) {
        this.name = name;
        this.age = age;
        }

        // Adding a method to the constructor's prototype
        Person.prototype.sayHello = function() {
        console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
        };

        const person = new Person("Carol", 28);
        person.sayHello(); // Output: Hello, my name is Carol and I'm 28 years old.
  </script>



3. First class functions

First class function that can be treated as normal values or like variables. You can store it in variable and pass it to an other function as an parameter.

Example:

<script>
        setTimeout(() => {
           
        }, timeout);
</script>

4. New keyword

In javascript, new keyword is use to create instant(copy) of the object of and class or constructor function. The new instant/object will be empty at first, But when to call it on some constructor function/class it will contain the properties of that function/class.

Read the example code of constructor function

5. IIFE (Immediately invoked function expression)

A function which we want to run/execute immediately. 

Why we use IIFE?

for many reason but for now i can say to secure some data of variables. means user cannot access it directly, because any variable we define in iife become private variable. 

It mean we cannot access it outside but access inside iife.

Example code:

<script>
        var result = (function(){
            var age = 16;
            // returning an object
            return {
                // its industery trend to set and get data like so
                getter: function() {
                    console.log(age);
                },
                setter: function(val) {
                    age = val;
                }
            }
        })();
        // getting and setting data from outside iife function
        console.log(result.getter());
        console.log(result.setter(19));
        console.log(result.getter());
</script>

6. Prototype

Go to console in browser and make a simple object.

var obj = {name: 'adnan'}

than on getting name property with object name followed by DOT operator, you will notice console suggesting other properties that we not created.

e.g hasOwnProperty etc

obj.

If we didn't create them than from where these came from?

That's where the concept of prototype come from.

Every object create in javascript get an prototype property. This mean you create a an object it automatically gets an prototype property.


Where these prototype came from ?

When objects are created in javascript than by default prototype where added to these abjects.

What does it contain ?

Prototype contains many helper properties and methods to apply some operation/action on object to complete our task.

Example: We make array and we need to find the length of that array. For that we use .length property on array to get array length. so question came here is we create .length() function? NO. Because these properties and method are build in and created by javascript creators in prototype property of object. 

7. Prototype Inheritance

At first!

What is inheritance ?

Simple example: A child get some properties/qualities from its father i.e may be eye color, hair color etc.

In programming term child class inherit properties of parent class right?

So what about protypal inheritance?

Just like parent send some properties to its childrens, we do the same thing in javascript with the help of prototype(One extra property always given by js to every object) that called prototypal inheritance.

Example: We have human object human can do many common things

like

var human = {

    canEat = true,

    canSee = true,

    canWalk = true

}

Now we have another object

var pilot = {

    canWaerUniform = true,

    canFlyPlane = true,

    canFixPlane = true

}

Now what you have notice.

Pilot of Aeroplane can fly plane as well as he can do things that human can do But every human can't fly a plan.

So we will add human properties to pilot mean pilot will inherit human properties.

How to inherit properties of human into pilot object?

pilot.__proto__ = human;

8. This keyword

This keyword in javascript is a special keyword that changes its value in different context. Its value can be different at different places.

What does it mean? I can't understand it.

In global Scope: When you define some variable, object outside the {} than these have global scope.

console.log(this); // this will return window object

Local Scope: When variables and objects are define within the {} than it have local scope.

mean we can't access those outside of their scope.

function abcd(){

    console.log(this); //this will return window object

}

Now lets check use of this  keyword in method.

Method ?

Than What is the difference between method and function?

example:

obj = {

    name: 'Adnan',

    letsTalk: function(){

        console.log(this); //check the value of this in console and see what it containing.

    }

}

obj.letsTalk();

A function we define/make in an object called method.

Now we know that in global scope this => window

In global scope this => window

In method scope this => object

Important: In any method, this keyword refers to parent object

Lets take an example with DOM

<button>Click me to check value of this keyword</button>
    <script>
        var button = document.querySelector('button');
        button.addEventListener('click',function(){
            console.log(this);
            this.style.color = 'green';
        });
    </script>

Now you will see console.log is returning button element. Because this is referring to the element that we write before addEventListener method.

9.Call, Apply and bind

All three call, apply and bind have same moto. 

What is Call?

If we have any function and any object and i want to run that function but before recall in mind, that this keyword have window object value in global and local scope. right?

Now i want to point this keyword value to any other object rather than window object.

Example code:

<script>
        function abcd(){
            console.log(this);
            // bydefault this have window object value.
            // now point it to other object
        }
        var obj = {
            name: 'adnan'
        }
        abcd.call(obj);
        // in console you will see this ketword have obj object properties.
    </script>

How to pass parameters to that function?

 // passsing parameters

        function abcd(val1,val2){
            console.log(this);
            // bydefault this have window object value.
            // now point it to other object
            console.log(this.name);
            console.log(val1);
        }
        var obj = {
            name: 'adnan'
        }
        abcd.call(obj,34,56);
        // in console you will see this ketword have obj object properties.

What is Apply?

Call and Apply bind have small different, In apply bind we pass parameters in array format.

apply method take two parameters, 

1st object for this keyword and 2nd array for passing parameters.

Example code:

 // apply binding

        function abcd(val1,val2){
            console.log(this);
            // bydefault this have window object value.
            // now point it to other object
            console.log(this.name);
            console.log(val1);
        }
        var obj = {
            name: 'adnan'
        }
        abcd.apply(obj,[34,56]);
        // in console you will see this ketword have obj object properties.

What is bind?

With bind we bind function with any object. Why we are binding? Because sometime we don't want to run function immediately like call and apply. They are automatically calling by itself.

Here we are binding and we will run that function when we need it. This we use mostly in react js.

Example code:

// bind

        function abcd(val1,val2){
            console.log(this);
            // bydefault this have window object value.
            // now we have point it to other object
            console.log(this.name);
            console.log(val2);
        }
        var obj = {
            name: 'adnan'
        }
        // we are binding function with object
        // way 1 to call and pass params
        var bindedFunc = abcd.bind(obj,3,4);
        bindedFunc();
        // way 2 to call and pass params
        var bindedFunc = abcd.bind(obj);

        bindedFunc(13,45); 


10 Pure and Impure functions

Pure functions

The Pure function have two qualities

1) It always return same output for same input.

2) It never update/change the global variable value.

Example code:

 <script>
        // pure function
        var age = 21;
        function abcd(a,b){
            return a+b;
        }
        var ans1 = abcd(1,3);
        var ans2 = abcd(3,3);
        console.log(age);
    </script>

Impure function

Function which change the global/parent variable value.

It also not return the same value on same input

Example code:

 // Impure function
        var age = 21;
        function abcd(){
            age = 23;
        }
        var ans1 = abcd();
        console.log(age);

4. map, filter and reduce



6. Prototype,  Prototype Inheritance

7. Currying

8. Method Chaining

Comments

Popular posts from this blog

Install MariaDB Latest Version 11.4 in Red Hat Version 9

 This this post i will show you step by step the installation process of mariaDB in red hat version 9. Step1 Run the command to pull the latest updated packages on applications installed in your system. -dnf update If you get Kernal update than reboot the system -reboot Step2 Go to official mariaDB site Make mariadb repository in /etc/yum.repos.d Place the configuration in this file # MariaDB 11.4 RedHatEnterpriseLinux repository list - created 2024-09-24 11:12 UTC # https://mariadb.org/download/ [mariadb] name = MariaDB # rpm.mariadb.org is a dynamic mirror if your preferred mirror goes offline. See https://mariadb.org/mirrorbits/ for details. # baseurl = https://rpm.mariadb.org/11.4/rhel/$releasever/$basearch baseurl = https://mirrors.aliyun.com/mariadb/yum/11.4/rhel/$releasever/$basearch # gpgkey = https://rpm.mariadb.org/RPM-GPG-KEY-MariaDB gpgkey = https://mirrors.aliyun.com/mariadb/yum/RPM-GPG-KEY-MariaDB gpgcheck = 1 Now install the mariaDB with its dependencies package...

Linux Commands

  Linux Commands 1.  OS-Release -cat /etc/os-release -cat /etc/redhat-release show os //kernal information -uname  show kernal middleware It is intermediator between hardware and software. -uname  -r what is process architect. -uname -p To show all information -uname -a 2.  Date-CAL -date -cal 3.  Booting in Linux (Run-Levels) Shutdown/Close pc -init 0  Single user mode -init 1 Multiple user mode -init 2 Multiple user mode with network plus full support Not use -init 4 Graphical mode init 5 Reboot the system -init 6 4.  Target command in Linux (systemctl) With the help of target we can manage system specific as well as user specific task. Target command is system Control (systemctl). Basically it is utility, which build to replace 'init' command. What systemctl can do ?  We can find its all commands with the help of single command. write systemctl enter twice TAB button. //it will list all its commands. Show current system mode - systemctl...