0% found this document useful (0 votes)
5 views74 pages

Javascript

The document provides an overview of JavaScript, detailing its capabilities such as manipulating HTML and CSS, performing calculations, and validating data. It covers fundamental concepts including variable declarations, operators, data types, functions, and control flow statements, along with examples for each. Additionally, it explains how to define and invoke functions, including different types of functions and their syntax.

Uploaded by

famebox
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)
5 views74 pages

Javascript

The document provides an overview of JavaScript, detailing its capabilities such as manipulating HTML and CSS, performing calculations, and validating data. It covers fundamental concepts including variable declarations, operators, data types, functions, and control flow statements, along with examples for each. Additionally, it explains how to define and invoke functions, including different types of functions and their syntax.

Uploaded by

famebox
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

JavaScript

 JavaScript is the programming language of the web.


 It can update and change both HTML and CSS.
 It can calculate, manipulate and validate data.
 JavaScript Can Change HTML Content.
JavaScript is Case Sensitive
<script> Tag:
In HTML, JavaScript code is inserted between <script> and </script> tags.
<script src=”[Link]”></script>
JavaScript can "display" data in different ways:
 Writing into an HTML element, using innerHTML.
 Writing into the HTML output using [Link]().
 Writing into an alert box, using [Link]().
 Writing into the browser console, using [Link]().
JavaScript Values:
 Fixed values
 Variable values
variables are used to store data values
JavaScript uses the keywords var, let and const to declare variables.
JavaScript Const
var x = 5;
var y = 6;
var z = x + y;
let x = 10;
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Toyota";
[Link]("Audi");
JavaScript Operators
Types of JavaScript Operators
There are different types of JavaScript operators:
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 String Operators
 Logical Operators
 Bitwise Operators
 Ternary Operators
 Type Operators
JavaScript Arithmetic Operators:
Arithmetic Operators are used to perform arithmetic on numbers.
addition operator (+) adds numbers
subtraction operator (-) subtracts numbers
multiplication operator (*) multiplies numbers.
division operator (/) divides numbers.
modulus operator (%) returns the division remainder.
increment operator (++) increments numbers.
decrement operator (--) decrements numbers.
exponentiation operator (**) raises the first operand to the power of the second
operand.
JavaScript Assignment
The = Operator
The Simple Assignment Operator assigns a value to a variable.
Simple Assignment Examples
let x = 10;
The += Operator
The Addition Assignment Operator adds a value to a variable.
Addition Assignment Examples
let x = 10;
x += 5;
The -= Operator
The Subtraction Assignment Operator subtracts a value from a variable.
Subtraction Assignment Example
let x = 10;
x -= 5;
The *= Operator
The Multiplication Assignment Operator multiplies a variable.
The **= Operator
The Exponentiation Assignment Operator raises a variable to the power of
the operand.
Exponentiation Assignment Example
let x = 10;
x **= 5;
The /= Operator
The Division Assignment Operator divides a variable.
Division Assignment Example
let x = 10;
x /= 5;
The %= Operator
The Remainder Assignment Operator assigns a remainder to a variable.
Remainder Assignment Example
let x = 10;
x %= 5;
The <<= Operator
The Left Shift Assignment Operator left shifts a variable.
Left Shift Assignment Example
let x = -100;
x <<= 5;
The >>= Operator
The Right Shift Assignment Operator right shifts a variable (signed).
Right Shift Assignment Example
let x = -100;
x >>= 5;
The >>>= Operator
The Unsigned Right Shift Assignment Operator right shifts a variable
(unsigned).
Unsigned Right Shift Assignment Example
let x = -100;
x >>>= 5;
The &= Operator
The Bitwise AND Assignment Operator does a bitwise AND operation on two
operands and assigns the result to the the variable.
Bitwise AND Assignment Example
let x = 10;
x &= 5;
The |= Operator
The Bitwise OR Assignment Operator does a bitwise OR operation on two
operands and assigns the result to the variable.
Bitwise OR Assignment Example
let x = 10;
x |= 5;
The ^= Operator
The Bitwise XOR Assignment Operator does a bitwise XOR operation on two
operands and assigns the result to the variable.
Bitwise XOR Assignment Example
let x = 10;
x ^= 5;
The &&= Operator
The Logical AND assignment operator is used between two values.
If the first value is true, the second value is assigned.
Logical AND Assignment Example
let x = 10;
x &&= 5;
The ||= Operator
The Logical OR assignment operator is used between two values.
If the first value is false, the second value is assigned.
Logical OR Assignment Example
let x = 10;
x ||= 5;
The ??= Operator
The Nullish coalescing assignment operator is used between two values.
If the first value is undefined or null, the second value is assigned.
Nullish Coalescing Assignment Example
let x;
x ??= 5;
JavaScript Data Types:
JavaScript has 8 Datatypes
String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object
Examples:
// Numbers:
let length = 16;
let weight = 7.5;

// Strings:
let color = "Yellow";
let lastName = "Johnson";

// Booleans
let x = true;
let y = false;

// Object:
const person = {firstName:"John", lastName:"Doe"};

// Array object:
const cars = ["Saab", "Volvo", "BMW"];

// Date object:
const date = new Date("2022-03-25");
One of many JavaScript HTML methods is getElementById().
Simple program:
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button"
onclick='[Link]("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>

JavaScript Can Change HTML Styles (CSS):


Changing the style of an HTML element, is a variant of changing an HTML
attribute.
Example:
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button"
onclick="[Link]('demo').[Link]='35px'">Click Me!
</button>
JavaScript Can Hide HTML Elements:
Hiding HTML elements can be done by changing the display style.
Example:
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button"
onclick="[Link]('demo').[Link]='none'">Click Me!
</button>
JavaScript Can Show HTML Elements:
Showing hidden HTML elements can also be done by changing the display style
Example:
[Link]("demo").[Link] = "block";
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
JavaScript Function Syntax:
A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function Return:
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to
the "caller".
Example:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
let x = myFunction(4, 3);
[Link]("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>
Function Arguments:
function welcome(name) {
[Link]("Hey " + "" + name + " " + "welcome to GfG");
}

// Passing arguments
welcome("Rohan");
Return Value:
function welcome() {

// Return statement
return "Welcome to GfG";
}

[Link](welcome());
Function Expression:
let welcome = function () {
return "Welcome to GfG";
}

let gfg = welcome();

[Link](gfg);
Types Of Functions in JavaScript:
1. Named function:
function add(a, b) {
return a + b;
}
[Link](add(5, 4));
[Link] function:
let add = function (a, b) {
return a + b;
}
[Link](add(5, 4));

[Link] Functions:
function msg(firstName) {
function hey() {
[Link]("Hey " + firstName);
}
return hey();
}
msg("Ravi");
[Link] invoked function expression:
let msg = (function() {
return "Welcome to GfG" ;
})();
[Link](msg);
JavaScript Function Call:
The call() method is a predefined JavaScript method. It can be used to invoke
(call) a method with an owner object as an argument (parameter).
Example:
function product(a, b) {
return a * b;
}
// Calling product() function
let result = [Link](this, 20, 5);
[Link](result);
Example:
let employee = {
details: function (designation, experience) {
return [Link]
+""
+ [Link]
+ designation
+ experience;
}
}
// Objects declaration
let emp1 = {
name: "A",
id: "123",
}
let emp2 = {
name: "B",
id: "456",
}
let x = [Link](emp2, " Manager ", "4 years");
[Link](x);
Different ways of writing functions in JavaScript:
1. Function Declaration:
A Function Declaration is the traditional way to define a function. It starts with
the function keyword, followed by the function name and any parameters the
function needs.
Example:
// Function declaration
function add(a, b) {
[Link](a + b);
}
// Calling a function
add(2, 3);
2. Function Expression:
Function Expression is another way to define a function. Here, the function is
defined inside a variable, and the function’s value (its returned value) is stored
in that variable.

// Function Expression
const add = function (a, b) {
[Link](a + b);
}
// Calling function
add(2, 3);
3. Arrow Functions:
Arrow Functions were introduced in ES6 (a newer version of JavaScript). They
provide a shorter syntax for writing functions. Instead of using the function
keyword, you use an arrow (=>).
let add = (a, b) => a + b;
[Link](add(3, 2));
Different Function States in JavaScript
the difference between
[Link] Person( ) { },
[Link] person = Person ( )
[Link] person = new Person ( ).
Example:
// Function declaration
function person() { }
let person = person()
// Printing the return value
// of the person() function
[Link](person)
function person1(name) {
return name;
}
let person1 = person1("Aayush")
// Printing the value of person1
[Link](person1)
function constructor in Javascript:
// Creating the function
function Person(name, age) {
[Link] = name;
[Link] = age;
}
// Calling the function
let person = new Person("Vikah", 22);
[Link]([Link]);
[Link]([Link]);
Example:
<body>
<h3> LOGIN </h3>
<formform ="Login_form" onsubmit="submit_form()">
<h4> USERNAME</h4>
<input type="text" placeholder="Enter your email id"/>
<h4> PASSWORD</h4>
<input type="password" placeholder="Enter your password"/></br></br>
<input type="submit" value="Login"/>
<input type="button" value="SignUp" onClick="create()"/>
</form>
<script type="text/javascript">
function submit_form(){
alert("Login successfully");
}
function create(){
[Link]="[Link]";
}
</script>
JavaScript Statements
JavaScript statements are programming instructions that a computer
executes. A computer program is essentially a list of these
“instructions” designed to perform tasks. In a programming language,
such instructions are called statements.
Types of Statements:
1. Variable Declarations (var, let, const):
Example:
let name = "Mohan"; // Declaration with 'let'
const age = 25; // Declaration with 'const' (constant value)
var isActive = true; // Declaration with 'var' (older version)
2. Assignment Statement:
An assignment statement is used to assign a value to a variable.
Example:
let number = 10; // Assigning a number
let message = "Hello, World!"; // Assigning a string
3. Expression Statements:
An expression in JavaScript is any valid unit of code that resolves to a
value.
Example:
x = y + 10; // Expression statement
[Link](x); // Expression statement using a function call.
4. Control Flow Statements:
Control flow statements are used to control the order in which
statements are executed in a program. Examples include if, else,
switch, while, and for loops.
Example:
let number = 10;
if (number > 5) {
[Link]("Number is greater than 5");
}
5. Function Declarations:
A function declaration is a statement that defines a function in
JavaScript. Functions are reusable blocks of code designed to perform
specific tasks.
Example:
function greet(name) {
return "Hello, " + name;
}

[Link](greet("Alisha"));
6. Return Statement:
The return statement is used to exit a function and optionally pass a
value back to the calling code.
Example:
function add(x, y) {
return x + y;
}
let result = add(5, 3); // result will be 8
7. Throw Statement:
The throw statement is used to create custom errors in JavaScript. It is
often used in conjunction with try…catch to handle errors.
Example:
function checkAge(age) {
if (age < 18) {
throw new Error("Age must be 18 or older");
}}
9. Break and Continue Statements:
The break and continue statements are used within loops. break exits
the loop, while continue skips to the next iteration.
Example:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exits the loop when i equals 5
}
[Link](i);
}
JavaScript if-else:
JavaScript if-else statement executes a block of code based on a
condition. If the condition evaluates to true, the code inside the “if”
block executes; otherwise, the code inside the “else” block, if present,
executes.
JavaScript if-statement
if(condition)
{
}
JavaScript if-else statement
if (condition){
//statement
}
Else{
//statement
}
Example:
// JavaScript program to illustrate If-else statement
let i = 10;
if (i < 15)
[Link]("i is less than 15");
else
[Link]("I am Not in if");
JavaScript nested-if statement:
JavaScript allows us to nest if statements within if statements. i.e, we
can place an if statement inside another if statement. A nested if is an
if statement that is the target of another if or else.
Syntax:
if(condition1){
if(condition2){}}

Example:
// JavaScript program to illustrate nested-if statement
let i = 10;
if (i == 10) { // First if statement
if (i < 15) {
[Link]("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
[Link]("i is smaller than 12 too");
else
[Link]("i is greater than 15");
}
}
JavaScript if-else-if ladder statement
Syntax:
if (condition){
//statement
}
Else if(condition2){
//statement
}
Else{}

Example:
// JavaScript program to illustrate nested-if statement
let i = 20;
if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
Example:
<h1>JavaScript Statements</h1>
<h2>The if...else Statements</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb" type="text">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
// Get the value of input field with id="numb"
x = [Link]("numb").value;

// If x is Not a Number or less than one or greater than 10, output


"input is not valid"
// If x is a number between 1 and 10, output "Input OK"
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
[Link]("demo").innerHTML = text;
}
</script>
</body>
</html>
Example:
<p>I'm thinking of a letter. Guess which: a, b, c, d or e?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var letter = [Link]("myInput").value;
var text;
// If the letter is "c"
if (letter === "c") {
text = "Spot on! Good job!";

// If the letter is "b" or "d"


} else if (letter === "b" || letter === "d") {
text = "Close, but not close enough.";
// If the letter is anything else
} else {
text = "Waaay off..";
}
[Link]("demo").innerHTML = text;
}
</script>
</body>
</html>
JavaScript switch Statement:
The JavaScript switch statement evaluates an expression and
executes a block of code based on matching cases. It provides an
alternative to long if-else chains, improving readability and
maintainability, especially when handling multiple conditional
branches.
Syntax:
switch (expression) {
case value1:
// code block 1;
break;
case value2:
// code block 2;
break;
...
default:
// default code block;
}
Example:
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
[Link](dayName); // Output: Wednesday
Example 1:
<p>Click the button to display what day it is today.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Unknown Day";
}
[Link]("demo").innerHTML = "Today is " +
day;
}
</script>
</body>
</html>
Example:
<p>Click the button to display a message based on what day it is.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text;
switch (new Date().getDay()) {
case 1:
case 2:
case 3:
default:
text = "Looking forward to the Weekend";
break;
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
}
[Link]("demo").innerHTML = text;
}
</script>
Example:
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction() {
var text;
var favDrink = prompt("What's your favorite cocktail drink?",
"Daiquiri");
switch(favDrink) {
case "Martini":
text = "Excellent choice. Martini is good for your soul.";
break;
case "Daiquiri":
text = "Daiquiri is my favorite too!";
break;
case "Cosmopolitan":
text = "Really? Are you sure the Cosmopolitan is your favorite?";
break;
default:
text = "I have never heard of that one..";
}
[Link]("demo").innerHTML = text;
}
</script>
JavaScript Break Statement:
JavaScript break statement is used to terminate the execution of the
loop or the switch statement when the condition is true.
JavaScript Continue Statemen:t
The continue statement in JavaScript is used to break the iteration of
the loop and follow with the next iteration.
Continue vs Break:
The major difference between the continue and break statement is that
the break statement breaks out of the loop completely while continue
is used to break one statement and iterate to the next statement.
JavaScript Return Statement:
The return statement in JavaScript is used to end the execution of a
function and return a value to the caller. It is used to control function
behaviour and optimise code execution.

try...catch...finally:
The try statement defines the code block to run (to try).
The catch statement defines a code block to handle any error.
The finally statement defines a code block to run regardless of the
result.
The throw statement defines a custom error.
Both catch and finally are optional, but you must use one of them.
Syntax:
try {
tryCode- Code block to run
}
catch(err){
catchCode- Code block to handle errors
}
finally {
finallyCode - Code block to be executed regardless of the try result
}
Example:
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
[Link]("demo").innerHTML = [Link];
}
</script>
Throw:
The throw statement allows you to create a custom error.
The throw statement throws (generates) an error.
The technical term for this is:
The throw statement throws an exception.
Syntax:
throw expression;
Example:
try {
if(x == "") throw "is Empty";
if(isNaN(x)) throw "not a number";
if(x > 10) throw "too high";
if(x < 5) throw "too low";
}
catch(err) {
[Link] = "Input " + err;

JavaScript Loops
Loops in JavaScript are used to reduce repetitive tasks by repeatedly
executing a block of code as long as a specified condition is true. This
makes code more concise and efficient.
The different types of loops available in javascript:
1. JavaScript for Loop:
for loop is a control flow statement that allows code to be executed
repeatedly based on a condition. It consists of three parts:
initialization, condition, and increment/decrement.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example:
for (let i = 1; i <= 3; i++) {
[Link]("Count:", i);
}
2. JavaScript while Loop:
It is an entry condition looping structure.
The while loop executes a block of code as long as a specified
condition is true. In JavaScript, this loop evaluates the condition
before each iteration and continues running as long as the condition
remains true.
Syntax:
while(condition){
}
Example:
let i = 0;
while (i < 3) {
[Link]("Number:", i);
i++;
}
3. JavaScript do-while Loop:
A Do-While loop is another type of loop in JavaScript that is similar
to the while loop, but with one key difference: the do-while loop
guarantees that the block of code inside the loop will be executed at
least once, regardless of whether the condition is
initially true or false .
 Entry Controlled loops: In this type of loop, the test condition is
tested before entering the loop body. For Loop and While
Loops are entry-controlled loops.
 Exit Controlled Loops: In this type of loop the test condition is
tested or evaluated at the end of the loop body. Therefore, the
loop body will execute at least once, irrespective of whether the
test condition is true or false. the do-while loop is exit controlled
loop.
It is an exit condition looping structure.
Syntax:
do{
code to be executed
}
while();
Example 1:
let i = 0;
do {
[Link]("Iteration:", i);
i++;
} while (i < 3);
Example:
let test = 1;
do {
[Link](test);
} while(test<1)

while(test<1){
[Link](test);
}
JavaScript For In Loop
The JavaScript for…in loop iterates over the properties of an object.
It allows you to access each key or property name of an object.
Syntax
for (key in object) { // Code}
Example:
const car = {
make: "Toyota",
model: "Corolla",
year: 2020
};
for (let key in car) {
[Link](`${key}: ${car[key]}`);
}
JavaScript for…of Loop
The JavaScript for…of loop is a modern, iteration statement.
 Works for iterable objects such as arrays, strings, maps, sets, and
more.
 It is better choice for traversing items of iterables compared to
traditional for and for in loops, especially when we have break
or continue statements. If we just want to perform an operation
on all items, we prefer forEach()
1. Iterating Over an Array using for…of

Example:
const a = [ 1, 2, 3, 4, 5 ];
for (const item of a) {
[Link](item);
}
2. Iterating Over a String using for…of
Example:
const str = "Hello";

for (const char of str) {


[Link](char);
}

[Link] Over a Map using for…of

Example:
const m = new Map([
["name", "Akash"],
["age", 25],
["city", "Noida"]
]);

for (let [key, value] of m) {


[Link](`${key}: ${value}`);
}
[Link] Over a Set using for…of
Example:
let s = new Set([1, 2, 3, 4, 5]);

for (let val of s) {


[Link](val);
}
5. Iterating Over an Object’s Properties using for…of
While the for…of loop is not directly used to iterate over object
properties, you can use it in combination with [Link](),
[Link](), or [Link]() to achieve this.

Example:
let person = {
name: "Akash",
age: 25,
city: "Noida"
};

for (let key of [Link](person)) {


[Link](`${key}: ${person[key]}`);
}
JavaScript Objects:
Object Properties:
A real life car has properties like weight and color:
[Link] = Fiat, [Link] = 500, [Link] = 850kg, [Link] = white.
Car objects have the same properties, but the values differ from car to car.
Object Methods:
A real life car has methods like start and stop:
[Link](), [Link](), [Link](), [Link]().
Car objects have the same methods, but the methods are performed at different
times.
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Example:
<p id="demo"></p>
<script>
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age:50,
eyeColor: "blue"
};
// Create a Copy
const x = person;
// Change Age
[Link] = 10;
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
Using the new Keyword:
This example create a new JavaScript object using new Object(), and then adds
4 properties.
Example:
// Create an Object
const person = new Object();

// Add Properties
[Link] = "John";
[Link] = "Doe";
[Link] = 50;
[Link] = "blue";
Accessing Object Properties:
You can access object properties in two ways:
[Link].
[Link]["propertyName"].
JavaScript Object Methods:
Object methods are actions that can be performed on objects.
A method is a function definition stored as a property value.
Example:
[Link] = function() {
return ([Link] + " " + [Link]).toUpperCase();
};
Basic Operations on JavaScript Objects:
1. Accessing Object Properties:
You can access an object’s properties using either dot notation or bracket
notation
Example:
let obj = { name: "Sourav", age: 23 };
// Using Dot Notation
[Link]([Link]);
// Using Bracket Notation
[Link](obj["age"]);
2. Modifying Object Properties:
Properties in an object can be modified by reassigning their values.
Example:
let obj = { name: "Sourav", age: 22 };
[Link](obj);
[Link] = 23;
[Link](obj);
3. Adding Properties to an Object:
You can dynamically add new properties to an object using dot or bracket
notation.
Example:
let obj = { model: "Tesla" };
[Link] = "Red";
[Link](obj);
[Link] Properties from an Object
The delete operator removes properties from an object.
Example:
let obj = { model: "Tesla", color: "Red" };
delete [Link];
[Link](obj);

JavaScript Arrays
In JavaScript, an array is an ordered list of values. Each value is called an
element, and each element has a numeric position in the array, known as its
index. Arrays in JavaScript are zero-indexed, meaning the first element is at
index 0, the second at index 1, and so on.
1. Create Array using Literal:
// Creating an Empty Array
let a = [];
[Link](a);
// Creating an Array and Initializing with Values
let b = [10, 20, 30];
[Link](b);
2. Create using new Keyword (Constructor):
The “Array Constructor” refers to a method of creating arrays by invoking the
Array constructor function.
Example:
// Creating and Initializing an array with values
let a = new Array(10, 20, 30);
[Link](a);
Basic Operations on JavaScript Arrays:
1. Accessing Elements of an Array:
Any element in the array can be accessed using the index number. The index in
the arrays starts with 0.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];

// Accessing Array Elements


[Link](a[0]);
[Link](a[1]);
2. Accessing the First Element of an Array:
The array indexing starts from 0, so we can access first element of array using
the index number.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Accessing First Array Elements
let fst = a[0];
[Link]("First Item: ", fst);
3. Accessing the Last Element of an Array:
We can access the last array element using [[Link] – 1] index number.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Accessing Last Array Elements
let lst = a[[Link] - 1];
[Link]("First Item: ", lst);
4. Modifying the Array Elements:
Elements in an array can be modified by assigning a new value to their
corresponding index.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
[Link](a);
a[1]= "Bootstrap";
[Link](a);
5. Adding Elements to the Array:
Elements can be added to the array using methods like push() and unshift().
 The push() method add the element to the end of the array.
 The unshift() method add the element to the starting of the array.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Add Element to the end of Array
[Link]("[Link]");
// Add Element to the beginning
[Link]("Web Development");
[Link](a);
6. Removing Elements from an Array:
To remove the elements from an array we have different methods
like pop(), shift(), or splice().
 The pop() method removes an element from the last index of the array.
 The shift() method removes the element from the first index of the array.
 The splice() method removes or replaces the element from the array.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
[Link]("Original Array: " + a);
// Removes and returns the last element
let lst = [Link]();
[Link]("After Removing the last: " + a);
// Removes and returns the first element
let fst = [Link]();
[Link]("After Removing the First: " + a);
// Removes 2 elements starting from index 1
[Link](1, 2);
[Link]("After Removing 2 elements starting from index 1: " + a);
7. Array Length
We can get the length of the array using the array length property.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
let len = [Link];
[Link]("Array Length: " + len);

8. Increase and Decrease the Array Length


We can increase and decrease the array length using the JavaScript length
property.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"]
// Increase the array length to 7
[Link] = 7;
[Link]("After Increasing Length: ", a);
// Decrease the array length to 2
[Link] = 2;
[Link]("After Decreasing Length: ", a)
9. Iterating Through Array Elements:
We can iterate array and access array elements using for loop and forEach loop.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Iterating through for loop
for (let i = 0; i < [Link]; i++) {
[Link](a[i])
}
10. Array Concatenation:
Combine two or more arrays using the concat() method. It returns new array
containing joined arrays elements.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS", "React"];
let b = ["[Link]", "[Link]"];
// Concatenate both arrays
let concateArray = [Link](b);
[Link]("Concatenated Array: ", concateArray);

11. Conversion of an Array to String:


We have a builtin method toString() to converts an array to a string.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Convert array ot String
[Link]([Link]());
12. Check the Type of an Arrays:
The JavaScript typeof operator is used ot check the type of an array. It returns
“object” for arrays.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Check type of array
[Link](typeof a);
JavaScript Array Methods:
To help you perform common tasks efficiently, JavaScript provides a wide
variety of array methods. These methods allow you to add, remove, find, and
transform array elements with ease.
1. JavaScript Array length :
The length property of an array returns the number of elements in the array. It
automatically updates as elements are added or removed.
Example:
let a = ["HTML", "CSS", "JS", "React"];
[Link]([Link]);
2. JavaScript Array toString() Method:
The toString() method converts the given value into the string with each
element separated by commas.
Example:
let a = ["HTML", "CSS", "JS", "React"];
let s = [Link]();
[Link](s);
3. JavaScript Array join() Method:
This join() method creates and returns a new string by concatenating all
elements of an array. It uses a specified separator between each element in the
resulting string.
Example:
let a = ["HTML", "CSS", "JS", "React"];
[Link]([Link]('|'));
4. JavaScript Array delete Operator:
The delete operator is used to delete the given value which can be an object,
array, or anything.
Example:
let emp = {
firstName: "Riya",
lastName: "Kaur",
salary: 40000
}

[Link](delete [Link]);
[Link](emp);
5. JavaScript Array concat() Method:
The concat() method is used to concatenate two or more arrays and it gives the
merged array.
Example:
let a1 = [11, 12, 13];
let a2 = [14, 15, 16];
let a3 = [17, 18, 19];
let newArr = [Link](a2, a3);
[Link](newArr);
6. JavaScript Array flat() Method:
The flat() method is used to flatten the array i.e. it merges all the given array
and reduces all the nesting present in it.

Example:
const a1 = [['1', '2'], ['3', '4', '5',['6'], '7']];
const a2 = [Link](Infinity);
[Link](a2);
 The code defines a multilevel (nested) array ‘a1’ and uses the
flat(Infinity) method to flatten it completely into a single-level array.
7. JavaScript [Link]() Method:
The push() method is used to add an element at the end of an Array. As arrays in
JavaScript are mutable objects, we can easily add or remove elements from the
Array.
Example:
let a = [10, 20, 30, 40, 50];
[Link](60);
[Link](70, 80, 90);
[Link](a);
8. JavaScript [Link]() Method:
The unshift() method is used to add elements to the front of an Array.
Example:
let a = [20, 30, 40];
[Link](10, 20);
[Link](a);
9. JavaScript [Link]() Method:
The pop() method is used to remove elements from the end of an array.
Example:
let a = [20, 30, 40, 50];
[Link]();
[Link](a);
10. JavaScript [Link]() Method:
The shift() method is used to remove elements from the beginning of an array.
Example:
let a = [20, 30, 40, 50];
[Link]();
[Link](a);
11. JavaScript [Link]() Method
The splice() method is used to Insert and Remove elements in between the
Array.
Example:
let a = [20, 30, 40, 50];
[Link](1, 3);
[Link](1, 0, 3, 4, 5);
[Link](a);
 The first [Link](1, 3) removes 3 elements (30, 40, 50) starting at index 1.
The array becomes [20].
 The second [Link](1, 0, 3, 4, 5) inserts 3, 4, and 5 at index 1 without
removing anything. The array becomes [20, 3, 4, 5].
12. JavaScript [Link]() Method:
The slice() method returns a new array containing a portion of the original array,
based on the start and end index provided as arguments.
Example:
const a = [1, 2, 3, 4, 5];
const res = [Link](1, 4);
[Link](res);
[Link](a)
13. JavaScript Array some() Method:
The some() method checks whether at least one of the elements of the array
satisfies the condition checked by the argument function.
Example:
const a = [1, 2, 3, 4, 5];
let res = [Link]((val) => val > 4);
[Link](res);
In this example
 The some() method checks if at least one element in the array satisfies
the provided condition.
 (val) => val > 4: The condition checks if any element in the array is
greater than 4.
 The method stops as soon as it finds the first matching element, making it
efficient for large arrays.
14. JavaScript Array map() Method:
The map() method creates an array by calling a specific function on each
element present in the parent array. It is a non-mutating method.
Example:

let a = [4, 9, 16, 25];


let sub = [Link](geeks);

function geeks() {

return [Link]([Link]);

}
[Link](sub);

In this example

 The code defines a geeks function, but instead of operating on the


individual array ‘a’ elements, it applies [Link]() to the entire a array,
resulting in a nested array of square roots.

 The output will be an array of the same length as a, but each element will
be the result of applying [Link]([Link]).

15. JavaScript Array filter() method

The filter() method in JavaScript creates a new array with all elements that pass
the test implemented by the provided function. It does not modify the original
array.

Example:

let a1 = [1, 2, 3, 4, 5]

let a2 = [Link]((num) => num > 1)


[Link](a2)

In this example

 The filter() method is used to create a new array (a2) that contains all
elements of the original array that satisfy the condition (num > 1).

 The filter() method does not modify the original array. It returns a new
array, leaving the original one unchanged.

16. JavaScript Array reduce() Method

The reduce() method is used to reduce the array to a single value and executes a
provided function for each value of the array (from left to right) and the return
value of the function is stored in an accumulator.

Example:

let a = [88, 50, 25, 10];


let sub = [Link](geeks);

function geeks(tot, num) {

return tot - num;

}
[Link](sub);

In this example

 The reduce() method iterates over the array ‘a’ and applies the geeks
function, which subtracts each element (num) from the running total (tot).

 For the array [88, 50, 25, 10], the calculation proceeds as: 88 – 50 – 25 –
10.

17. JavaScript Array reverse() method:

The reverse() method is used to reverse the order of elements in an array. It


modifies the array in place and returns a reference to the same array with the
reversed order.

Example:

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

[Link]();
[Link](a);

In this example

 The reverse() method reverses the order of elements in the array arr in
place, modifying the original array.

 After applying reverse(), the array.

18. JavaScript Array values() method:

The values() method returns a new Array Iterator object that contains the values
for each index in the array.

const a = ["Apple", "Banana", "Cherry"];


const res = [Link]();

for (const value of res) {

[Link](value);
}

In this example:

 The values() method returns an iterator object that allows iterating over
the values of the ‘a’ array.

 The for…of loop is used to iterate over the iterator and log each fruit
(“Apple”, “Banana”, “Cherry”) to the console.

Best-Known JavaScript Array Methods:

Array some() Method:


The Array some() method checks if at least one element of the array satisfies the
condition implemented by the provided function.
Example:
// JavaScript to illustrate
// lastIndexOf() method
function isGreaterThan5(element, index, array) {
return element > 5;
}
function func() {
// Original array
let array = [2, 5, 8, 1, 4];
// Checking for condition in array
let value = [Link](isGreaterThan5);
[Link](value);
}
func();
Array reduce() Method:
The array reduce() method reduces an array to a single value by executing a
provided function for each value from left to right.
Example:
// Original array
let numbers = [88, 50, 25, 10];
// Performing reduce method
let sub = [Link](geeks);
function geeks(total, num) {
return total - num;
}
[Link](sub);

Array map() Method:


The map() method in JavaScript creates a new array by calling a specific
function on each element of the parent array. It does not mutate the original
array.
Example:
// Original array
let numbers = [4, 9, 16, 25];
// Performing map method
let sub = [Link](geeks);
function geeks() {
return [Link]([Link]);
}
[Link](sub);
Array every() Method:
The Array every() method checks if all elements in the array satisfy a given
condition provided by a function.
Example:
//Original array
let arr = [[11, 89], [23, 7], 98];
// Performing flat method
let geeks = [Link]();
[Link](geeks);
Array flatMap() Method
This Array flatMap() method is used to flatten the input array element into a
new array. This method first of all map every element with the help of a
mapping function, then flattens the input array element into a new array.
Example:
const myAwesomeArray = [
[1], [2], [3], [4], [5]
];
let geeks = [Link](
(arr) => arr * 10
);
[Link](geeks);
Array filter() Method
The Array filter() method is used to create a new array from a given array
consisting of only those elements from the given array which satisfy a condition
set by the argument function.
Example:
function isPositive(value) {
return value > 0;
}
function func() {
let filtered = [112, 52, 0, -1, 944]
.filter(isPositive);
[Link](filtered);
}
func();
Array findindex() Method:
The Array findIndex() method returns the index of the first element in a given
array that satisfies the provided testing function. Otherwise, -1 is returned.
Example:
let array = [10, 20, 30, 110, 60];
function finding_index(element) {
return element > 25;
}
[Link](array
.findIndex(finding_index)
);
Array find() Method:
The Array find() method is used to get the value of the first element in the array
that satisfies the provided condition. It checks all the elements of the array and
whichever the first element satisfies the condition is going to print.

Example:
// Input array contain some elements.
let array = [10, 20, 30, 40, 50];
// Function (return element > 10).
let found = [Link](function (element) {
return element > 20;
});
// Printing desired values.
[Link](found);
Array fill() Method:
The Array fill() method is used to fill the array with a given static value. The
value can be used to fill the entire array or it can be used to fill a part of the
array.
Example:
// JavaScript code for fill() function
let arr = [1, 23, 46, 58];
// Here value = 87, start index = 1 and
// and last index = 3
[Link](87, 1, 3);
[Link](arr);
Array forEach() Method:
The Array forEach() method calls the provided function once for each element
of the array. The provided function may perform any kind of operation on the
elements of the given array.
Example:
// Original array
const items = [1, 29, 47];
const copy = [];
[Link](function (item) {
[Link](item * item);
});

[Link](copy);
Array sort() Method:
The Array sort() method is used to sort the array. An array can be of any type
i.e. string, numbers, characters, etc.
Example:
// Original array
let numbers = [88, 50, 25, 10];
// Performing sort method
let sub = [Link](geeks);
function geeks(a, b) {
return a - b;
}
[Link](sub);
Array concat() Method:
The Array concat() method is used to merge two or more arrays together. This
function does not alter the original arrays passed as arguments.
Example:
// JavaScript code for concat() function
let num1 = [11, 12, 13],
num2 = [14, 15, 16],
num3 = [17, 18, 19];
[Link]([Link](num2, num3));
Array includes() Method:
The Array includes() method is used to know whether a particular element is
present in the array or not and accordingly, it returns true or false i.e, if the
element is present, then it returns true otherwise false
// Taking input as an array A
// having some elements.
let A = [1, 2, 3, 4, 5];
// Include() function is called to
// test whether the searching element
// is present in given array or not.
let a = [Link](2);
// Printing result of function.
[Link](a);
Array reverse() Method:
The Array reverse() method is used for in-place reversal of the array. The first
element of the array becomes the last element and vice versa.
Example:
//Original Array
let arr = [34, 234, 567, 4];
[Link]("Original array: " + arr);
//Reversed array
let new_arr = [Link]();
// Display the result
[Link]("Newly reversed array: " + new_arr);
Important Array Methods of JavaScript
JavaScript arrays are powerful tools for managing collections of data.
They come with a wide range of built-in methods that allow developers to
manipulate, transform, and interact with array elements.
[Link] indexOf() Method
The indexOf() method is used to find the index of a particular element in
an array.
Example:
let a = ["Hello", "GFG", "JS"];
[Link]([Link]('GFG'));
[Link] includes() Method:
The includes() method is used to check whether the array contains the specified
element or not.
Example:
let a = ["Hello", "GFG", "JS"];
[Link]([Link]("GFG"));
[Link]([Link]("React"));

Output
true
false
[Link] concat() Method:
The concat() method is used to concat or basically join two different arrays from
end to end.
Example:
let a1 = ["Hello","GFG", "Js"];
let a2 = ["React"];
let new = [Link](a2);
[Link](a1);
[Link](a2);
[Link](new);
// The concat() method merges a1 and a2 into a new array without modifying the
original arrays.//
[Link] forEach() Method:
The forEach() works as a loop over an array where for every element the function
just runs once only.
Example:
let a = ["Hello", "GFG", "JS"];
[Link](function (element) {
[Link](element)
});
Output
Hello
GeeksforGeeks
JavaScript
//The forEach() method iterates over each element in the array a and executes the
provided function for each element.//
[Link] sort() Method:
The sort() method sorts the elements of an array in alphabetical order in
ascending order.
Example:
let a = ["Hello", "GFG", "JS"];
[Link](a);
[Link]();
[Link](a);
Output
[ 'Hello', 'GeeksforGeeks', 'JavaScript' ]
[ 'GeeksforGeeks', 'Hello', 'JavaScript' ]
[Link] map() method:
The map() method iterates over an array, transforms the array according to user-
specified conditions and returns a new array.
Example:
let a1 = [1, 2, 3, 4, 5];
[Link](a1);
let a2 = [Link](function (elem) {
return elem * 5;
});
[Link](a2);
Output
[ 1, 2, 3, 4, 5 ]
[ 5, 10, 15, 20, 25 ]
7. JavaScript reduce() Method:
The reduce() method uses a reducer function that reduces the results into a single
output.
Example:
let a1 = [1, 2, 3, 4, 5];
[Link](a1);
let sum = [Link](
function (acc, elem) {
return acc + elem;
});

[Link](sum);
Output
[ 1, 2, 3, 4, 5 ]
15
8. JavaScript filter() Method:
The filter() method is used to filter out the contents, as per the user-specified
condition, in the form of a new array.
Example:
let a1 = [1, 2, 3, 4, 5];
[Link](a1);
let a2 = [Link](function (elem) {
return elem % 2 === 0;
});
[Link](a2);
Output
[ 1, 2, 3, 4, 5 ]
[ 2, 4 ]
9. JavaScript find() & findIndex() Method
The find() method finds out the first value which passes the user-specified
conditions and findIndex() method finds out the first index value which passes
the user-specified conditions.
Example:
let a = [1, 2, 3, 4, 5];
let find = [Link](function (elem) {
return elem > 4
});
[Link](find);
let val = [Link](function (elem) {
return elem >= 4
});
[Link](val);
Output
5
3
[Link] slice() & splice() Method:
The slice() selects the specified number of elements without affecting the original
array elements whereas splice() removes the selected elements from the original
array itself.
Example:
let a = [1, 2, 3, 4, 5];
let slice = [Link](0, 2);
[Link]("Slice Array: " + slice);
[Link]("Original Array: " + a);
let splice = [Link](0, 2);
[Link]("Slice Array: " + splice);
[Link]("Original Array: " + a);
Output
Slice Array: 1,2
Original Array: 1,2,3,4,5
Slice Array: 1,2
Original Array: 3,4,5
[Link] some() and every() Method:
The some() method checks the user-specified conditions on some elements of an
array (i.e. it checks for a few elements only), whereas every() method checks the
user-specified conditions on every element of an array then returns the results in
true or false.
Example:
let a = [1, 2, 3, 4, 5];
let n1 = [Link](
function (elem) {
return elem > 0
});
let n2 = [Link](
function (elem) {
return elem < 0
});
[Link](n1);
[Link](n2);
Output
true
false
13. Javascript forEach() method:
The forEach() method in JavaScript is used to execute a provided function once
for each element in an array.
let n = [1, 2, 3, 4, 5];
[Link](function(elem, index) {
[Link](elem);
});
Output
1
2
3
4
5
14. JavaScript Array reverse() Method:
The reverse() method is used to reverse the order of the elements in an array.
let a = [1, 2, 3, 4, 5];
[Link]();
[Link](a);
Output
[ 5, 4, 3, 2, 1 ]

15. Javascript Array every() method:


The every() method is used to check if all elements in the array pass the test
implemented by the provided function. It returns a boolean value true if all
elements satisfy the test otherwise returns false.
const a = [2, 4, 6];
const isEven = (num) => num % 2 === 0;
const allEven = [Link](isEven);
[Link](allEven);
Output
true
Examplr program:
Body background changer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
background-color: white;
}
button {
margin-left: 50%;
margin-top: 50vh;
padding: 2px;
}
</style>
</head>
<body id="body">
<button onclick="changeColor()">Change Color</button>
<script>
const body = [Link]('body').style
const colors = ["red", "blue", "green", "pink", "white", "purple", "grey",
"orange", "yellow"]
function changeColor () {
[Link] = colors[[Link]([Link]() *
[Link])]
}
</script>
</body>
</html>
JavaScript Strings
JavaScript Strings mutable ?
immutable since once a string is created it will receive a reference in the
memory and its value will never change. This means that any operation on a
string may give the new string without mutating the main string.
Create using Constructor
let s = new String('abcd');
[Link](s);
Basic Operations on JavaScript Strings:
[Link] the length of a String:
let len = [Link];
2. String Concatenation:
let res = s1 + s2;
[Link] Characters:
We can use escape characters in string to add single quotes, dual quotes, and
backslash.
const s1 = "\'GfG\' is a learning portal";
const s2 = "\"GfG\" is a learning portal";
const s3 = "\\GfG\\ is a learning portal";
[Link](s1);
[Link](s2);
[Link](s3);
Output
'GfG' is a learning portal
"GfG" is a learning portal
\GfG\ is a learning portal
4. Breaking Long Strings
We will use a backslash to break a long string in multiple lines of code.
const s = "'GeeksforGeeks' is \
a learning portal";
[Link](s);
Output
'GeeksforGeeks' is a learning portal

5. Find Substring of a String


We can extract a portion of a string using the substring() method.
let s1 = 'JavaScript Tutorial';
let s2 = [Link](0, 10);
[Link](s2);
Output
JavaScript
6. Convert String to Uppercase and Lowercase
Convert a string to uppercase and lowercase
using toUpperCase() and toLowerCase() methods.
let s = 'JavaScript';
let uCase = [Link]();
let lCase = [Link]();
[Link](uCase);
[Link](lCase);

Output
JAVASCRIPT
javascript
7. String Search in JavaScript:
Find the first index of a substring within a string using indexOf() method.
let s1 = 'def abc abc';
let i = [Link]('abc');
[Link](i);
Output
4
8. String Replace in JavaScript:
Replace occurrences of a substring with another using replace() method.
let s1 = 'Learn HTML at GfG';
let s2 = [Link]('HTML', 'JavaScript');
[Link](s2);
Output
Learn JavaScript at GfG
9. Trimming Whitespace from String:
Remove leading and trailing whitespaces using trim() method.
let s1 = ' Learn JavaScript ';
let s2 = [Link]();
[Link](s2);
Output
Learn JavaScript
10. Access Characters from String
Access individual characters in a string using bracket notation and charAt()
method.
let s1 = 'Learn JavaScript';
let s2 = s1[6];

[Link](s2);
s2 = [Link](6);
[Link](s2);
Output
J
J
11. String Comparison in JavaScript
There are some inbuilt methods that can be used to compare strings such as the
equality operator and another like localeCompare() method.
let str1 = "John";
let str2 = new String("John");
[Link](str1 == str2);
[Link]([Link](str2));
Output
true
0
12. Passing JavaScript String as Objects
We can create a JavaScript string using the new keyword.
const str = new String("GeeksforGeeks");
[Link](str);
Output
[String: 'GeeksforGeeks']

JavaScript Numbers
JavaScript numbers are primitive data types and, unlike other programming
languages, you don’t need to declare different numeric types like int, float, etc.
JavaScript numbers are always stored in double-precision 64-bit binary format
IEEE 754. This format stores numbers in 64 bits:
 0-51 bits store the value (fraction)
 52-62 bits store the exponent
 63rd bit stores the sign
Numeric Types in JavaScript:
In JavaScript, numbers play an important role, and understanding their behavior
is essential for effective programming. Let’s explore the various aspects of
numeric types in JavaScript.

Number Literals:
The types of number literals You can use decimal, binary, octal, and
hexadecimal.
1. Decimal Numbers:
JavaScript Numbers does not have different types of numbers(ex: int, float,
long, short) which other programming languages do. It has only one type of
number and it can hold both with or without decimal values.
Example:
let a=33;
let b=3.3;
[Link](a);
[Link](b);
Output
33
3.3
2. Octal Number:
If the number starts with 0 and the following number is smaller than 8. It will be
parsed as an Octal Number.
let x = 0562;
[Link](x);
Output
370
3. Binary Numbers:
They start with 0b or 0B followed by 0’s and 1’s.
let x = 0b11;
let y = 0B0111;

[Link](x);
[Link](y);
Output
3
7
4. Hexadecimal Numbers:
They start with 0x or 0X followed by any digit belonging
(0123456789ABCDEF) .
let x = 0xfff;
[Link](x);
Output
4095
Number Coercion in JavaScript
In JavaScript, coercion refers to the automatic or implicit conversion of
values from one data type to another.
1. Undefined to NaN:
When you perform an operation involving undefined, JavaScript
returns NaN (Not-a-Number).
const result = undefined + 10;
[Link](result); // NaN
Output
NaN
2. Null to 0:
The value null is coerced to 0 when used in arithmetic operations.
const total = null + 5;
[Link](total); // 5
Output
5
3. Boolean to Number:
Boolean values (true and false) are converted to
numbers: 1 for true and 0 for false.
const num1 = true + 10;
const num2 = false + 10;

[Link](num1);
[Link](num2);
Output
11
10
4. String to Number
When performing arithmetic operations, JavaScript converts strings to numbers.
If the string cannot be parsed as a valid number, it returns NaN.
const str1 = '42';
const str2 = 'hello';
const numFromString1 = Number(str1);
const numFromString2 = Number(str2);
[Link](numFromString1);
[Link](numFromString2);
Output
42
NaN
5. BigInts and Symbols
Attempting to coerce Symbol values to numbers results in a TypeError.
const symbolValue = Symbol('mySymbol');

const numFromSymbol = Number(symbolValue); // TypeError


[Link](numFromSymbol);
Output:
TypeError: Cannot convert a Symbol value to a number
JavaScript Number Methods
Now, we will use Number methods such
as toString(), toExponential(), toPrecision(), isInteger(),
and toLocaleString() method. Let’s see the examples of these Number methods.
let x = 21
[Link]([Link]());
[Link]([Link]());
[Link]([Link](4));
[Link]([Link](x));
[Link]([Link]("bn-BD"));
Output:
21
2.1e+1
21.00
true
২১
How numbers are stored in JavaScript ?
Storing of Integer Numbers
Integer: These numbers are further divided into two types
 Signed Integers
 Unsigned Integers.
Signed Integers: −32,768 to 32,767 Unsigned: 0 to 65,535.
To store unsigned integers simple binary format is used.
let a = 4
let b = 78
a will be stored in the memory with the value of:- 100
b will be stored in the memory with the value of:- 1001110
JavaScript Math Object
The Math object is a built-in object that provides properties and methods for
mathematical constants and functions. It is not a constructor, so all its properties
and methods are static and can be called without creating a Math object
instance.
JavaScript Math object is used to perform mathematical operations on
numbers. All the properties of Math are static and unlike other objects, it does
not have a constructor.

Example program:
Palindrome:
function palindromeCheck(num) {
let numStr = [Link]();
let result = [Link]('').reverse().join('');
return numStr === result;
}

[Link](palindromeCheck(121)); // true
[Link](palindromeCheck(123)); // false
Output
true
false
Check a Number is Prime or Not
let n = 17;
let isPrime = true;
if (n <= 1) {
isPrime = false;
} else {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
isPrime = false;
break;
}
}
}
[Link](isPrime ? `${n} is a prime number.` : `${n} is not a prime
number.`);

$() – dollar function


The dollar sign ($) is also used as a shortcut to the
function [Link](). The $ is being used as an alternative
since this function references a DOM element if we pass an element’s id and
now is used frequently in JavaScript to serve the purpose.
JavaScript Math Object
JavaScript Math object is used to perform mathematical operations on numbers.
All the properties of Math are static and unlike other objects, it does not have a
constructor.
Math Methods:
The syntax for Math any methods is : [Link](number)
Number to Integer
There are 4 common methods to round a number to an integer:
[Link]()
[Link](x) returns the nearest integer
Example:
<script>
[Link]("demo").innerHTML = [Link](4.6);
</script>
[Link]()
[Link](x) returns the value of x rounded up to its nearest integer
Example:
<script>
[Link]("demo").innerHTML = [Link](4.4);
</script>
[Link]()
[Link](x) returns the value of x rounded down to its nearest integer
[Link]()
[Link](x) returns the integer part of x
Example:
<script>
[Link]("demo").innerHTML = [Link](4.7);
</script>
[Link]()
[Link](x, y) returns the value of x to the power of y
Example:
<script>
[Link]("demo").innerHTML = [Link](8,2);
</script>
[Link]()
[Link](x) returns the square root of x
Example:
<script>
[Link]("demo").innerHTML = [Link](64);
</script>
[Link]()
[Link](x) returns the absolute (positive) value of x
Example:
<script>
[Link]("demo").innerHTML = [Link](-4.7);
</script>
[Link]()
[Link](x) returns the sine (a value between -1 and 1) of the angle x (given in
radians).
If you want to use degrees instead of radians, you have to convert degrees to
radians:
Angle in radians = Angle in degrees x PI / 180.
[Link]()
[Link](x) returns the sine (a value between -1 and 1) of the angle x (given in
radians).
If you want to use degrees instead of radians, you have to convert degrees to
radians:
Angle in radians = Angle in degrees x PI / 180.
[Link]()
[Link](x) returns the cosine (a value between -1 and 1) of the angle x (given in
radians).
If you want to use degrees instead of radians, you have to convert degrees to
radians:
Angle in radians = Angle in degrees x PI / 180
Example:
<script>
[Link]("demo").innerHTML =
"The cosine value of 0 degrees is " + [Link](0 * [Link] / 180);
</script>
[Link]() and [Link]()
[Link]() and [Link]() can be used to find the lowest or highest value in a list
of arguments
Example:
<script>
[Link]("demo").innerHTML =
[Link](0, 150, 30, 20, -8, -200);
</script>
[Link]()
[Link]() returns a random number between 0 (inclusive), and 1 (exclusive)
Example:
<script>
[Link]("demo").innerHTML = [Link]();
</script>
The [Link]() Method:
[Link](x) returns the natural logarithm of x.
The natural logarithm returns the time needed to reach a certain level of growth
Map in JS
 inserts keys in the order they were added.
 Allows keys of any type, not just strings and symbols.
 Provides better performance when dealing with large datasets.
A Map is a data structure that stores key-value pairs, where each key is unique.
It is similar to an object but has some advantages:
 Inserts keys in the order they were added.
 Allows keys of any type, not just strings and symbols.
 Provides better performance when dealing with large datasets.
Creating a Map
Map() constructor allows two ways to create a Map in JavaScript.
 Passing an Array to new Map().
 Create a Map and use [Link]().
let myMap = new Map();
let anotherMap = new Map([
['name', 'GFG'],
['age', 30],
['city', 'Noida']
]);
[Link](anotherMap);
Output
Map(3) { 'name' => 'GFG', 'age' => 30, 'city' => 'Noida' }
Properties of JavaScript Map
 set(key,val) : Adds or updates an element with a specified key and value.
 get(key) : Returns the value associated with the specified key.
 has(key) : Returns a boolean indicating whether an element with the
specified key exists.
 delete(key) : Removes the element with the specified key.
 clear(): Removes all elements from the Map.

 size: Returns the number of key-value pairs in the Map.

Example: Creating and Using a Map


const company = new Map([
["name", "GFG"],
["no_of_employee", 200],
["category", "education"]
]);
function print(key, values) {
[Link](values + "=>" + key);
}
[Link](print);
Output
name=>GFG
no_of_employee=>200
category=>education
Set in JavaScript:
A Set in JavaScript is used to store a unique collection of items, meaning no
duplicates are allowed.
 Sets internally use a hash table which makes search, insert and delete
operations faster than arrays. Please note that a hash table data structure
allows these operations to be performed on average in constant time.
 Set maintains insertion of items. When we access items, we get them in
the same order as inserted.
 Only Unique Keys are allowed, if we insert the same key with a different
value, it overwrites the previous one.
 A set can be created either empty or by providing an iterable like array or
string.
Example:
// using an array
let s1 = new Set([10, 30, 30, 40, 40]);
[Link](s1);
let s2 = new Set(["gfg", "gfg", "geeks"]);
[Link](s2);
// using string
let s3 = new Set("fooooooood");
[Link](s3);
// an empty set
let s4 = new Set();
[Link](s4);
Output
Set(3) { 10, 30, 40 }
Set(2) { 'gfg', 'geeks' }
Set(3) { 'f', 'o', 'd' }
Set(0) {}
Key Characteristics of Sets:
 Unique Values: A Set cannot contain duplicate values.
 Ordered: Sets maintain the insertion order of elements.
 Iterable: Sets can be iterated using loops or methods like forEach.
 No Indexing: Unlike arrays, Sets do not support indexing.
Methods of Set in JavaScript
 [Link]() : adds the new element with a specified value at the end of the
Set object.
 [Link]() : deletes an element with the specified value from the Set
object.
 [Link](): removes all the element from the set.

 [Link]() : returns an iterator object which contains an array having


the entries of the set, in the insertion order.
 [Link]() : returns true if the specified value is present in the Set
object.
 [Link]() : returns all the values from the Set in the same insertion
order.
 [Link](): also returns all the values from the Set in the insertion
order.
 [Link]() : executes the given function once for every element in
the Set, in the insertion order.
 [Link][@@iterator]() : returns a Set iterator function which
is values() function by default.
 has(value) : Checks if a value exists in the Set.

Arrow functions in JavaScript:


arrow function is a shorter syntax for writing functions in JavaScript.
1. Arrow Function without Parameters
const gfg = () => {
[Link]( "Hi from GeekforGeeks!" );
}
gfg();
Output
Hi from GeekforGeeks!
2. Arrow Function with Single Parameters
If your arrow function has a single parameter, you can omit the parentheses
around it.
const square = x => x*x;
[Link](square(4));
Output
16
3. Arrow Function with Multiple Parameters
const gfg = ( x, y, z ) => {
[Link]( x + y + z )
}
gfg( 10, 20, 30 );
Output
60
4. Arrow Function with Default Parameters
const gfg = ( x, y, z = 30 ) => {
[Link]( x + " " + y + " " + z);
}
gfg( 10, 20 );
Output
10 20 30
5. Return Object Liter
const makePerson = (firstName, lastName) =>
({first: firstName, last: lastName});
[Link](makePerson("Pankaj", "Bind"));
Output
{ first: 'Pankaj', last: 'Bind' }
avaScript this Keyword
Last Updated : 18 Jan, 2025
The ‘this keyword’ in JavaScript refers to the object to which it belongs. Its
value is determined by how a function is called, making it a dynamic reference.
The ‘this’ keyword is a powerful and fundamental concept used to access
properties and methods of an object, allowing for more flexible and reusable
code.
const person = {
name: "GeeksforGeeks",
greet() {
return `Welcome To, ${[Link]}`;
}
};
[Link]([Link]());
Output
Welcome To, GeeksforGeeks

You might also like