0% found this document useful (0 votes)
3 views

JS

Uploaded by

anjanashri108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JS

Uploaded by

anjanashri108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Chapter 1: Introduction to JavaScript

● What is JavaScript
● History of JavaScript
● Client-Side & Server-side JavaScript
● First JavaScript Code
● Dialogue boxes (alert, Confirmation Dialog Box, Prompt Dialog Box)
● JS predefined words

Chapter 2: Understanding Variables and Data Types

● Data types
● Variables and constants
● Scope and Closures
● Type Coercion and Type Conversion

Chapter 3: Conditionals and arrays

● Conditional Statements (if, else if else)


● Logical Operators (&&, ||, !, ==)
● Switch Statements
● Loops (for, while, do-while)
● Array syntax, Properties & Array constructor

Chapter 4: Functions

● Functions
● Function Declaration vs. Function Expression (Parameters and Arguments)
● Return Values and Scope
● Nested Functions
● Higher-Order Functions and Callbacks
● Arrow Functions

Chapter 5: Array Function methods

● concat()
● shift(), unshift()
● split(), join(), reverse()
● map()
● filter()
● push(), pop(), splice()
● eval()
● reduce()
● forEach()
● toString()
● slice()
● length()

Chapter 6: string methods

● charAt()
● indexOf()
● toUpperCase()
● toLowerCase()
● includes()
● replace()

Chapter 7: Math methods

● floor()
● ceil()
● sqrt()
● round()
● pow()
● random()

Chapter 8: Date operators

● Current date.getFullYear, Month, Date, Day, Hours, Minutes, Seconds,


Milliseconds,
● toDateString(), toLocaleDateString (), toLocaleTimeString ()

Chapter 9: Document Object Model (DOM)

● What is the DOM?


● Selecting DOM Elements
● Manipulating HTML Content & Changing CSS Styles
● Adding and Removing DOM Elements
● Event Handling (onclick, onsubmit, onmouseover and onmouseout)
● addEventListener properties
● Practical DOM Manipulation and event handling Examples

Chapter 10: Objects

● Object keys, values, entries


● Object overrides
● Object assign
● Object & Array destructing
● Spread operator
JAVASCRIPT

Chapter 1: Introduction to JavaScript

● What is JavaScript
➢ JavaScript is a high-level, interpreted programming language
primarily used for making web pages interactive.
➢ It was created to add dynamic and interactive elements to web pages,
allowing them to respond to user actions
➢ JavaScript can be embedded directly into HTML code and executed
by web browsers, making it an essential component of web
development.

● A Brief History of JavaScript


➢ Creation by Brendan Eich: JavaScript was created by Brendan Eich in
1995 while he was working at Netscape Communications Corporation.

➢ Launch and Early Adoption: JavaScript was introduced alongside


Netscape in December 1995, quickly gaining resistance among web
developers for its ability to add interactivity to web pages.

➢ Standardisation: In 1996, Netscape submitted JavaScript to Ecma


International for standardisation. This led to the creation of the
ECMAScript version.

➢ Evolution: JS underwent rapid evolution with the introduction of new


features through updates to the ECMAScript specification.
➢ JS in backend: With the emergence of server-side JavaScript
platforms like Node.js in 2009, JavaScript enabled developers to build
backend services and web applications using a single language.

➢ Structure and branches of JS: The rapid rise of JavaScript structure


and libraries, such as React, Angular, and Vue.js, revolutionised web
development by providing tools for building complex and interactive
web applications efficiently.
➢ Omni-Presence: Today, JavaScript is ubiquitous, powering the majority
of websites and applications. Its versatility and performances have
solidified its position as a foundation of modern web development.

● Client-Side & Server-side JavaScript


➢ Client-side JavaScript refers to JavaScript code that is executed on
the client's browser. When a user visits a website, the HTML, CSS, and
JavaScript files are downloaded to the client's browser. The JavaScript
code runs locally on the client's machine, allowing for dynamic
interactions and modifications to the webpage without needing to
reload the entire page.

➢ Server-side JavaScript refers to JavaScript code that is executed on


the server instead of the client's browser. In this context, JavaScript is
used to handle server-side logic, process incoming requests, interact
with databases, and generate dynamic content that is then sent to
the client.

● First JavaScript Code

var message = "Hello, world!";


console.log(message);

➢ Defines a variable named ‘message’


➢ assigns it the string value “Hello, world!”;
➢ Uses console.log() to print the value of the ‘message’ variable to the
browser's console.
➢ you'll see the output "Hello, world!"
➢ Dialogue boxes (alert, Confirmation Dialog Box, Prompt Dialog Box)

● Dialogue boxes (alert, Confirmation Dialog Box, Prompt Dialog Box)


➢ Alert Dialog Box
★ A pop-up window that displays a message to the user.
★ Typically contains a message and an OK button.
★ When the alert dialog box is displayed, it halts the execution
of the JavaScript code until the user clicks the OK button.
★ alert("This is an alert message!");

➢ Confirmation Dialog Box:


★ A confirmation dialog box in JavaScript is a pop-up window
that asks the user to confirm or cancel an action.
★ It typically contains a message and two buttons: OK and
Cancel.
★ When the confirmation dialog box is displayed, it halts the
execution of the JavaScript code until the user clicks either
the OK or Cancel button.
★ confirm("Do you want to proceed?");

➢ Prompt Dialog Box:


★ A prompt dialog box in JavaScript is a pop-up window that
prompts the user to enter some input.
★ It typically contains a message, an input field for the user to
enter text, and two buttons: OK and Cancel.
★ When the prompt dialog box is displayed, it halts the
execution of the JavaScript code until the user enters text
and clicks either the OK or Cancel button.
★ prompt("Please enter your name:");

● JS predefined words:
➢ Keywords for Variable Declaration:
★ var: Declares a variable.
★ let: Declares a block-scoped variable.
★ const: Declares a block-scoped constant variable.

➢ Control Flow Statements:


★ if, else: Conditionally executes code.
★ switch, case, default: Selectively executes code based on
the value of an expression.
★ for, while, do...while: Loops that execute code repeatedly

➢ Functions:
★ function: Declares a function.
★ return: Exits a function and optionally specifies a value to
be returned.

Chapter 2: Understanding Variables and Data Types

● Data types
➢ Primitive Data Types:
★ Number: Represents numeric values, both integers and
floating-point numbers. let age = 30;
★ String: Represents textual data, enclosed in single ('') or
double ("") quotes. let name = "John";
★ Boolean: Represents a logical value, either true or false.
let isStudent = true;

➢ Composite Data Types:


★ Object: Represents a collection of key-value pairs, where keys
are strings (or Symbols) and values can be any data type,
including other objects. let person = { name: "Alice",
age: 25 };
★ Array: Represents an ordered list of values, stored at integer
indices starting from 0. let numbers = [1, 2, 3, 4, 5];
★ Function: Represents a reusable block of code that can be
called function greet(name) {
console.log("Hello, " + name + "!");
}
★ Date: Represents a specific point in time, with methods to
manipulate dates and times. let currentDate = new
Date();
★ Math: provides a set of properties and methods for
performing mathematical tasks. Math.add(a, b);

➢ Special Data Types:


★ Undefined: A primitive data type representing an
uninitialized variable or a function without a return value.
let score;
★ Null: A primitive data type representing the intentional
absence of any object value. let result = null;
★ NaN: A special numeric value representing "Not-a-Number,"
returned when a mathematical operation cannot produce a
meaningful result. let result = "Hello" / 2;
console.log(result); (result: NaN)

● Variables and constants


➢ Variables:
★ Variables are used to store data that can be changed or
reassigned during the execution of a program.
★ Declaration: let and var
★ ‘=’ assignment operator for assigning values
★ var age = 25;
let name = ‘Anju’;
➢ Constants:
★ Constants are similar to variables, but their values cannot
be changed once they are assigned.
★ Declaration: const
★ ‘=’ assignment operator for assigning values
★ const PI = 3.14;

● Scope and Closures

Scopes in JavaScript refer to the areas of code where variables are


accessible

Closures, allow functions to remember and access the variables from


their outer scopes even after those outer scopes have finished
executing.

● Type Coercion and Type Conversion

Type Coercion:

➢ Type coercion is the automatic conversion of data types by


JavaScript during operations. It occurs when values of different types
are used together in an expression. JavaScript tries to convert one of
the values to match the other value's type before performing the
operation.

let result = 10 + "5"; // JavaScript coerces the number 10


to a string, resulting in "105"

Type Conversion:

➢ Type conversion is the explicit conversion of data types using


JavaScript functions or operators. Developers explicitly convert a
value from one data type to another when needed.

let stringNumber = "10";


let number = parseInt(stringNumber); // Convert the string
"10" to a number using parseInt

Chapter 3: Conditionals and arrays

● Conditional Statements (if, else, else if)


➢ Conditional statements in JavaScript allow you to execute different
blocks of code based on certain conditions

If: :Executes a block of code if a specified condition is true.

let temperature = 25;

if (temperature > 20) {


console.log("It's a warm day!"); // Output: It's a warm day!
}

Else: Executes a block of code if the if condition is false.


let age = 20;
if (age >= 18) {
console.log("You are an adult."); // Output
} else {
console.log("You are a minor.");
}

Else if: Allows you to check additional conditions if the previous condition is
false.

let score = 75;


if (score >= 90) {
console.log("You got an A!");
} else if (score >= 80) {
console.log("You got a B!");
} else {
console.log("You need to study harder!");
}

● Logical Operators (&&, ||, !, ==):


➢ And Operator (&&):
★ Returns true if both operands are true, otherwise returns
false.
★ (x > 0 && y < 10)
➢ Or Operator (||):
★ Returns true if at least one of the operands is true, otherwise
returns false.
★ (x == "foo" || y === "bar")
➢ Not Operator (!):
★ Reverses the logical state of its operand (true becomes false,
and false becomes true).
★ (x!=2)

(==) operator: Returns true if the values are equal (even with different
data types) after type coercion, otherwise returns false. 0 =='0' // true

(===) operator: Returns true if the values are equal in both value and
data type, otherwise returns false. 0 === '0' // false

● Switch Statements

Switch statements provide a way to execute different blocks of code


based on the value of a variable or expression.

It's an alternative to using multiple if statements for such scenarios.

let day = "Monday";

switch (day) {
case "Monday":
console.log("It's the start of the week.");
case "Tuesday":
console.log("It's Tuesday!");
case "Wednesday":
console.log("It's midweek.");
default:
console.log("It's some other day.");
}
● Loops (for, while, do-while)

Used to execute a block of code repeatedly until the certain condition


is met.

They provide a way to automate repetitive tasks and iterate over


collections of data.

➢ For Loop: Executes a block of code a specified number of times.

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


console.log(i); // Output: 0, 1, 2, 3, 4
}

➢ While Loop: Executes a block of code while a specified condition is


true.
let i = 0;
while (i < 5) {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
}

➢ Do-While Loop: Executes a block of code once, then repeats the loop
as long as a specified
let i = 0;
do {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
} while (i < 5);

● Array syntax, Properties & Array constructor


➢ Array:
★ An ordered collection of values, accessed by numeric indices
from 0,1,2…
★ declared using square brackets [ ] and separated by commas.
let numbers = [1, 2, 3, 4, 5];
➢ Properties:
★ length: Returns the number of elements in the array.
➢ Array constructor:
★ The array( ) constructor creates an array object with a specified
length or set of elements.
let numbers = new Array(1, 2, 3, 4, 5);
console.log(numbers);
Chapter 4: Functions

● Functions : A function is a named block of code that can be called or


invoked to perform a specific task. Functions can accept input values, called
parameters, and can return a value as output.

function greet(name) {
console.log("Hello, " + name + "!");
}

● Function Declaration vs. Function Expression (Parameters and Arguments)


➢ Function Declaration:
★ Defined using the ‘function’ keyword followed by the function
name and parameters.
★ Can be called before or after the declaration.

function add(a, b) {
return a + b;
}

➢ Function Expression:
★ Defined by assigning a function to a variable or a constant.
★ Cannot be called before declaration.

const add = function(a, b) {


return a + b;
};

➢ Parameters: Variables listed in the function definition.


➢ Arguments: Values passed to the function when it is called.

function greet(name) { // 'name' is a parameter


console.log("Hello, " + name + "!");
}

greet("Alice"); // 'Alice' is an argument

● Return Values and Scope


➢ Return Values:
★ Functions can return a value using the return keyword.
★ The returned value can be of any data type, such as a
number, string, object, or even another function.

function add(a, b) {
return a + b;
}
let result = add(3, 5); // Calling the function and
storing its return value
console.log(result); // Output: 8

➢ Scope:
★ JavaScript has function scope, meaning variables declared
within a function are only accessible within that function.
★ Variables declared outside of any function have global
scope, making them accessible from anywhere in the script.

let globalVar = "I'm a global variable";

function myFunction() {
let localVar = "I'm a local variable";
console.log(globalVar); // Accessible from inside
the function
console.log(localVar); // Accessible from inside
the function
}

console.log(globalVar); // Accessible from anywhere


console.log(localVar); // Error: localVar is not
defined

(In this example, add function returns the sum of two numbers, and the result
variable stores the return value. In terms of scope, globalVar is accessible
globally, while localVar is accessible only within the myFunction function. Trying
to access localVar outside of myFunction will result in an error.)

● Nested Functions:

Nested functions in JavaScript are functions defined within another


function. They have access to the outer function's variables and
parameters, as well as global variables.

function outerFunction() {
let outerVariable = "I'm from outerFunction";

function innerFunction() {
console.log(outerVariable); // Access outerVariable from
outerFunction
}
innerFunction(); // Call innerFunction
}

outerFunction(); // Call outerFunction

● Higher-Order Functions and Callbacks


➢ Higher-order functions are functions that either take other functions
as arguments or return functions as output.
➢ Callbacks are functions passed as arguments to other functions and
are executed after some operation has been completed.

function higherOrderFunction(callback) {
console.log("Performing some operation...");
callback(); // Execute the callback function
}

function callbackFunction() {
console.log("Callback function executed!");
}

higherOrderFunction(callbackFunction); // Pass
callbackFunction as an argument

● Arrow Functions:

A concise way to write functions which provides a shorter syntax


compared to traditional function expressions.

let add = (a, b) => a + b;

Chapter 5: Array Function methods

● concat():

Method in JavaScript used to merge two or more arrays, creating a


new array without modifying the original arrays.

let arr1 = [1, 2, 3];


let arr2 = [4, 5, 6];
let mergedArray = arr1.concat(arr2);
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
● shift(), unshift():
➢ shift( ): Method used to remove the first element from an array
and return that removed element.

let fruits = ['apple', 'banana', 'orange'];


let removedFruit = fruits.shift();
console.log(removedFruit); // Output: 'apple'
console.log(fruits); // Output: ['banana', 'orange']

➢ unshift( ): Method used to add one or more elements to the


beginning of an array and returns the new length of the array.

let newLength = fruits.unshift('grape');


console.log(newLength); // Output: 3
console.log(fruits); // Output: ['grape', 'banana',
'orange']

● split(), join(), reverse()


➢ split( ): method used to split a string into an array of substrings
based on a specified separator

let str = "apple,banana,orange";

let arr = str.split(',');


console.log(arr); // Output: ['apple', 'banana',
'orange']

➢ join( ): method used to join all elements of an array into a string.

let joinedStr = arr.join('-');


console.log(joinedStr); // Output:
'apple-banana-orange'

➢ reverse( ): method used to reverse the order of elements in an


array.

arr.reverse();
console.log(arr); // Output: ['orange', 'banana',
'apple']
● map()

Applies a function to each element of an array and returns a new


array with the results.

let numbers = [1, 2, 3];


let doubled = numbers.map(num => num * 2); // doubled: [2,
4, 6]

● filter()

Creates a new array with all elements that pass a test specified by a
provided function.

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


let evens = numbers.filter(num => num % 2 === 0); // evens:
[2, 4]

● push(), pop(), splice()


➢ Push( ): Adds one or more elements to the end of an array and
returns the new length of the array.

let fruits = ['apple', 'banana'];


fruits.push('orange'); // fruits: ['apple', 'banana',
'orange']

➢ pop( ): Removes the last element from an array and returns that
element.

let fruits = ['apple', 'banana', 'orange'];


let removedFruit = fruits.pop(); // removedFruit:
'orange', fruits: ['apple', 'banana']

➢ splice( ): Changes the contents of an array by removing or


replacing existing elements and/or adding new elements in
place.

let fruits = ['apple', 'banana', 'orange'];


fruits.splice(1, 1, 'grape'); // fruits: ['apple',
'grape', 'orange']

● eval()

Evaluates JavaScript code represented as a string.

let x = 10;
let result = eval('x * 2'); // result: 20
● reduce()

Applies a function against an accumulator and each element in the


array (from left to right) to reduce it to a single value.

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


let sum = numbers.reduce((accumulator, currentValue) =>
accumulator + currentValue, 0); // sum: 15

● forEach()

Executes a provided function once for each array element.

let numbers = [1, 2, 3];


numbers.forEach(num => console.log(num)); // Output: 1 2 3

● toString()

Converts an array to a string by joining all its elements into a single


string.

let fruits = ['apple', 'banana', 'orange'];


let fruitsString = fruits.toString(); // fruitsString:
'apple,banana,orange'

● slice()

Returns a shallow copy of a portion of an array into a new array


object selected from start to end (end not included).

let fruits = ['apple', 'banana', 'orange', 'grape'];


let slicedFruits = fruits.slice(1, 3); // slicedFruits:
['banana', 'orange']

● length()

Returns the number of elements in an array or the number of


characters in a string.

let fruits = ['apple', 'banana', 'orange'];


let fruitsLength = fruits.length; // fruitsLength: 3
Chapter 6: string methods

● charAt()

Returns the character at the specified index (position) in a string.

let str = 'Hello';


let char = str.charAt(2); // char: 'l'

● indexOf()

Returns the first index at which a given element can be found in the
array, or -1 if it is not present.

let fruits = ['apple', 'banana', 'orange'];


let index = fruits.indexOf('banana'); // index: 1

● toUpperCase()

Converts a string to uppercase letters.

let str = 'hello';


let upperCaseStr = str.toUpperCase(); // upperCaseStr:
'HELLO'

● toLowerCase()

Converts a string to lowercase letters.

let str = 'HELLO';


let lowerCaseStr = str.toLowerCase(); // lowerCaseStr:
'hello'

● includes():

Determines whether an array includes a certain element, returning


true or false as appropriate.

let fruits = ['apple', 'banana', 'orange'];


let includesBanana = fruits.includes('banana'); //
includesBanana: true

● replace()

Returns a new string with some or all matches of a pattern replaced


by a replacement.
let str = 'Hello, world!';
let newStr = str.replace('world', 'JavaScript'); // newStr:
'Hello, JavaScript!'

Chapter 7: Math methods

● floor()

Returns an integer less than or equal to a given number.

let num = 5.8;


let roundedNum = Math.floor(num); // roundedNum: 5

● ceil()

Returns an integer greater than or equal to a given number.

let num = 5.2;


let roundedNum = Math.ceil(num); // roundedNum: 6

● sqrt()

Returns the square root of a number.

let num = 25;


let squareRoot = Math.sqrt(num); // square Root: 5

● round()

Returns the value of a number rounded to the nearest integer.

let num = 5.4;


let roundedNum = Math.round(num); // roundedNum: 5

● pow()

Returns the value of base to the exponent power. (base^exponent)

let base = 2;
let exponent = 3;
let result = Math.pow(base, exponent); // result: 8
● random()

Returns a random floating-point number between 0 (inclusive) and 1


(exclusive).

let randomNumber = Math.random(); // Generates a random


number between 0 and 1

Chapter 8: Date operators

● Current date.getFullYear, Month, Date, Day, Hours, Minutes, Seconds,


Milliseconds() :
➢ getFullYear( ):

Returns the year of the specified date according to local time.

let currentDate = new Date();


let year = currentDate.getFullYear(); // year: current
year

➢ getMonth( ):

Returns the month of the specified date according to local time,


ranging from 0 (January) to 11 (December).

let currentDate = new Date();


let month = currentDate.getMonth(); // month: current
month (0 to 11)

➢ getDate( ):

Returns the day of the month for the specified date according
to local time.

let currentDate = new Date();


let date = currentDate.getDate(); // date: current day
of the month

➢ getDay( ):

Returns the day of the week for the specified date according to
local time, ranging from 0 (Sunday) to 6 (Saturday).
let currentDate = new Date();
let day = currentDate.getDay(); // day: current day of
the week (0 to 6)

➢ getHours( ):

Returns the hour for the specified date according to local time,
from 0 to 23.

let currentDate = new Date();


let hours = currentDate.getHours(); // hours: current
hour (0 to 23)

➢ getMinutes( ):

Returns the minutes in the specified date according to local


time, from 0 to 59.

let currentDate = new Date();


let minutes = currentDate.getMinutes(); // minutes:
current minutes (0 to 59)

➢ getSeconds( ):

Returns the seconds in the specified date according to local


time, from 0 to 59.

let currentDate = new Date();


let seconds = currentDate.getSeconds(); // seconds:
current seconds (0 to 59)

➢ getMilliseconds( ):

Returns the milliseconds in the specified date according to local


time, from 0 to 999.

let currentDate = new Date();


let milliseconds = currentDate.getMilliseconds(); //
milliseconds: current milliseconds (0 to 999)
● toDateString(), toLocaleDateString(), toLocaleTimeString():
➢ toDateString():

Returns the date portion of a Date object as a human-readable


string.

let currentDate = new Date();


let dateString = currentDate.toDateString(); //
dateString: "Wed Mar 31 2024"

➢ toLocaleDateString():

Returns a string with a language-sensitive representation of the


date portion of a Date object.

let currentDate = new Date();


let dateString = currentDate.toLocaleDateString();
// dateString: depending on the locale, e.g.,
"3/31/2024" or "31/03/2024"

➢ toLocaleTimeString():

Returns a string with a language-sensitive representation of the


time portion of a Date object.

let currentDate = new Date();


let timeString = currentDate.toLocaleTimeString(); //
timeString: depending on the locale, e.g., "8:30:00 PM"
or "20:30:00"

Chapter 9: Document Object Model (DOM)

● What is the DOM?


➢ DOM is a programming interface that allows us to create, change, or
remove elements from the document.
➢ We can also add events to these elements to make our page more
dynamic.
● Selecting DOM Elements
➢ Select elements from the DOM based on their ID, class, or CSS
selector.

let myElement = document.getElementById('myElement');

● Manipulating HTML Content & Changing CSS Styles


➢ Manipulating Elements: Once selected an element, we can manipulate
its properties, attributes, or content

myElement.innerHTML = 'New content';


myElement.style.color = 'red';

● Adding and Removing DOM Elements


➢ Adding:

we can create new elements and then append them to an existing


element

let newDiv = document.createElement('div');


document.body.appendChild(newDiv);

➢ removing:

you can use methods like remove( ) on the parent element containing
the element you want to remove.

let elementToRemove =
document.getElementById('element-to-remove');
elementToRemove.remove();

● Event Handling (onclick, onsubmit, onmouseover and onmouseout):

Involves responding to actions or occurrences (events) that happen in the


browser, such as user interactions, like clicking a button, submitting a form,
moving the mouse, etc.

➢ onclick: Occurs when an element is clicked.

<button onclick="handleClick()">
➢ onsubmit: Occurs when a form is submitted.

<form onsubmit="handleSubmit()">

➢ onmouseover: Occurs when the mouse pointer moves over an


element.
➢ onmouseout: Occurs when the mouse pointer moves out of an
element.

<div onmouseover="handleMouseOver()"
onmouseout="handleMouseOut()">

● addEventListener properties
➢ Target Element: Specifies the HTML element to which the event
listener will be added.

➢ Event Type: Defines the type of event to listen for, such as "click",
"mouseover", "keydown", etc.

➢ Event Handler Function: Specifies the function to be executed


when the event occurs.

➢ Options: Optional parameter that allows specifying additional


options for the event listener

Chapter 10: Objects

● Object keys, values, entries


➢ Keys: method that returns an array of a given object's own
countless property names. It provides a way to access the keys
of an object.

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj)); //array of keys

➢ Values: method that returns an array containing the values of


the enumerable properties of a given object. It provides a way to
access the values of an object.

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj)); //array of values
➢ Entries: method that returns an array containing the
enumerable property key-value pairs of a given object as arrays.
It provides a way to access both keys and values of an object
simultaneously.

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.entries(obj)); //array of the
entered value

● Object overrides:

When an object has duplicate keys, the last occurrence of the key will
override the previous ones.

let myObj = { a:10, b:20, c:30, d:10, a:40 }


console.log(myObj); //a: 40, b: 20, c: 30, d: 10

● Object assign:

This method copies all the properties from one source objects to a
target object and returns the target object.

const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };
const merged = Object.assign(target, source);
console.log(merged);

● Object & Array destructing:


➢ Object destructing:

allows you to extract properties from objects and assign them to


variables. It provides a convenient way to access and use object
properties

const obj = { a: 1, b: 2, c: 3 };
let { a, c, b } = obj;
console.log(a, c, b);
➢ Array destructing:

allows you to unpack values from arrays into distinct variables


using a concise syntax. It simplifies the process of accessing
and using elements stored in arrays.

const numbers = [10, 20, 30, 40, 50];


const [first, second, third] = numbers;
console.log(second);

● Spread operator

allows for easy copying of arrays, merging arrays, and passing


multiple arguments to functions.

let arr1 = [1,2,3,4]


let arr2 = [5,6,7,8]
let arr3 = [...arr1,...arr2]
console.log(arr3);

You might also like