CM Java Script Ver 9.0
CM Java Script Ver 9.0
[Link](a);
[Link](b);
[Link](c);
[Link](d);
Output
Hello Geeks
10
12
22
Example 2:
In this example, we will declare variables using let.
let a = "Hello learners"
let b = "joining";
let c = " 12";
let d = b + c;
[Link](a);
[Link](b);
[Link](c);
[Link](d);
Output
Hello learners
joining
12
joining 12
Example 3:
In this example, we will declare the variable using the const keyword.
const a = "Hello learners"
[Link](a);
const b = 400;
[Link](b);
const c = "12";
[Link](c);
// Can not change a value for a constant
c = "new"
[Link](c)
Output:
Example 4:
In this example, we are trying to access the block scoped variables outside the
block that is why we are getting error.
{
let a = 2;
var b = 4;
const c = "Hello";
[Link](a);
[Link](b);
[Link](c);
}
[Link](b);
[Link](c);
[Link](a);
Output:
Boolean Represents a logical entity and can have two values: true or false.
Undefine
A variable that has not been assigned a value is undefined.
d
Greater than (>) This operator checks whether the let X = 10 then X > 11 is
left side value is greater than the false.
right side value. If yes then it
returns true otherwise it returns
false.
Ternary Operator It is like the short form of the Y = ? A : B If the condition is true
(?:) if-else condition. then Y = A otherwise Y = B
delete object
This operator is more specifically // or
Delete used to delete JavaScript object delete [Link]
properties. // or
delete object[‘property’]
1.6.9 JavaScript Relational Operators
JavaScript Relational operators are used to compare its operands and
determine the relationship between them. They return a Boolean value (true
or false) based on the comparison result.
1.7 Functions
1.7.1 Overview
A function in JavaScript is a reusable block of code that performs a specific task.
You define it once, and then you can run (or call) it whenever you need that
task done in your program.
Syntax: The basic syntax to create a function in JavaScript is shown below.
function functionName(Parameter1, Parameter2, ...)
{
// Function body
}
To create a function in JavaScript, we have to first use the keyword function,
separated by the name of the function and parameters within parenthesis. The
part of the function inside the curly braces {} is the body of the function.
1.7.2 Features
Functions can be used multiple times, reducing redundancy.
Break down complex problems into manageable pieces.
Manage complexity by hiding implementation details.
Can call themselves to solve problems recursively.
1.7.3 Function Invocation
The function code you have written will be executed whenever it is called.
Triggered by an event (e.g., a button clicks by a user).
When explicitly called from JavaScript code.
Automatically executed, such as in self-invoking functions.
1.7.4 Function Definition
A function definition is sometimes also termed a function declaration or
function statement. Below are the rules for creating a function in JavaScript:
Every function should begin with the keyword function followed by,
A user-defined function name that should be unique,
A list of parameters enclosed within parentheses and separated by commas,
A list of statements composing the body of the function enclosed within
curly braces {}.
Example:
This example shows a basic declaration of a function in javascript.
function calcAddition(number1, number2) {
return number1 + number2;
}
[Link](calcAddition(6,9));
Output:
15
In the above example, we have created a function named calcAddition,
This function accepts two numbers as parameters and returns the addition
of these two numbers.
Accessing the function with just the function name without () will return the
function object instead of the function result.
There are three ways of writing a function in JavaScript:
Syntax:
let function_name = (argument1, argument2 ,..) => expression
Example:
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
const a2 = [Link](function (s) {
return [Link];
});
[Link]("Normal way ", a2); // [8, 6, 7, 9]
const a3 = [Link]((s) => [Link]);
[Link]("Using Arrow Function ", a3);
Output:
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
1.7.9 Function Parameters
Parameters are additional information (optional) passed to a function. The
parameters are passed to the function within parentheses after the function
name and separated by commas.
Example:
function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a * b;
}
[Link](multiply(69));
Output:
69
Syntax:
functionName( Value1, Value2, ..);
Example:
Below is a sample program that illustrates the working of functions in
JavaScript:
function welcomeMsg(name) {
return ("Hello " + name + " welcome to GeeksforGeeks");
}
// creating a variable
let nameVal = "Admin";
// calling the function
[Link](welcomeMsg(nameVal));
Output:
Hello Admin welcome to GeeksforGeeks
1.7.11 Return Statement
There are some situations when we want to return some values from a
function after performing some operations. In such cases, we can make use of
the return statement in JavaScript. This is an optional statement and most of
the time the last statement in a JavaScript function. Look at our first example
with the function named as calcAddition. This function is calculating two
numbers and then returns the result.
Syntax:
The most basic syntax for using the return statement is:
return value;
The return statement begins with the keyword return separated by the value
which we want to return from it. We can use an expression also instead of
directly returning the value.
Chapter 2: Control Structures and Loops
2.1 Conditional Statements
2.1.1 if Statement
The if statement is used to evaluate a particular condition. If the condition
holds true, the associated code block is executed.
Syntax:
if ( condition ) {
// If the condition is met,
//code will get executed.
}
Example:
This JavaScript code determines if the variable num is even or odd using the
modulo operator %. If `num` is divisible by 2 without a remainder, it logs Given
number is even number. Otherwise, it logs Given number is odd number.
let num = 20;
if (num % 2 === 0) {
[Link]("Given number is even number.");
}
if (num % 2 !== 0) {
[Link]("Given number is odd number.");
};
Output:
Given number is even number.
2.1.2 Using if-else Statement
The if-else statement will perform some action for a specific condition. Here we
are using the else statement in which the else statement is written after the if
statement and it has no condition in their code block.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Example:
This JavaScript code checks if the variable age is greater than or equal to 18. If
true, it logs You are eligible for a driving license. Otherwise, it logs You are not
eligible for a driving license. This indicates eligibility for driving based on age.
let age = 25;
if (age >= 18) {
[Link]("You are eligible of driving licence")
} else {
[Link]("You are not eligible for driving licence")
};
Output:
You are eligible of driving licence
2.1.3. else if Statement
The else if statement in JavaScript allows handling multiple possible conditions
and Outputs, evaluating more than two options based on whether the
conditions are true or false.
Syntax:
if (1st condition) {
// Code for 1st condition
} else if (2nd condition) {
// ode for 2nd condition
} else if (3rd condition) {
// Code for 3rd condition
} else {
// Code that will execute if all
// above conditions are false
}
Example:
This JavaScript code determines whether the constant num is positive,
negative, or zero. If num is greater than 0, it logs Given number is positive. If
num is less than 0, it logs Given number is negative. If neither condition is met
(i.e., num is zero), it logs Given number is zero.
const num = 0;
if (num > 0) {
[Link] ("Given number is positive.");
} else if (num < 0) {
[Link] ("Given number is negative.");
} else {
[Link] ("Given number is zero.");
};
Output:
Given number is zero.
2.1.4. Using Switch Statement (JavaScript Switch Case)
As the number of conditions increases, you can use multiple else-if statements
in JavaScript. but when we dealing with many conditions, the switch statement
may be a more preferred option.
Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
default:
statementDefault;
};
Example: This JavaScript code assigns a branch of engineering to a student
based on their marks. It uses a switch statement with cases for different mark
ranges. The student’s branch is determined according to their marks and
logged to the console.
const marks = 85;
let Branch;
switch (true) {
case marks >= 90:
Branch = "Computer science engineering";
break;
case marks >= 80:
Branch = "Mechanical engineering";
break;
case marks >= 70:
Branch = "Chemical engineering";
break;
case marks >= 60:
Branch = "Electronics and communication";
break;
case marks >= 50:
Branch = "Civil engineering";
break;
default:
Branch = "Bio technology";
break;
}
[Link](`Student Branch name is : ${Branch}`);
Output:
Student Branch name is : Mechanical engineering
2.1.5. Using Ternary Operator ( ?: )
The conditional operator, also referred to as the ternary operator (?:), is a
shortcut for expressing conditional statements in JavaScript.
Syntax:
condition ? value if true : value if false
Example: This JavaScript code checks if the variable `age` is greater than or
equal to 18. If true, it assigns the string “You are eligible to vote.” to the
variable `result`. Otherwise, it assigns “You are not eligible to vote.” The value
of `result` is then logged to the console.
JavaScript
let age = 21;
const result =
(age >= 18) ? "You are eligible to vote."
: "You are not eligible to vote.";
[Link](result);
Output:
You are eligible to vote.
2.1.6 Nested if…else
Nested if…else statements in JavaScript allow us to create complex conditional
logic by checking multiple conditions in a hierarchical manner. Each if
statement can have an associated else block, and within each if or else block,
you can nest another if…else statement. This nesting can continue to multiple
levels, but it’s important to maintain readability and avoid excessive
complexity.
Syntax:
if (condition1) {
// Code block 1
if (condition2) {
// Code block 2
} else {
// Code block 3
}
} else {
// Code block 4
}
Example: In this example, the outer if statement checks the weather variable. If
it’s sunny, it further checks the temperature variable to determine the type of
day it is (hot, warm, or cool). Depending on the values of weather and
temperature, different messages will be logged to the console.
let weather = "sunny";
let temperature = 25;
Syntax:
for (statement 1 ; statement 2 ; statement 3){
code here...
}
Example:
// JavaScript program to illustrate for loop
let x;
// for loop begins when x=2
// and runs till x <=4
for (x = 2; x <= 4; x++) {
[Link]("Value of x:" + x);
}
Output:
Value of x:2
Value of x:3
Value of x:4
2.2.2 while Loop
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. The loop terminates
when the condition becomes false, enabling dynamic and repeated operations
based on changing conditions.
Syntax
while (condition) {
Code block to be executed
}
Example:
let count = 1;
while (count <= 5) {
[Link](count);
count++;
}
Output:
1
2
3
4
5
2.2.3 do…while Loop
A do…while loop in JavaScript is a control structure where the code executes
repeatedly based on a given boolean condition. It’s similar to a repeating if
statement. One key difference is that a do…while loop guarantees that the
code block will execute at least once, regardless of whether the condition is
met initially or not.
Syntax:
do {
// Statements
}
while(conditions)
Example:
let test = 1;
do {
[Link](test);
test++;
} while(test<=5)
Output:
1
2
3
4
5
2.2.4 break Statement
JavaScript break statement is used to terminate the execution of the loop or
the switch statement when the condition is true.
In a switch, code breaks out and the execution of code is stopped.
In a loop, it breaks out to the loop but the code after the loop is
executed.
Syntax:
break;
Example:
In this example, the loop iterates from 1 to 6 when it is equal to 4 then the
condition becomes true, and code breaks out to the loop.
for (let i = 1; i < 6; i++) {
if (i == 4) break;
[Link](i);
}
Output:
1
2
3
2.2.5 continue Statement
The continue statement in Javascript is used to break the iteration of the loop
and follow with the next iteration. The break in the iteration is possible only
when the specified condition going to occur.
Syntax:
continue;
Example:
let i = 0;
while (i < 11) {
i++;
if (i % 2 == 0) continue;
[Link](i);
}
Output:
1
3
5
7
9
11
Chapter 3: Advanced Functions
3.1 Higher-Order Functions
JavaScript Higher-Order Functions are functions that can accept other functions
as arguments, return functions, or both. They enable abstraction and flexibility
in code, allowing you to create reusable and modular functions for complex
operations, making them essential in functional programming.
Syntax:
function higherOrderFunction(callback) {
// Perform some operations
// Call the callback function
callback();
}
function callbackFunction() {
[Link]("Callback function is executed.");
}
// Passing the callback function to the higher-order function
higherOrderFunction(callbackFunction);
Parameters:
higherOrderFunction: Takes a callback function, executes it, and performs
operations.
callback: A function passed as an argument, executed inside
higherOrderFunction.
callbackFunction(): Logs “Callback function is executed.”
Invocation: Calls higherOrderFunction(callbackFunction), executing
callbackFunction within higherOrderFunction.
3.1.1 Function as an Argument
This approach involves passing a function (callback) as an argument to another
function. The receiving function can then execute the callback, enabling flexible
and customizable behavior in JavaScript programs.
Example:
In this example, Two functions: greet accepts name and returns a greeting.
greet name combines greeting, message, and name, logging a customized
message. Output: Hi!! JavaScript Welcome To GeeksForGeeks.
function greet(name) {
return `Hi!! ${name} `;}
function greet_name(greeting, message, name) {
[Link](`${greeting(name)} ${message}`);
}
greet_name(greet, 'Welcome To GeeksForGeeks', 'Geeks');
Output:
Hi!! Geeks Welcome To GeeksForGeeks
3.1.2 Functions as Return Values
Higher-order functions can also return new functions. This is often used for
creating specialized functions or closures. For instance, you can create a
function factory that generates functions with specific behavior.
Example
In this example, multiplier is a higher-order function that takes a factor as an
argument and returns a new function that multiplies any number by that
factor. We then use double and triple to create specialized functions.
function multiplier(factor) {
return function (x) {
return x * factor;
};
}
const double = multiplier(2);
const triple = multiplier(3);
[Link](double(5));
[Link](triple(5));
Output
10
15
3.2 Closures
3.2.1 Overview
Closures in JavaScript are functions that retain access to variables from their
containing scope even after the parent function has finished executing. They
are useful for maintaining private data, creating modular code, and
implementing callback functions with persistent state.
A closure is the combination of a function bundled together (enclosed) with
references to its surrounding state (the lexical environment). When you create
a closure, you gain access to an outer function’s scope from an inner function.
Closures are automatically created every time a function is defined in
JavaScript.
3.2.2 Lexical Scoping
Lexical scoping refers to how a parser resolves variable names when functions
are nested. The location where a variable is declared within the source code
determines where that variable is available. Nested functions have access to
variables declared in their outer scope.
Example
function foo() {
let b = 1;
function inner() {
return b;
}
return inner;
}
let get_func_inner = foo();
[Link](get_func_inner());
[Link](get_func_inner());
[Link](get_func_inner());
Output
1
1
1
We can access the variable b which is defined in the function
foo() through function inner() as the later preserves the scope chain of the
enclosing function at the time of execution of the enclosing function i.e. the
inner function knows the value of b through its scope chain.
This is closure in action that is inner function can have access to the outer
function variables as well as all the global variables.
Closure in JavaScript
Closure is the concept of function + lexical environment in which function it
was created. so every function declared within another function then it has
access to the scope chain of the outer function and the variables created
within the scope of the outer function will not get destroyed.
3.2.3 Creating Closures
Example – 1 : Basic Closure.
function foo(outer_arg) {
function inner(inner_arg) {
return outer_arg + inner_arg;
}
return inner;
}
let get_func_inner = foo(5);
[Link](get_func_inner(4));
[Link](get_func_inner(3));
Output
9
8
In the above example we used a parameter function rather than a default one.
Not even when we are done with the execution of foo(5) we can access
the outer_arg variable from the inner function. And on the execution of the
inner function produce the summation of outer_arg and inner_arg as desired.
Example 2:
// Outer function
function outer() {
let arr = [];
let i;
for (i = 0; i < 4; i++) {
// storing anonymous function
arr[i] = function () { return i; }
}
Syntax:
Let promise = new Promise (function (resolve, reject) {
// do something
});
A promise can be created using Promise constructor.
Parameters:
Promise constructor takes only one argument which is a callback function
(and that callback function is also referred as an anonymous function too).
Callback function takes two arguments, resolve and reject
Perform operations inside the callback function and if everything went well
then call resolve.
If desired operations do not go well then call reject.
Example:
In this example, a Promise is created to compare two strings, geeksforgeeks
and geeksforgeeks. If the strings match, the promise resolves, logging a success
message. Otherwise, it rejects, logging an error message. The then method
handles success, and the catch method handles errors.
let promise = new Promise(function (resolve, reject) {
const x = "geeksforgeeks";
const y = "geeksforgeeks"
if (x === y) {
resolve();
} else {
reject();
}
});
promise.
then(function () {
[Link]('Success, You are a GEEK');
}).
catch(function () {
[Link]('Some error has occurred');
});
Output
Success, You are a GEEK
Benefits of Promises:
Improves Code Readability
3.3.2 Callbacks
Callbacks are a great approach to dealing with something once another task
has been finished. Here, something refers to the execution of a function.
Callbacks can be utilized if we wish to run a function immediately following the
return of another function.
The type of JavaScript function is objects. They may therefore be supplied as an
argument to any other function when calling them, just like any other objects
(Strings, Arrays, etc.).
Example:
In this example, the add function takes two numbers, adds them, logs the
result, and executes a callback function (disp). When calling add(5, 6, disp), it
outputs the sum and a message from the callback.
// The add() function is called with arguments a, b and callback, callback
// will be executed just after ending of add() function
function add(a, b, callback) {
[Link](`The sum of ${a}
and ${b} is ${a + b}`);
callback();
}
// The disp() function is called just after the ending of add() function
function disp() {
[Link](`This must be printed
after addition`);
}
// Calling add() function
add(5, 6, disp)
Output:
The sum of 5 and 6 is 11
This must be printed after addition
Explanation:
Here are the two functions – add(a, b, callback) and disp(). Here add() is called
with the disp() function i.e. passed in as the third argument to the add function
along with two numbers.
As a result, the add () is invoked with 1, 2, and the disp () which is the callback.
The add() prints the addition of the two numbers and as soon as that is done,
the callback function is fired! Consequently, we see whatever is inside the
disp() as the output below the additional output.
The benefit of Callback:
You can run another function call after waiting for the outcome of a prior
function call.
You can call the parent function from the child function and can also pass
data from child to parent.
Chapter 4: Asynchronous JavaScript
4.1 Async/Await
Async and Await in JavaScript is used to simplify handling asynchronous
operations using promises. By enabling asynchronous code to appear
synchronous, they enhance code readability and make it easier to manage
complex asynchronous flows.
4.1.1 Async Function
The async function allows us to write promise-based code as if it were
synchronous. This ensures that the execution thread is not blocked.
Promise Handling: Async functions always return a promise. If a value is
returned that is not a promise, JavaScript automatically wraps it in a
resolved promise.
Async Syntax:
async function myFunction() {
return "Hello";
}
Example:
const getData = async () => {
let data = "Hello World";
return data;
}
getData().then(data => [Link](data));
Output:
Hello World
4.1.2 Await Keyword
The await keyword is used to wait for a promise to resolve. It can only be used
within an async block.
Execution Pause: Await makes the code wait until the promise returns a
result, allowing for cleaner and more manageable asynchronous code.
Syntax:
let value = await promise;
Example:
const getData = async () => {
let y = await "Hello World";
[Link](y);
}
[Link](1);
getData();
[Link](2);
Output
1
2
Hello World
The async keyword transforms a regular JavaScript function into an
asynchronous function, causing it to return a Promise.
The await keyword is used inside an async function to pause its execution and
wait for a Promise to resolve before continuing.
4.1.3 Async/Await Example
Here, we will be implementing several promises in a method, and then that
method we will use for displaying our result. You can check the JS async/await
syntax in the example.
function asynchronous_operational_method() {
let first_promise =
new Promise((resolve, reject) => resolve("Hello"));
let second_promise =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(" GeeksforGeeks..");
}, 1000);
});
let combined_promise =
[Link]([first_promise, second_promise]);
return combined_promise;
}
async function display() {
let data = await asynchronous_operational_method();
[Link](data);
}
display();
Output:
[ 'Hello', ' GeeksforGeeks..' ]
Explanation:
Promise Creation: Two promises are created: one resolve immediately with
“Hello”, and the other resolves after 1 second with ” GeeksforGeeks..”.
Combining Promises: The [Link]() method combines both promises
into a single promise, combined_promise.
Asynchronous Function: The display() function is declared as async,
indicating it contains asynchronous operations.
Awaiting Promise Resolution: The await keyword pauses execution until
combined_promise is resolved.
Logging Result: The resolved array from combined_promise is logged to the
console.
Note
To resolve and reject are predefined arguments by JavaScript.
resolve function is used when an asynchronous task is completed and
returns the result.
reject function is used when an asynchronous task fails and returns reasons
for failure.
4.1.4 Error Handling in Async/Await
JavaScript provides predefined arguments for handling promises: resolve and
reject.
resolve: Used when an asynchronous task is completed successfully.
reject: Used when an asynchronous task fails, providing the reason for
failure.
Example:
async function fetchData() {
try {
let response = await fetch('[Link]
let data = await [Link]();
[Link](data);
} catch (error) {
[Link]('Error fetching data:', error); }
}
4.1.5 Advantages of Async and Await
1. Improved Readability: Async and Await allow asynchronous code to be
written in a synchronous style, making it easier to read and understand.
2. Error Handling: Using try/catch blocks with async/await simplifies error
handling.
3. Avoids Callback Hell: Async and Await prevent nested callbacks and
complex promise chains, making the code more linear and readable.
4. Better Debugging: Debugging async/await code is more intuitive since it
behaves similarly to synchronous code.
4.2 Fetch API
4.2.1 Overview
The fetch() method in JavaScript is a modern and powerful way to retrieve
resources from a server. It returns a Promise that resolves to a Response
object, encapsulating the server’s response to your request.
fetch() seamlessly integrates advanced HTTP functionalities such as Cross-
Origin Resource Sharing (CORS) and other extensions, enriching the web
development experience with enhanced security and interoperability.
Note: Fetch API comes with the fetch() method, which is used to fetch data
from different sources.
Syntax:
fetch('url') // api for the get request
.then(response => [Link]())
.then(data => [Link](data));
Parameters:
URL: The URL to which the request is to be made.
Options: It is an array of properties. It is an optional parameter. Options
available are:
o Method: Specifies HTTP method for the request. (can be GET, POST, PUT
or DELETE)
o Headers
Explanation:
1. The JS fetch() function is used to send a GET request to the URL
[Link] This function returns a
Promise that resolves to a Response object representing the response to the
request.
2. The then() method is chained to the fetch() call to handle the response
asynchronously. Inside the callback function passed to then(), the [Link]()
method is called to parse the response body as JSON. This method also
returns a Promise that resolves to the parsed JSON data.
3. Another then() method is chained to handle the parsed JSON data. Inside its
callback function, the parsed JSON data d is logged to the console using
[Link]()
2. Using fetch to Post JSON Data
In this example, we have uploaded JSON data using the fetch() API in
JavaScript, you can set the request body to a JSON stringified version of your
data and set the appropriate headers to indicate that you’re sending JSON.
Post requests can be made using fetch by giving the options given below:
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: [Link](data)
}
After checking the Syntax of the post request, look at the example below which
demonstrates using post request in fetch method.
// Your JSON data
const jsonData = { key1: 'value1', key2: 'value2' };
We make the fetch request using fetch() with the provided options.