Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

JavaScript notes

JavaScript is a high-level, dynamic scripting language used for creating interactive web pages and applications, with capabilities in both front-end and back-end development. It supports various applications including mobile apps, games, and machine learning, and features such as event handling, variable storage, and data types. The document also covers JavaScript syntax, variable scope, operators, control structures, and how to integrate JavaScript into HTML.

Uploaded by

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

JavaScript notes

JavaScript is a high-level, dynamic scripting language used for creating interactive web pages and applications, with capabilities in both front-end and back-end development. It supports various applications including mobile apps, games, and machine learning, and features such as event handling, variable storage, and data types. The document also covers JavaScript syntax, variable scope, operators, control structures, and how to integrate JavaScript into HTML.

Uploaded by

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

JavaScript

JavaScript (also referred to as ‘javascript’ or JS) is a

• high-level,
• prototype-based,
• dynamic scripting language
• Used to create interactive web pages and applications.

Its flexibility and front and back-end capabilities make JavaScript a popular programming language.

• Some of the useful features of


• JavaScript include storing values in variables,
• performing operations on strings,
• and triggering or acting on events that happen in the DOM.

JavaScript Applications
Frontend Development
Backend Development
Software Development
Console Applications
Mobile Apps Development
Web Animations
Games
AR and VR
2D and 3D
Machine Learning
Data Science
Some popular facts about JavaScript.
1. Javascript is the only client side programming language for web browser.
2. JavaScript can build interactivity Websites.
3. Javascript is Object Based with prototype inheritance model for OOPS.
4. Javascript is Case Sensitive.
5. Javascript can put dynamic content into a webpage. .
6. Javascript can react to events like Mouse Click, mouse hover, mouse out, form submit etc
known as JavaScript Events.
7. Javascript can validate form data.

Adding JavaScript into an HTML Document


The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want
the JavaScript to load.

Internal JavaScript

<script>
document.write("Hello Javascript");
</script>
Eg:-
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Today's Date</title>
</head>
<body>
<script>
let d = new Date();
document.body.innerHTML = "<h1>Today's date is " + d + "</h1>"
</script>
</body>
</html>

Working with a Separate JavaScript File

External JavaScripts In External JavaScript, javascript code is written in external file with .js extension and then linked with
script tag
The benefits of using a separate JavaScript file include:
o Separating the HTML markup and JavaScript code to make both more straightforward
o Separate files makes maintenance easier
o When JavaScript files are cached, pages load more quickly

<script src="myscript.js"></script>

Inline Javascript
In Inline Javascript, javascript code is written directly inside html tags.
Eg:-
<button onclick="alert('Hello JS')">Check</button>
<marquee onmouseover="stop()" onmouseout="start()">Hello Javascript</marquee>
<a href="javascript:void(0)" onclick="print()">Print</a>

Project Structure
project/
├── css/
| └──mystyle.css
├── js/
| └── myscript.js
└── index.html

Print text in JavaScript Console


<script>
var x="hello string";
console.log(x);
</script>

JavaScript Dialog Box

<script>

var x="hello js";

alert(x);

</script>
JS Prompt, prompt()

prompt() or window.prompt() dialog box is used to receive input from user. The default datatype of prompt object
is string. But id cancelled, it will return null.

<script>

var x=prompt("Enter Name");

alert(x);

</script>

JS Confirm, confirm()

confirm() or window.confirm() dialog box is used to get confirmation from user. This will show ok or Cancel in
dialog box. ok will return true and cancel will return false.

<script>

var x=confirm("Press Ok or Cancel");

alert(x);

</script>

JavaScript Comments

Comments are used to write explanations, hints, and to stop execution of code. JavaScript use two
comments syntax. One is Single line comment, and second is Multi-line comment.

JavaScript Single Line Comment

<script>

// single line comment

</script>

JavaScript Multi-line Line Comment

<script>

/* Multi-line Comment */

</script>

Variables in JavaScript

A variable or var is storage area used to store a value in memory.

Consider variable as a container to store data.

JavaScript variables are loosely typed.

This is also knows as dynamic typing. Means a variable x (var x) can store any type of data, like string,
number, function, boolean, undefined, null, array or object.

<script>

var x="ElysiumAcademy”; // value of x is " ElysiumAcademy ";

var y= ElysiumAcademy '; // value of y is also " ElysiumAcademy ";

var z=9; // value of z is 9 numeric.

var a=2, b=3, c=5; // multiple variables in single line

var u; // u is undefined
</script>

Variable naming convention in JavaScript

➢ variables names cannot include javascript reserved keywords, like var, for, in, while,
true, false, null, class, let, const, function etc.
➢ variables cannot starts with numbers and hyphen, use alphabets, underscore(_) or
dollar ($).
➢ variables can have strings followed by numbers, like x1 and x2 are allowed but 1x, 2x
is not allowed.
➢ For separation in variable names, use underscore (_) or camel casing, do not use
hyphen (-) separation and white space, i.e, user_name is valid, username is also
valid, but user-name is invalid.
➢ variables names are case sensitive, i.e, x1 and X1 are different.

Local Vs Global Variables

A variable in javascript can be local or global variable based on its scope.

Variables declared outside function are global variables and variable declared inside function are local
variables.

Global Variables

Variables declared outside function are global variable.

Global variables have global scope. This means, a variable in <script> tag is by default global. Global Variable
once declared can be used anywhere, even inside a function.

Eg:-

var x="hello js"; // global variable

var y=88; // another global variable

console.log(x); // returns "hello string"

console.log(y); // returns 88

function myFunction()

console.log(x) // returns "hello string"

console.log(y); // returns 88

Local Variable

Variables declared inside functions are local variables. Local Variables have local scope. This means they are
accessible only within their function block, not outside.

function myFunction(){

var x="local variable";

var y="local variable";


console.log(x); // returns "local variable"

console.log(y); // returns "local variable"

myFunction() // call the function

console.log(x); // x is not defined

console.log(y); // y is not defined

let and Const block scope

let and const were introduced in ECMA 6(European Computer Manufacturers Association).

let is used to declare temporary values with block scope, inside {} . Whereas const is used to declare
permanent values, which can't be change. Like value of pi

JavaScript let

JavaScript let is used to declare variable in block scope. The value of let is only accessible inside block.

<script>

let x="user"; // to store values in block scope

</script>

Eg:-

<script>

var i=2; // global scope

if(i==2)

let i=3; // block scope

console.log(i); // 3

console.log(i); // 2

</script>
JavaScript const

JavaScript const is used to declared immutable values, i.e fixed values which are not changeable.
Const can't be undefined.

<script>

const pi=Math.PI; // pi is a constant, and can't be changed

</script>

<script>

const user="avi";

user="xyz"; //Assignment to constant variable.

</script>

var vs let vs const

var is function scoped, but let and const are block scoped. let and const are replacement of var in JS ES6 and
onwards. Here is table of comparison of var, let and const.

Javascript DataTypes

Datatypes in javascript means the type of data stored in a variable.

As JavaScript and all scripting languages are loosely typed, there is no typecast in javascript. JS supports
dynamic typing . We can create any type of data using a single variable.

var means a variable which can store any type of data. Data type of variable is not declared.

Declaring var means creating a new variable in memory with variable name after white-space. Assignment
Operator (=) means assigning value to variable declared.

We can also use const and let to declared variables.

Datatypes in JavaScript

Primitive datatypes in JavaScript

Primitive datatypes are the basic or common data types in javascript. Like string, numbers, boolean, undefined
and null. They are very commonly used data types.

Primitive Data Type Meaning

var x; undefined
var x=undefined; undefined

var x=null; null type data

var x=3; Data Type is number.

var x=3.5 Data Type is number with decimal

var x="3" Data Type is string

var x='3' Data Type is string

var x="HELLO" Data Type is string

var x=true Boolean data type

var x=false; Boolean data type

Reference Data Type in JAVASCRIPT

Reference are datatypes based on primitive.

Like Array, Object and Functions.

Everything is JavaScript is either a primitive datatype or Object.

Even Arrays and Functions are objects, but they are build-in objects.

Reference Data Type Meaning

let month=[ "Jan", "Feb", "Mar" ]; Array

let user={ name : "ABC", age : 22 }; Object

var x=function(x,y){ return x+y;}; Function Expression

function sum(x,y){ return x+y;} Function Declaration

var x=new Date(); Date

var x=/^[0-9]{6}$/; Regex

typeof Operator

typeof operator in javascript is used to check data type of a variable. It can return string, number, boolean and
undefined. For reference type and null, typeof operator will return object.

var x; // undefined

var y=9; // number

var z="ElysiumAcademy”; // string

typeof(x) and typeof x will return undefined,

typeof(y) and typeof y will return number,

typeof(z) and typeof z will return string.


Javascript Operators

Operators

Javascript Operators are used to assign, add, subtract, compare data.

JavaScript is having arithmetic, logical, assignment and comparison operators.

JavaScript has both binary and unary operator including one ternary operator (conditional operator).

binary operator

Binary operators required two operands, one before and one after operator. x+y=z

Eg:-

x (operand) +(operator) y(operand)

Unary Operator

Unary operators required only one operand, either before or after operator. i++

x++

++x

Ternary Operator

Ternary Operator is conditional operator in javaScript witch use three operands.

For Example, (3>2) ? console.log("yes"): console.log("no")

Arithmetic operators in JavaScript

Operator Description Example

+ Addition 2+3=5

- Subtraction 5-3=2

* Multiply 2*3=6

/ Divide 6/3=2

% Reminder 6%3=0

++ Increment, y++ means y = y+1 var y=2; ++y; y=3

-- Decrement, y-- means y = y-1 var y=2; --y; y=1

** Exponentiation Operator 2**3 returns 8


Logical Operators

Logical Operators are used to check logic between two operators. and (&&), or (||) and not (!) are logical
operators.

Logical Operators in JavaScript

Operator Description Example

&& and, when both are correct 2 < 5 && 2> 1 is true

|| or, when any one is correct var x=2, 2>5 || x==2 is true

! not !(2==3) is true

Assignment Operators

Assignment operators ars used to assign some value to js variables. =, +=, -=, *=, /= are all assignment
operators in javascript.

Assignment Operators in JavaScript

Operator Description Example

= Assignment x=2; means x is 2

+= Addition Assignment var x=2; x+=2 means x=x+2

-= Subtraction Assignment var x=2; x-=2 means x=x-2

*= Multiplication Assignment var x=2; x*=2 means x=x*2

/= Division Assignment var x=2; x/=2 means x=x/2

Comparision Operators

Comparision operators are used in a statement to compare two values.

Comparision Operators in JavaScript

Operator Description Example

== Equal to 2=="2" is true

=== Strict equal to 2==="2" is false

!= not equal 2!=1 is true

!== not strict equal 2!=="2" is true

> greater than 2> 5 is false,

& 2 <5 is true

>= greater than or equal to 3>=3 is true

< less than 1< 3 is true

<= less than or equal to 2<=2 is true


JavaScript Control structures(DecisionMaking)

JavaScript supports the following forms of if..else statement −


if statement
if...else statement
if...else if... statement.
if (expression)

Statement(s) to be executed if expression is true

If statement

Example:-
<html>

<body>

<script type = "text/javascript">

<!--

var age = 20;

if( age > 18 ) {

document.write("<b>Qualifies for driving</b>");

//-->

</script>

<p>Set the variable to different value and then try...</p>

</body>

</html>

if...else statement

The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.

Syntax

if (expression) {

Statement(s) to be executed if expression is true

} else {

Statement(s) to be executed if expression is false

}
Example

Try the following code to learn how to implement an if-else statement in JavaScript.

<html>

<body>

<script type = "text/javascript">

<!--

var age = 15;

if( age > 18 ) {

document.write("<b>Qualifies for driving</b>");

} else {

document.write("<b>Does not qualify for driving</b>");

//-->

</script>

<p>Set the variable to different value and then try...</p>

</body>

</html>

if...else if... statement

The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.

Syntax

The syntax of an if-else-if statement is as follows −

if (expression 1) {

Statement(s) to be executed if expression 1 is true

} else if (expression 2) {

Statement(s) to be executed if expression 2 is true

} else if (expression 3) {

Statement(s) to be executed if expression 3 is true

} else {

Statement(s) to be executed if no expression is true

Example

<html>

<body>

<script type = "text/javascript">

<!--

var book = "maths";

if( book == "history" ) {


document.write("<b>History Book</b>");

} else if( book == "maths" ) {

document.write("<b>Maths Book</b>");

} else if( book == "economics" ) {

document.write("<b>Economics Book</b>");

} else {

document.write("<b>Unknown Book</b>");

//-->

</script>

<p>Set the variable to different value and then try...</p>

</body>

</html>

JavaScript - Switch Case

You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway branch

Syntax

switch (expression) {

case condition 1: statement(s)

break;

case condition 2: statement(s)

break;

case condition n: statement(s)

break;

default: statement(s)

Example

<html>

<body>

<script type = "text/javascript">

<!--

var grade = 'A';

document.write("Entering switch block<br />");

switch (grade) {

case 'A': document.write("Good job<br />");

break;

case 'B': document.write("Pretty good<br />");

break;
case 'C': document.write("Passed<br />");

break;

case 'D': document.write("Not so good<br />");

break;

case 'F': document.write("Failed<br />");

break;

default: document.write("Unknown grade<br />")

document.write("Exiting switch block");

//-->

</script>

<p>Set the variable to different value and then try...</p>

</body>

</html>

JavaScript -Loopings

A task of set of task repeat again and again we used loopings.

Types

For loop

While loop

Do while loop

For loop

The 'for' loop is the most compact form of looping. It includes the following three important parts −

The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.

The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be
executed, otherwise the control will come out of the loop.

The iteration statement where you can increase or decrease your counter.

Syntax

for (initialization; test condition; iteration statement)

Statement(s) to be executed if test condition is true

Example:-

<html>

<body>

<script type = "text/javascript">

<!--

var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++) {

document.write("Current Count : " + count );

document.write("<br />");

document.write("Loop stopped!");

//-->

</script>

<p>Set the variable to different value and then try...</p>

</body>

</html>

While loop

Syntax

while (expression)

Statement(s) to be executed if expression is true

Example:-

<html>

<body>

<script type = "text/javascript">

<!--

var count = 0;

document.write("Starting Loop ");

while (count < 10) {

document.write("Current Count : " + count + "<br />");

count++;

document.write("Loop stopped!");

//-->

</script>

<p>Set the variable to different value and then try...</p>

</body>

</html>
The do...while Loop

The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means
that the loop will always be executed at least once, even if the condition is false.

Syntax

The syntax for do-while loop in JavaScript is as follows −

do {

Statement(s) to be executed;

} while (expression);

Example

<html>

<body>

<script type = "text/javascript">

<!--

var count = 0;

document.write("Starting Loop" + "<br />");

do {

document.write("Current Count : " + count + "<br />");

count++;

while (count < 5);

document.write ("Loop stopped!");

//-->

</script>

<p>Set the variable to different value and then try...</p>

</body>

</html>

JavaScript Arrays

The Array object lets you store multiple values in a single variable.

It stores a fixed-size sequential collection of elements of the same type.

An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the
same type.

Syntax

Use the following syntax to create an Array object −

var fruits = new Array( "apple", "orange", "mango" );


You can create array by simply assigning values as follows −

var fruits = [ "apple", "orange", "mango" ];

eg:-

<html>

<script>

var names=["raja","kumar","mani","ram","madan","martin"];

// or

names=new Array("raja","kumar","mani","ram","madan","martin");

document.write(names);

document.write("<br>"+names);

</script>

</html>

//creating two dimentional array

var a = new Array(new Array(1, 2, 3),new Array(4, 5, 6));

document.write("Two dimentional array elements are=>"+"<br>");

for(var i=0;i<2;i++)

for(var j=0;j<3;j++)

document.write(a[i][j]+"<br>");

Removing the element with splice() function.

var array = ["Hi","Hello","How","are","you?"];

document.write("Array elements before removing are => <br>"+array+"<br>");

var indexValue = array.indexOf("How");

if (indexValue > -1) {

array.splice(indexValue, 1);

document.write("Array elements after removing are => <br>"+array);


Eg:- How to create Dynamic array and values

<html>

<body>

<script>

x=new Array();

names=new Array();

age=new Array();

sal=new Array();

x=prompt("How many records u want to insert");

for(i=0;i<x;i++)

names[i]=prompt("enter name");

age[i]=prompt("enter age");

sal[i]=prompt("enter salary");

for(j=0;j<x;j++)

document.write(names[j]+" "+age[j]+" "+sal[j]+"<br>");

</script>

</body>

</html>

JavaScript Functions

What is functions?

A function is a group of reusable code which can be called anywhere in your program. T

This eliminates the need of writing the same code again and again.

It helps programmers in writing modular codes.

Functions allow a programmer to divide a big program into a number of small and manageable functions.

Function Definition

Before we use a function, we need to define it.

The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function
name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax

The basic syntax is shown here.


<script type = "text/javascript">

<!--

function functionname(parameter-list)

statements

//-->

</script>

Function define with calling function

<html>

<head>

<script type = "text/javascript">

function sayHello() {

document.write ("Hello there!");

</script>

</head>

<body>

<p>Click the following button to call the function</p>

<form>

<input type = "button" onclick = "sayHello()" value = "Say Hello">

</form>

<p>Use different text in write method and then try...</p>

</body>

</html>

Function Parameters

Example

Try the following example. We have modified our sayHello function here. Now it takes two parameters.

<html>

<head>

<script type = "text/javascript">

function sayHello(name, age) {

document.write (name + " is " + age + " years old.");


}

</script>

</head>

<body>

<p>Click the following button to call the function</p>

<form>

<input type = "button" onclick = "sayHello('raja',33)" value = "Say Hello">

</form>

<p>Use different parameters inside the function and then try...</p>

</body>

</html>

Function with return Statement

A JavaScript function can have an optional return statement. This is required if you want to return a value from a function.
This statement should be the last statement in a function.

<html>

<head>

<script type = "text/javascript">

function concatenate(first, last) {

var full;

full = first + last;

return full;

function secondFunction() {

var result;

result = concatenate('Zara', 'Ali');

document.write (result );

</script>

</head>

<body>

<p>Click the following button to call the function</p>

<form>

<input type = "button" onclick = "secondFunction()" value = "Call Function">


</form>

<p>Use different parameters inside the function and then try...</p>

</body>

</html>

JavaScript - Objects Overview

JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it
provides four basic capabilities to developers −

Encapsulation − the capability to store related information, whether data or methods, together in an object.

Aggregation − the capability to store one object inside another object.

Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and
methods.

Polymorphism − the capability to write one function or method that works in a variety of different ways.

The new Operator

The new operator is used to create an instance of an object. To create an object, the new operator is followed by the
constructor method.

In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in
JavaScript functions.

var employee = new Object();

var books = new Array("C++", "Perl", "Java");

var day = new Date("August 15, 1947");

Example

Try the following example; it demonstrates how to create an Object.

<html>

<head>

<title>User-defined objects</title>

<script type = "text/javascript">

var book = new Object(); // Create the object

book.subject = "Perl"; // Assign properties to the object

book.author = "Mohtashim";

book.price=1000.00;

book.pub="Abc";

</script>

</head>

<body>

<script type = "text/javascript">


document.write("Book name is : " + book.subject + "<br>");

document.write("Book author is : " + book.author + "<br>");

document.write("Book name is : " + book.price+ "<br>");

document.write("Book author is : " + book.pub + "<br>");

document.write(book);

</script>

</body>

</html>

how to create an object with a User-Defined Function. Here this keyword is used to refer to the object that has been passed
to a function.

<html>

<head>

<title>User-defined objects</title>

<script type = "text/javascript">

title=”undefined”;

author=”undefined”;

function book(title, author)

this.title = title;

this.author = author;

</script>

</head>

<body>

<script type = "text/javascript">

var myBook = new book("Java", "James Goesling”);

document.write("Book title is : " + myBook.title + "<br>");

document.write("Book author is : " + myBook.author + "<br>");

</script>

</body>

</html>
Example

<html>

<script>

//Defining object

let person = {

first_name:'Mukul',

last_name: 'Latiyan',

//method

getFunction : function()

return (`The name of the person is ${person.first_name} ${person.last_name}`)

},

//object within object

phone_number :

mobile:'12345',

landline:'6789'

console.log(person.getFunction());

console.log(person.phone_number.landline);

</script>

</html>

JavaScript Strings
Strings are collection of characters stored inside quotes ( double or single) or back tick (in ES6). Strings
represents text and can have lower case, upper case, special characters or numbers within quotes.

Strings can store data, like name, email id, age etc. Default datatype for input, select, textarea value is always a
string.

In JavaScript, Strings are declared inside double quotes "" or single quotes ''.

Declare Strings in JavaScript


var x="Elysium Academy"; // string;

var y=' Elysium Academy '; // string;

var z=` Elysium Academy `; // template literal in ES6

var str=String("abc"); // String class or function

Eg:-

var x=3;

var y=5;

console.log(`sum of ${x} and ${y} is ${x+y}`); //ES6

console.log("sum of " + x + " and " + y + " is " + (x+y)); //ES5

// returns "sum of 3 and 5 is 8"

Multi line string

Template literals can also add multi-line strings. Till ES5, we use + operator to do the same. See example of
Multi line string .

var template=’<!doctype html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

</head>

<body>

</body>

</html>’;

String.length

String.length property shows the number of characters in string.

var x="hello js";

x.length; // 8

String Methods

JavaScript Methods are build in functions used to perform an action to strings

indexOf

indexOf methods returns index of first matched substring. The return value of indexOf methods is always a
number.

var x="Elysium ";


alert(x.indexOf("E") )

x.indexOf("i")

x.indexOf("m")

lastIndexOf

lastIndexOf methods returns index of last matched substring. The return value of lastIndexOf method will also
be number.

var x="Elysium";

x.indexOf("s")

x.lastIndexOf("y")

x.lastIndexOf("e")

concat

concat method is used to concatenate or merge two strings into one. The second string should be passed as
argument.

var x="Elysium";

var y="Academy”;

x.concat(y);

var x="Elysium";

var y="Academy”;

x+y;

charAt

charAt method return character at given index in argument.

var x="Elysium”;

x.charAt(0); // return E

x.charAt(1); // return l

x.charAt(x.length-1); // return m

x.charAt(x.length); // return ""

charCodeAt

charCodeAt method return ASCII code of character at given index in argument.

var x="Elysium”;

x.charCodeAt(0);

x.charCodeAt(1);

toUpperCase

toUpperCase method convert all lowercase characters to uppercase.


var x="Elysium";

x.toUpperCase();

x.toLowerCase();

substr

substr method return substrings from index (first argument ) to given no of characters (second argument). First
argument is always index and second is no of characters. If second argument is missing, it will return substrings
after first index.

var x="HelloWorld”;

x.substr(2); // return "lloWorld"

x.substr(4); // return "oWorld"

x.substr(0,4); // return "Hello"

x.substr(2,2); // return "ll"

x.substr(5,5); // return "world"

search

search method search for a matched pattern between string and regular expression and return index of
matched pattern.

var x="Elysium Academy";

x.search("E"); // return 0

x.search("M"); // return -1

x.search(/\s/); // return 4, i.e, white space found at 4th index

x.search(/\d/); // return -1, i.e, no digit found

x=”AAdmin”

trim

trim method trim extra whitespace from beginning and ending.

var x=" Elysium Academy ";

x.trim(); // return "Elysium Academy"

The length property returns the number of characters in a string.

Example

// defining a string

let sentence = "I love Programiz.";

// returns number of characters in the sentence string

let len = sentence.length;

console.log(len);
// Output:

// 17

The charAt() method returns the character at the specified index in a string.

Example

// string declaration

const string = "Hello World!";

// finding character at index 1

let index1 = string.charAt(1);

console.log("Character at index 1 is " + index1);

// Output:

// Character at index 1 is e

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code
unit at the given index.

Example

// string definition

const greeting = "Good morning!";

// UTF-16 code unit of character at index 5

let result = greeting .charCodeAt(5);

console.log(result);

// Output: 109

The concat() method concatenates given arguments to the given string.

Example

let emptyString = "";

// joint arguments string

let joinedString = emptyString.concat("JavaScript", " is", " fun.");

console.log(joinedString);

// Output: JavaScript is fun.


The concat() method returns a new array by merging two or more values/arrays.

Example

let primeNumbers = [2, 3, 5, 7]

let evenNumbers = [2, 4, 6, 8]

// join two arrays

let joinedArrays = primeNumbers.concat(evenNumbers);

console.log(joinedArrays);

/* Output:

2, 3, 5, 7,

2, 4, 6, 8

*/

The slice() method returns a shallow copy of a portion of an array into a new array object.

Example

let numbers = [2, 3, 5, 7, 11, 13, 17];

// create another array by slicing numbers from index 3 to 5

let newArray = numbers.slice(3, 6);

console.log(newArray);

// Output: [ 7, 11, 13 ]

The some() method tests whether any of the array elements pass the given test function.

Example

// a test function: returns an even number

function isEven(element) {

return element % 2 === 0;

// defining an array

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


// checks whether the numbers array contain at least one even number

console.log(numbers.some(isEven));

// Output: true

The sort() method sorts the items of an array in a specific order (ascending or descending).

Example

let city = ["California", "Barcelona", "Paris", "Kathmandu"];

// sort the city array in ascending order

let sortedArray = city.sort();

console.log(sortedArray);

// Output: [ 'Barcelona', 'California', 'Kathmandu', 'Paris' ]

The splice() method returns an array by changing (adding/removing) its elements in place.

Example

let prime_numbers = [2, 3, 5, 7, 9, 11];

// replace 1 element from index 4 by 13

let removedElement = prime_numbers.splice(4, 1, 13);

console.log(removedElement);

console.log(prime_numbers);

// Output: [ 9 ]

// [ 2, 3, 5, 7, 13, 11 ]

The toLocaleString() method returns a string representing the elements of the array in a particular
locale.

Example

let array1 = ["Nepal", 1];

// returns string representation of array

let stringFromArray = array1.toLocaleString();

console.log(stringFromArray);

// Output:
// Nepal,1

The toString() method returns a string formed by the elements of the given array.

Example

// defining an array

let items = ["JavaScript", 1, "a", 3];

// returns a string with elements of the array separated by commas

let itemsString = items.toString();

console.log(itemsString);

// Output:

// JavaScript,1,a,3

The push() method adds zero or more elements to the end of the array.

Example

let city = ["New York", "Madrid", "Kathmandu"];

// add "London" to the array

city.push("London");

console.log(city);

// Output: [ 'New York', 'Madrid', 'Kathmandu', 'London' ]

The reduce() method executes a reducer function on each element of the array and returns a single
output value.

Example

const message = ["JavaScript ", "is ", "fun."];

// function to join each string elements

function joinStrings(accumulator, currentValue) {

return accumulator + currentValue;

}
// reduce join each element of the string

let joinedString = message.reduce(joinStrings);

console.log(joinedString);

// Output: JavaScript is fun.

The reverse() method returns the array in reverse order.

Example

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

// reversing the numbers array

let reversedArray = numbers.reverse();

console.log(reversedArray);

// Output: [ 5, 4, 3, 2, 1 ]

You might also like