[Go to site: main page, start]

0% found this document useful (0 votes)
7 views17 pages

Java Script

The document provides a comprehensive overview of JavaScript, covering its fundamentals, arrays, objects, and advanced concepts. Key topics include the nature of JavaScript as an interpreted and synchronous language, variable scope, function types, and methods for manipulating arrays. It also explains important distinctions between operators and variable declarations, as well as advanced features like promises and async/await.

Uploaded by

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

Java Script

The document provides a comprehensive overview of JavaScript, covering its fundamentals, arrays, objects, and advanced concepts. Key topics include the nature of JavaScript as an interpreted and synchronous language, variable scope, function types, and methods for manipulating arrays. It also explains important distinctions between operators and variable declarations, as well as advanced features like promises and async/await.

Uploaded by

Talha Younas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Table of contents

Fundamentals​ 3
1- What is JavaScript?​ 3
2- Is JavaScript a compiled language or interpreted language?​ 3
3- Is JavaScript a synchronous or asynchronous programming language?​ 3
Synchronous Programming​ 3
Asynchronous Programming​ 3
4- Scope​ 4
Block Scope​ 4
Global Scope​ 4
Function or Local Scope​ 4
5- Difference between the == and === operators.​ 5
6- What is the Difference between var, let, and const in JavaScript?​ 5
7- Functions and their types.​ 6
Simple Functions with functions declaration​ 6
Function Expressions or Anonymous function expression​ 7
Arrow Functions​ 7
8- What is IIFE (Immediately Invoked Function Expression)?​ 7
9- What is the difference between null and undefined in JavaScript?​ 7
Arrays and Objects​ 8
1- What is the array in JavaScript?​ 8
2- What is the object in JavaScript?​ 8
3- What is the map() method in JavaScript?​ 8
4- What is the filter() method in JavaScript?​ 9
5- What is the reduce() method in JavaScript?​ 9
6- What is the find() method in JavaScript?​ 9
7- What is the difference between the slice() and splice() method in JavaScript?​ 10
slice()​ 10
splice()​ 10
8- What is the difference between rest and spread operator in JavaScript?​ 10
Rest Operator​ 10
Spread Operator​ 11
9- What is the JSON object in JavaScript?​ 11
Advance Steps​ 12
1- What is the Execution Context in JavaScript?​ 12
Creation Phase​ 12
Execution Phase​ 12
2- What is the Global Execution Context and Function or Local Execution Context in
JavaScript?​ 13
Global Execution Context:​ 13
Function or Local Execution Context:​ 13
3- What is Hoisting in JavaScript?​ 14
4- Hoisting in case of let and const in JavaScript?​ 14
5- Exercising the hoisting in JavaScript.​ 14

1
6- What is a callback function in JavaScript?​ 15
7- What is a Promise in JavaScript?​ 16
8- What is Async/Await in JavaScript?​ 17

2
Fundamentals
1- What is JavaScript?
JavaScript is a high-level, interpreted, single-threaded, and synchronous
programming language used to create interactive websites.
It runs in the browser and can also be used on the backend ([Link]).
●​ High-level: Easy to read and write, handles low-level stuff for you.
●​ Interpreted: Runs code line by line in the browser.
●​ Single-threaded: Can do one thing at a time.
●​ Synchronous: Executes code in order, one step after another.

2- Is JavaScript a compiled language or interpreted language?


JavaScript is an interpreted language, not a compiled language. The major
difference between compiled language and interpreted language is that compiled
language is first converted into machine code and then executed while
interpreted language is executed line by [Link] which means that JS is single
threaded language.
[Link]("Hello World") // this will be executed first then the next line will
be executed
[Link]("Hello World") // this will be executed after the first line

3- Is JavaScript a synchronous or asynchronous programming


language?

Synchronous Programming
JavaScript is a synchronous programming language, meaning that it executes
code line by line in the order it appears in the source [Link] means that it
will execute one line of code at a time and move to the next line after the
execution of the first line.

Asynchronous Programming
JavaScript is also capable of asynchronous programming, which allows code to
run in parallel without blocking the main execution thread. This is achieved
using asynchronous functions, callbacks, promises, and async/await.
[Link]("Hello World") // this will be executed first
setTimeout(() => {

3
[Link]("Hello World") // this will be executed after 2 seconds
}, 2000)
[Link]("Hello World") // this will be executed after the first line

4- Scope
The region where we can access the variable is known as the scope for that
variable Scope determines the accessibility (visibility) of variables.
JavaScript variables have 3 types of scope:
●​ Block scope
●​ Function scope
●​ Global scope

Block Scope
Variables declared inside a { } block can NOT be accessed from outside the
block. It is also known as the local scope. It could be an if statement, for loop,
while loop, or a function.
{
let x = 2;
}
// x can NOT be used here

Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.

Global Scope
The variables that can accessed from anywhere in the code are known as global
variables

Function or Local Scope


Variables declared within a JavaScript function, are LOCAL to the function:
function myFunction() {
let carName = "Volvo";
// variable carName has local scope because it is declared inside a function
}

4
5- Difference between the == and === operators.
●​ In JavaScript, the == operator is known as the equality operator. When
using ==, JavaScript attempts to convert both operands to a common type
before making the comparison. This process is called type coercion.
Here are some examples of how the == operator works:
[Link](1 == '1'); // true, '1' is converted to a number
[Link](true == 1); // true, true is converted to 1
[Link]({} == '[object Object]'); // true, both are converted to
strings
[Link](null == undefined); // true, null and undefined are
considered equal
[Link](0 == NaN); // false, NaN is not equal to anything
including itself
[Link]({} == {}); // false, different objects

●​ === operator in JavaScript is known as the strict equality operator. It


behaves differently from the == operator in that it does not perform type
coercion. Instead, it requires both operands to be of the same type and
have the same value for the comparison to return true else it will return
false even if the values are same but the data type is different.
[Link](1 === '1'); // false, number is not equal to string
[Link](true === 1); // false, boolean is not equal to number

6- What is the Difference between var, let, and const in


JavaScript?
In JavaScript, var, let, and const are used to declare variables, but they have
different scopes and behaviors. The main differences between var, let, and const
are:

var let const

Variables declared with Variables declared with Variables declared with


var are let are block-scoped. const are block-scoped.
function-scoped.

5
Variables declared with Variables declared with Variables declared with
var are hoisted to the let are hoisted to the const are hoisted to the
top of their function or top of their block scope top of their block scope
global scope. but not initialized. but not initialized.

Variables declared with Variables declared with Variables declared with


var can be redeclared let can be reassigned const cannot be
and reassigned. but not redeclared. redeclared or
reassigned.

Variables declared with Variables declared with Variables declared with


var have global scope let do not have global const do not have global
if declared outside a scope if declared scope if declared
function. outside a function. outside a function.

var a = 10;
let b = 20;
const c = 30;

var a = 40; // No error


let b = 50; // SyntaxError: Identifier 'b' has already been declared
const c = 60; // SyntaxError: Identifier 'c' has already been declared

a = 70; // No error
b = 80; // No error
c = 90; // TypeError: Assignment to constant variable

7- Functions and their types.


Functions in JavaScript are blocks of reusable code that perform a specific task.
There are several types of functions in JavaScript:

Simple Functions with functions declaration


These functions are simply defined with the function keyword and the name of
the function
We can call a function or execute the code of a function by using its name. Let
me give you an example.
function print(name){
​ [Link](name)

6
}
print("Dev") // Dev

Function Expressions or Anonymous function expression


In functions saving a function into a variable as an expression is known as a
function expression.
Here is example
const greet = function(name) {
[Link]('Hello, ' + name + '!');
};

Arrow Functions
Arrow functions, also known as arrow function expressions, provide a concise
syntax for writing functions in JavaScript. They were introduced in ES6
(ECMAScript 2015) and offer a more concise and expressive way to define
functions compared to traditional function expressions.
const print = (name) => {
[Link](name);
};
print("Dev"); // Dev

8- What is IIFE (Immediately Invoked Function Expression)?


A Immediately Invoked Function Expression (IIFE) is a JavaScript function that
runs as soon as it is defined. It is a design pattern that is used to create a private
scope for variables to avoid polluting the global [Link] call the function
immediately after defining it, we wrap the function in parentheses and then
append an additional set of parentheses at the end.
(function() {
[Link]("Hello World");
})();

9- What is the difference between null and undefined in


JavaScript?
The main difference between null and undefined in JavaScript is that null is an
assigned value that represents the absence of a value, while undefined is a
variable that has been declared but not assigned a value.

7
Let's consider an example,to store variable value we use a box and if the box is
empty then it is null and if the box is not present then it is undefined.
let a;
[Link](a); // undefined

Arrays and Objects


1- What is the array in JavaScript?
An array in JavaScript is a special type of variable that can hold multiple values
at once. Arrays are used to store collections of data, such as a list of numbers or
a list of [Link] can save function, object, string, number, boolean in an
[Link] access the element of an array we use the index of the element.

let numbers = [1, 2, 3, 4, 5];


[Link](numbers[0]); // 1

2- What is the object in JavaScript?


An Object is a variable that can hold multiple values at once. Objects are used
to store collections of key-value pairs, where each key is a unique identifier for
a value. Objects can contain properties and methods, which are defined as
key-value pairs within the object.

let person = {
name: 'John',
age: 30,
city: 'New York'
};

[Link]([Link]); // John

3- What is the map() method in JavaScript?


The map() method in JavaScript is used to create a new array by applying a
function to each element of an existing array. The map() method does not
change the original array but returns a new array with the results of the function
applied to each element.
let numbers = [1, 2, 3, 4, 5];

8
let newNumbers = [Link]((number) => number * 2);
[Link](newNumbers); // [2, 4, 6, 8, 10]
[Link](numbers); // [1, 2, 3, 4, 5]

4- What is the filter() method in JavaScript?


The filter() method in JavaScript is used to create a new array with elements
that pass a certain condition. The filter() method does not change the original
array but returns a new array with elements that satisfy the condition.
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = [Link]((number) => number % 2 === 0);
[Link](evenNumbers); // [2, 4]
[Link](numbers); // [1, 2, 3, 4, 5]

5- What is the reduce() method in JavaScript?


The reduce() method in JavaScript is used to reduce an array to a single value
by applying a function to each element of the array. The reduce() method takes
an accumulator and a current value as arguments and returns a single value. The
reduce() method can be used to perform operations such as summing the
elements of an array or finding the maximum value.
let numbers = [1, 2, 3, 4, 5];
let sum = [Link]((accumulator, currentValue) => accumulator +
currentValue, 0);
[Link](sum); // 15

6- What is the find() method in JavaScript?


The find() method in JavaScript is used to find the first element in an array that
satisfies a certain condition. The find() method returns the value of the first
element that satisfies the condition, or undefined if no such element is found.
let numbers = [1, 2, 3, 4, 5];
let evenNumber = [Link]((number) => number % 2 === 0);
[Link](evenNumber); // 2

9
7- What is the difference between the slice() and splice() method
in JavaScript?

slice()
The slice() method in JavaScript is used to extract a portion of an array and
return a new array without modifying the original array. The slice() method
takes two arguments: the start index and the end index (optional). The slice()
method returns a new array containing the elements from the start index up to,
but not including, the end index.
let numbers = [1, 2, 3, 4, 5];
let slicedNumbers = [Link](1, 4);
[Link](slicedNumbers); // [2, 3, 4]
[Link](numbers); // [1, 2, 3, 4, 5]

splice()
The splice() method in JavaScript is used to add or remove elements from an
array. The splice() method takes three arguments: the start index, the number of
elements to remove, and optional elements to add. The splice() method modifies
the original array and returns an array containing the removed elements.
let numbers = [1, 2, 3, 4, 5];
let removedNumbers = [Link](1, 2);
[Link](removedNumbers); // [2, 3]
[Link](numbers); // [1, 4, 5]

8- What is the difference between rest and spread operator in


JavaScript?

Rest Operator
The rest operator is denoted by three dots (...) and is used to gather elements
into an array. The rest operator can be used to collect the remaining arguments
of a function into an array or to destructure an array into individual elements.
function sum(...numbers) {
return [Link]((acc, curr) => acc + curr, 0);
}

[Link](sum(1, 2, 3, 4, 5)); // 15

10
Spread Operator
The spread operator is also denoted by three dots (...) and is used to spread
elements from an array. The spread operator can be used to copy an array,
concatenate arrays, or pass elements of an array as arguments to a function.
let numbers = [1, 2, 3];
let newNumbers = [...numbers, 4, 5];
[Link](newNumbers); // [1, 2, 3, 4, 5]

9- What is the JSON object in JavaScript?


JSON (JavaScript Object Notation) is a lightweight data interchange format that
is easy for humans to read and write and easy for machines to parse and
generate. JSON is a text-based format and is used to represent structured data.
In JavaScript, the JSON object is used to parse and stringify JSON data. The
JSON object has two methods: [Link]() and [Link]().
let person = {
name: 'John',
age: 30,
city: 'New York'
};

let json = [Link](person);


[Link](json); // {"name":"John","age":30,"city":"New York"}

let obj = [Link](json);


[Link]([Link]); // John

11
Advance Steps
1- What is the Execution Context in JavaScript?
The execution context in JavaScript means that how the code executes is [Link]
execution context consists of two things or part Creational Phase and
Execution Phase.

Creation Phase
In the creation phase,the JS engine creates the global execution context and sets
up the memory space for variables and [Link] the variables are stored in
the memory space with the value of undefined and the function definition is
stored in the memory space.

let a=10; // In creations phase the value of all variables store as undefined
let b=a; // As the value of a is undefined so the value of b will be undefined

function print(){
[Link]("Hello World")
} // In creation phase the value of print will hold the function definition

Execution Phase
In the execution phase, the JavaScript engine assigns values to variables and
executes the code line by line. The JavaScript engine starts executing the code
from the top of the file and moves down line by line. The JavaScript engine
assigns values to variables, evaluates expressions, and executes function calls
during the execution phase.

let a=10; // In creations phase the value of all variables store as undefined

const print = function(){


[Link]("Hello World")
} // In creation phase the value of print will hold the function definition

print() // Hello World

12
2- What is the Global Execution Context and Function or Local
Execution Context in JavaScript?

Global Execution Context:


When a JavaScript program starts, the JavaScript engine creates the global
execution context. The global execution context is the outermost context and is
responsible for executing the global code. The global execution context consists
of the global object, the this keyword, the scope chain, and the variable object.

Function or Local Execution Context:


When a function is called in JavaScript, the JavaScript engine creates a new
execution context for that function. This new execution context is known as the
function or local execution context. This function execution context is also
consist of two parts Creation Phase and Execution Phase. The variables
declared inside the function have local scope and are only accessible within that
function. When the function completes execution, its execution context is
removed from the stack. We use call stack to determine the order of local
execution context

function print() {
let message = 'Hello World';
[Link](message);
}

print(); // Hello World

13
3- What is Hoisting in JavaScript?
As we already know that in the creation phase the value of all variables stored
as undefined and the function definition is stored in the variable [Link] which
means that I can access the variable before it is declared while executing the
code. This is known as the hoisting in JavaScript.

Hoisting only works for the function declaration and variable declared with var
keyword not with let and const keyword.
[Link](a); // undefined
var a = 10;

show(); // Hello World

function show() {
[Link]('Hello World');
}

4- Hoisting in case of let and const in JavaScript?


Hoisting only works for the function declaration and variable declared with var
keyword not with let and const keyword. When we use the let and const
keyword to declare a variable, the variable is hoisted to the top of the block
scope but not initialized. This means that you cannot access the variable before
it is declared, and you will get a ReferenceError if you try to access the variable
before its [Link] is known as the temporal dead [Link] is the time
between the variable hoisted to the top of the block scope and the variable
initialized.
[Link](a); // ReferenceError: Cannot access 'a' before initialization
let a = 10;

[Link](b); // ReferenceError: Cannot access 'b' before initialization


const b = 20;

5- Exercising the hoisting in JavaScript.


​ [Link](a); // Guess the output

var a = 10;

14
function a(){
[Link]("Hello World")
}

[Link](a); // Guess the output

[Link](a); // Guess the output

var a = 10;

a =function sum(){
[Link]("Hello World")
}

[Link](a); // Guess the output

[Link](b); // Guess the output

var a=b=10;

[Link](b); // Guess the output

show(); // Guess the output


showUsingVar(); // Guess the output
const show=()=>{
[Link]("Hello World")
}
var showUsingVar=()=>{
[Link]("Hello World")
};

6- What is a callback function in JavaScript?


A callback function is a function that is passed as an argument to another
function and is executed after the completion of the first function. Callback
functions are used to handle asynchronous operations, such as reading a file or

15
making an API request, and are commonly used in event handling, timers, and
AJAX requests.
function greet(name, callback) {
[Link]("Hello " + name);
callback();
}

function sayBye() {
[Link]("Goodbye!");
}

greet("Usama", sayBye);

7- What is a Promise in JavaScript?


In JavaScript, a promise is an object that represents the eventual completion or
failure of an asynchronous operation. A promise can be in one of three states:
pending, fulfilled, or rejected. When a promise is fulfilled, it means that the
operation was successful, and the promise returns a value. When a promise is
rejected, it means that the operation failed, and the promise returns an [Link]
also know that every action has a reaction so in both cases if our promise is
fulfilled then we have to do something and if our promise is rejected then we
have to do something. So we use the then() method to handle the fulfillment of a
promise and the catch() method to handle the rejection of a promise.
let promise=new Promise((resolve,reject)=>{
setTimeout(()=>{
let data="Hello World"
resolve(data)
},2000)
})

[Link]((data)=>{
[Link](data)
}).catch((error)=>{
[Link](error)
})

16
8- What is Async/Await in JavaScript?
Async/Await is a modern way to handle asynchronous operations in JavaScript.
Async/Await is built on top of promises and provides a more readable and
concise syntax for handling asynchronous code. The async keyword is used to
define an asynchronous function, and the await keyword is used to pause the
execution of an asynchronous function until a promise is settled. Async/Await
makes it easier to write and maintain asynchronous code by allowing you to
write asynchronous code that looks synchronous.
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve("Data received"), 2000);
});
}

async function showData() {


[Link]("Waiting...");
let result = await getData();
[Link](result);
}

showData();

17

You might also like