JavaScript is a client-side scripting language, his generated by Brendan Eich In 1995
It is a Event based Programming language (for HTML & CSS)
JavaScript is a high-level untype interpreater programming language,
JavaScript follow Object oriented programming structure
,
JavaScript provide client side validation and It is a case sensiitive.
Full integration with HTML & CSS, simple things are done simply and support by all major browser
It is used to view the releted information and to see the JavaScript Error
There are three ways to add Js in our web page
Click me
function changeColor(arg){
arg.style.color='red';
}
⭕ In HTML4 type attribute use for javascript type but in HTML5 type attribute is used for module define
⭕ The benefit of the external js is that browser will download this file and store it in the cache, when you come next time this site it will take minimum time to load it
⭕ If there are set src attribute in the script then don't write code in this script tag, we have to create other script tag and write code here
⭕ We use language attribute to see which scripting language we use
For fully enable all features of modern JavaScript, we should start script code with "use_strict"
"use_strict";
document.write('Hello Tech Pravin');
Variable is a container that contains a value, value may get change during the execution of program
Variable is named storage, Variable use to store data
⭕ Variable name must not be var, let, const, class, return, function
⭕ var scope is global scope
⭕ let & const scope is block scope
⭕ We cannot change the value of const, but when we create an object using const we can change its value
//Here we can understand easily
function check(){
var a = 1;
}
document.write(a); // output 1
function check(){
let a = 1;
}
document.write(a); // Error because here a is block scope
⭕ prompt(); // for input
⭕ confirm(); // for confirmation
⭕ alert(); // for output
⭕ document.write(); // for output
⭕ document.writeln(); // for output
⭕ console.log(); // for output
⭕ console.worn(); // for output
⭕ console.error(); // for output
⭕ console.clear(); // for output
⭕ console.table(); // for output
DataType is a keyword which specifies the value of the variable, but javaScript dataType handle dynamicly, because JavaScript is a untyped language
Primitive datatype has some properties and some methods and Can't create it with the new keyword
There are total eight type of dataType in javaScript
⭕ String // let a = 'techpravin'; or let a = "techpravin" or let a = `techpravin`;
⭕ Boolean // let a = true; or let a = false;
⭕ null // let a = null;
⭕ undefined // let a;
⭕ Number // let a = 123; // Regular numbers in JavaScript are stored in 64-bit format
⭕ BigInt // let a = 10n; // BigInt numbers, to represent integers of arbitrary length.
⭕ Symbol // let a = Symbol("id");
⭕ Object // let a = []; or let a = {};
The typeof operator returns the type of the argument. It’s useful when we want to check variable type.
alert(typeof undefined); // "undefined"
alert(typeof 0); // "number"
alert(typeof 10n); // "bigint"
alert(typeof true); // "boolean"
alert(typeof "foo"); // "string"
alert(typeof Symbol("id")); // "symbol"
alert(typeof Math); // "object" (1)
alert(typeof null); // "object" (2)
alert(typeof alert); // "function" (3)
let value = true;
alert(typeof value); // boolean
value = String(value); // now value is a string "true"
alert(typeof value); // string
let str = "123";
alert(typeof str); // string
let num = Number(str); // becomes a number 123
alert(typeof num); // number
An operator performs some operation on two or moere operands and produces a result.
There are six type of operator in JS
⭕ Arithmetical operator (+,-,*,/,%,**)
//Here you can understand with example
let x = 1;
x = -x;
alert( x ); // -1, unary negation was applied
let x = 1, y = 3;
alert( y - x ); // 2, binary minus subtracts values
alert( 5 % 2 ); // 1, a remainder of 5 divided by 2
alert( 2 ** 2 ); // 2² = 4
alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)
let s = "my" + "string";
alert(s); // mystring
alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21"
alert(2 + 2 + '1' ); // "41" and not "221"
alert('1' + 2 + 2); // "122" and not "14"
alert( 6 - '2' ); // 4, converts '2' to a number
alert( '6' / '2' ); // 3, converts both operands to numbers
// No effect on numbers
let x = 1;
alert( +x ); // 1
let y = -2;
alert( +y ); // -2
// Converts non-numbers
alert( +true ); // 1
alert( +"" ); // 0
let apples = "2";
let oranges = "3";
alert( apples + oranges ); // "23", the binary plus concatenates strings
let apples = "2";
let oranges = "3";
// both values converted to numbers before the binary plus
alert( +apples + +oranges ); // 5
// the longer variant
// alert( Number(apples) + Number(oranges) ); // 5
alert( 2 > 1 ); // true (correct)
alert( 2 == 1 ); // false (wrong)
alert( 2 != 1 ); // true (correct)
let result = 5 > 4; // assign the result of the comparison
alert( result ); // true
alert( 'Z' > 'A' ); // true
alert( 'Glow' > 'Glee' ); // true
alert( 'Bee' > 'Be' ); // true
alert( '2' > 1 ); // true, string '2' becomes a number 2
alert( '01' == 1 ); // true, string '01' becomes a number 1
alert( true == 1 ); // true
alert( false == 0 ); // true
let a = 0;
alert( Boolean(a) ); // false
let b = "0";
alert( Boolean(b) ); // true
alert(a == b); // true!
alert( 0 == false ); // true
alert( '' == false ); // true
alert( 0 === false ); // false, because the types are different
alert( null === undefined ); // false
alert( null == undefined ); // true
alert( null > 0 ); // (1) false
alert( null == 0 ); // (2) false
alert( null >= 0 ); // (3) true
alert( undefined > 0 ); // false (1)
alert( undefined < 0 ); // false (2)
alert( undefined == 0 ); // false (3)
if (new Date().getFullYeay() == 2021) {
alert( "That's correct!" );
alert( "You're so smart!" );
}
let accessAllowed;
let age = prompt('How old are you?', '');
if (age > 18) {
accessAllowed = true;
} else {
accessAllowed = false;
}
alert(accessAllowed);
alert( true || true ); // true
alert( false || true ); // true
alert( true || false ); // true
alert( false || false ); // false
alert( true && true ); // true
alert( false && true ); // false
alert( true && false ); // false
alert( false && false ); // false
alert( null || 2 || undefined ); // 2
alert( 1 && null && 2 ); // null
alert( alert(1) && alert(2) ); // null and undefined
let user;
alert(user ?? "Tech Pravin"); // Tech Pravin (user not defined)
If an expression has more than one operator, the execution order is defined by their precedence, or, in other words, the default priority order of operators.
| Precedence | Name | Sign |
|---|---|---|
| … | … | … |
| 17 | unary plus | + |
| 17 | unary negation | - |
| 16 | exponentiation | ** |
| 15 | multiplication | * |
| 15 | division | / |
| 13 | addition | + |
| 13 | subtraction | - |
| … | … | … |
| 3 | assignment | = |
| … | … | … |
When we often need to repeat actions then we use loop
There are seven type of loop in JavaScript
⭕ forThe condition is checked before each iteration, additional settings available.
for loop used when the length is known
for (inetialization; condition; updation) {
// ... loop body ...
}
for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2
alert(i);
}
// Any part of for can be skipped.
// For example, we can omit begin if we don’t need to do anything // at the loop start.
// Like here:
let i = 0; // we have i already declared and assigned
for (; i < 3; i++) { // no need for "begin"
alert( i ); // 0, 1, 2
}
// We can also remove the updation part:
let i = 0;
for (; i < 3;) {
alert( i++ );
}
while loop used when the length is unknown
mostly while loop, we use for fetching records in the database
The condition check can be moved below the loop body using the do..while syntax
while (condition) {
// code
// so-called "loop body"
}
let i = 1;
while (i <= 50) { // shows 1 to 50
alert(i);
i++;
}
// do while
do {
// loop body
} while (condition);
let i = 0;
do {
alert( i );
i++;
} while (i < 3);
The forEach method allows to run a function for every element of the array.
let arr = [1,2,3,4,5];
arr.forEach(function(item, index, array) {
// ... do something with item
});
The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, Maps, NodeLists, generator function and more:
Iterable - An object that has iterable properties.
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element);
}
// output
> "a"
> "b"
> "c"
The for...in statement iterates over all enumerable properties of an object that are keyed by strings.
var obj = {a: 1, b: 2, c: 3};
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
// Output:
> "obj.a = 1"
> "obj.b = 2"
> "obj.c = 3"
The for await...of statement creates a loop iterating over async iterable objects as well as on sync iterables, including: built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined async/sync iterables.
for await (variable of iterable) {
// statement
}
async function* asyncGenerator() {
let i = 0;
while (i < 3) {
yield i++;
}
}
(async function() {
for await (let num of asyncGenerator()) {
console.log(num);
}
})(); // this is cald anonimus function
> 0
> 1
> 2
JavaScript statements are the commands to tell the browser to what action to perform. Statements are separated by semicolon (;).
There are nine type of statement in JavaScript
⭕ BlockA block statement is a sequence of zero or more statements enclosed in braces.
var x = 1;
let y = 1;
if (true) {
var x = 2;
let y = 2;
}
console.log(x);
> 2
console.log(y);
> 1
Normally, a loop exits when its condition becomes falsy. But we can force the exit at any time using the special break directive.
for (let i = 0; i < 10; i++) {
// if true, skip the remaining part of the body
if (i == 5) break;
alert(i); // 1, then 2, 3, 4, 5
}
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
for (let i = 0; i < 10; i++) {
// if true, skip the remaining part of the body
if (i % 2 == 0) continue;
alert(i);
> 1, then 3, 5, 7, 9
}
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
const array1 = [1, 2, 3];
// Assign all array values to 0
for (let i = 0; i < array1.length; array1[i++] = 0) /* empty statement */;
console.log(array1);
> Array [0, 0, 0]
The if statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed.
if (condition) {
statement1
} else {
statement2
}
let i = 1;
while(i<=100){
if(i%2 == 0){
console.log("even no");
}else{
console_log("odd number");
}
}
A switch statement can replace multiple if checks. It gives a more descriptive way to compare a value with multiple variants.
The switch has one or more case blocks and an optional default.
let a = 2 + 2;
switch (a) {
case 3:
alert( 'Too small' );
break;
case 4:
alert( 'Exactly!' );
break;
case 5:
alert( 'Too big' );
break;
default:
alert( "I don't know such values" );
}
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed)
function getRectArea(width, height) {
if (isNaN(width) || isNaN(height)) {
throw 'Parameter is not a number!';
}
}
try {
getRectArea(3, 'A');
} catch (e) {
console.error(e);
// expected output: "Parameter is not a number!"
}
The try...catch statement marks a block of statements to try and specifies a response should an exception be thrown.
try {
try_statements
}
catch (exception_var) {
catch_statements
}
finally {
finally_statements
}
// Example
(function() {
try {
try {
throw new Error('oops');
} catch (ex) {
console.error('inner', ex.message);
throw ex;
} finally {
console.log('finally');
return;
}
} catch (ex) {
console.error('outer', ex.message);
}
})();
// Output:
// "inner" "oops"
// "finally"
The with statement extends the scope chain for a statement.
let a, b, c;
const r = 10;
with (Math) {
a = PI * r * r;
b = r * cos(PI);
c = r * sin(PI / 2);
}
console.log(a);
console.log(b);
console.log(c);
> 314.1592653589793
> -10
> 10
Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition.
There are seven type of function in javaScript
⭕ Function declaration
✔ function declartion
function functionName(){
console.log("Welcome tech pravin");
}
functionName();
> Welcome tech pravin
✔ function experassion
let fun = function(){
console.log("Welcome tech pravin");
}
fun();
> Welcome tech pravin
✔ anonimus function
(function(){
console.log("Hello I am Anonimus function");
})();
> Hello I am Arrow function
✔ Arrow function
let arrow = () => {
console.log("Hello I am Arrow function");
}
arrow();
> Hello I am Arrow function
✔ Async function
async function hello() {
return greeting = await Promise.resolve("Hello");
};
hello().then(alert);
✔ Generator function
function* generator(i) {
yield i;
yield i + 10;
}
const gen = generator(10);
console.log(gen.next().value);
> 10
console.log(gen.next().value);
> 20
✔ new Function()
let func = new Function('a','b','return a+b');
alert(sum(1,2,3,4,5));
> 15
✔ Construction function
function Fruit(color, taste, seeds) {
this.color = color;
this.taste = taste;
this.seeds = seeds;
}
// Create an object
const fruit1 = new Fruit('Yellow', 'Sweet', 1);
// Display the result
document.write(fruit1.color);
> Yellow
✔ factory function
let john = {
firstName: 'Tech',
lastName: 'Pravin',
getFullName() {
return this.firstName + ' ' + this.lastName;
}
};
console.log(john.getFullName());
>Tech Pravin
Objects are used to store keyed collections of various data and more complex entities. object is a collection of datamember and method, Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value.
There are three way to create an object in javaScript
let user = new Object(); // "object constructor" syntax
let user = {}; // "object literal" syntax
let user = Object.create({"name":"Pravin"});
let user = { // an object
name: "John", // by key "name" store value "John"
age: 30 // by key "age" store value 30
};
alert( user.name ); // John
alert( user.age ); // 30
// We can also use multiword property names, but then they must be quoted:
let user = {
name: "John",
age: 30,
"likes birds": true // multiword property name must be quoted
};
let user = {};
// set
user["likes birds"] = true;
// get
alert(user["likes birds"]); // true
// delete
delete user["likes birds"];
let a = {};
let b = a;
alert( a == b ); // true, both variables reference the same object
alert( a === b ); // true
// We also can use Object.assign to replace for..in loop for simple cloning:
let user = {
name: "John",
age: 30
};
let clone = Object.assign({}, user);
The value of this is the object “before dot”, the one used to call the method. The value of this is defined at run-time. Methods can reference the object as this. When a function is declared, it may use this, but that this has no value until the function is called. A function can be copied between objects. When a function is called in the “method” syntax: object.method(), the value of this during the call is object.
Note:-that arrow functions are special: they have no this. When this is accessed inside an arrow function, it is taken from outside.
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs. This is the same as iterating with a for...in loop
Object.keys() method returns all object keys
Object.values() method returns all object values
The Object.freeze() method freezes an object. A frozen object can no longer be changed
const obj = {
prop: 42
};
Object.freeze(obj);
obj.prop = 33;
// Throws an error in strict mode
console.log(obj.prop);
// expected output: 42
The Object.fromEntries() method transforms a list of key-value pairs into an object.
const entries = new Map([
['foo', 'bar'],
['baz', 42]
]);
const obj = Object.fromEntries(entries);
console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }
The Object.is() method determines whether two values are the same value.
Object.is(25, 25); // true
Object.is('foo', 'foo'); // true
Object.is('foo', 'bar'); // false
Object.is(null, null); // true
Object.is(undefined, undefined); // true
Object.is(window, window); // true
Object.is([], []); // false
var foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo); // true
Object.is(foo, bar); // false
The Object.seal() method seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable.
const object1 = {
property1: 42
};
Object.seal(object1);
object1.property1 = 33;
console.log(object1.property1);
// expected output: 33
delete object1.property1; // cannot delete when sealed
console.log(object1.property1);
// expected output: 33
By specification, object property keys may be either of string type, or of symbol type. Not numbers, not booleans, only strings or symbols, these two types.
let id1 = Symbol("id");
let id2 = Symbol("id");
alert(id1 == id2); // false
// Symbols are skipped by for…in
There are 7 primitive types: string, number, bigint, boolean, symbol, null and undefined.
In modern JavaScript, there are two types of numbers:
1. Regular numbers in JavaScript are stored in 64-bit format
let billion = 1000000000;
let billion = 1_000_000_000;
let billion = 1e9;
alert( 0xff ); // 255
alert( 0xFF ); // 255
Number.isFinite(1 / 0); //false
Number.isInteger(1); //true
Number.isInteger('1'); //false
Number.isNaN(1); //false
Number.parseFloat()
Number.parseInt();
var number = 3500;
alert(number.toLocaleString("hi-IN")); // ३,५००
Math.floor(3.1) // 3
Math.floor(-3.1) // -4
Math.ceil(3.1) // 4
Math.ceil(-3.1) // -3
Math.round(3.1) // 3
Math.round(3.6) // 4
Math.round(-1.1) // -1
Math.sqrt();
Math.cbrt();
Math.random(); // it will return random number
Math.pow();
Math.max();
Math.min();
Math.toFixed();
In JavaScript, the textual data is stored as strings. There is no separate type for a single character.
there are four way to write stringOne of the old tricks used here is the bitwise NOT ~ operator. It converts the number to a 32-bit integer (removes the decimal part if exists) and then reverses all bits in its binary representation. In practice, that means a simple thing: for 32-bit integers ~n equals -(n+1).
let str = "Pravin";
let str = 'Pravin';
let str = `Pravin`;
let str = new String("Pravin"); // string object
alert( "\u00A9" ); // ©
alert( "\u{20331}" ); // 佫, a rare Chinese hieroglyph (long Unicode)
alert( "\u{1F60D}" ); // 😍,
alert( "\u03A9" ); // Ω
// Strings are immutable
let str = 'Hi';
str[0] = 'h'; // error
alert( str[0] ); // doesn't work
alert( ~2 ); // -3, the same as -(2+1)
alert( ~1 ); // -2, the same as -(1+1)
alert( ~0 ); // -1, the same as -(0+1)
alert( ~-1 ); // 0, the same as -(-1+1)
| Character | Description |
|---|---|
\n |
New line |
\r |
Carriage return: not used alone. Windows text files use a combination of two characters \r\n to represent a line break. |
\', \" |
Quotes |
\\ |
Backslash |
\t |
Tab |
\b, \f, \v |
Backspace, Form Feed, Vertical Tab – kept for compatibility, not used nowadays. |
\xXX |
Unicode character with the given hexadecimal Unicode XX, e.g. '\x7A' is the same as 'z'. |
\uXXXX |
A Unicode symbol with the hex code XXXX in UTF-16 encoding, for instance \u00A9 – is a Unicode for the copyright symbol ©. It must be exactly 4 hex digits. |
\u{X…XXXXXX} (1 to 6 hex characters) |
A Unicode symbol with the given UTF-32 encoding. Some rare characters are encoded with two Unicode symbols, taking 4 bytes. This way we can insert long codes. |
Strings can be created as primitives, from string literals, or as objects, using the String() constructor:
return 'cat'.charAt(1) // returns "a"
return 'cat'[1] // returns "a"
const str1 = 'Pravin';
const str2 = 'Kumar';
console.log(str1.concat(' ', str2));
// expected output: "Pravin Kumar"
let str = 'Widget with id';
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// expected output: "Fire,Air,Water"
alert( str.indexOf('Widget') ); // 0,
alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive
alert( "Widget with id".includes("Widget") ); // true
alert( "Hello".includes("Bye") ); // false
alert( "Widget".includes("id", 3) ); // false, from position 3 there is no "id"
alert( "Widget".startsWith("Wid") ); // true, "Widget" starts with "Wid"
alert( "Widget".endsWith("get") );
let str = "stringify";
alert( str.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5)
alert( str.slice(0, 1) ); // 's', from 0 to 1, but not including 1, so only character at 0
alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"
let str = "stringify";
alert( str.substr(2, 4) ); // 'ring', from the 2nd position get 4 characters
" pravin ".trim(); //pravin – removes (“trims”) spaces from the beginning and end of the string.
console.log(" pravin ".trimEnd());//" Pravin"
console.log(" pravin ".trimStart());//"Pravin "
Pra.repeat(3); // praprapra
str.toUpperCase()
str.toLowerCase()
const a = 'réservé'; // with accents, lowercase
const b = 'RESERVE'; // no accents, uppercase
console.log(a.localeCompare(b));
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);
console.log(found);
// expected output: Array ["T", "I"]
const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';
const array = [...str.matchAll(regexp)];
console.log(array[0]);
// expected output: Array ["test1", "e", "st1", "1"]
const str1 = 'Breaded Mushrooms';
console.log(str1.padEnd(25, '.'));
// expected output: "Breaded Mushrooms........"
const str1 = '5';
console.log(str1.padStart(2, '0'));
// expected output: "05"
const fullNumber = '2034399002125581';
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, '*');
console.log(maskedNumber);
// expected output: "************5581"
let p ="Pravin kumar";
console.log(p.replace('kumar', 'dubey')); // Pravin dubey
console.log(p.replaceAll('kumar', 'dubey')); // all replace matched charector
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
// any character that is not a word character or whitespace
const regex = /[^\w\s]/g;
console.log(paragraph.search(regex));
// expected output: 43
Array is a special kind of object, suited to storing and managing ordered data items.
There are three type to create array
let arr = [];
let arr = new Array();
let arr = Array.of(1,2,3);
let fruits = ["Apple", "Orange", "Plum"];
alert( fruits[0] ); // Apple
alert( fruits.length ); // 3
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
const array1 = ['a', 'b', 'c', 'd', 'e'];
// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]
const array1 = ['a', 'b', 'c'];
// The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array.
const iterator1 = array1.entries();
console.log(iterator1.next().value);
// expected output: Array [0, "a"]
console.log(iterator1.next().value);
// expected output: Array [1, "b"]
console.log(iterator1.next().value); // [2, "c"]
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
const array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element)); // a b c
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
Array.isArray([1,2,3]); // true
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// expected output: "Fire,Air,Water"
console.log(elements.join('-'));
// expected output: "Fire-Air-Water"
const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
for (const key of iterator) {
console.log(key);
}
> 0, 1, 2
const iterator = array1.values();
for (const value of iterator) {
console.log(value);
}
> a, b , c
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
console.log(animals.lastIndexOf('Dodo'));
// expected output: 3
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
// expected output: "tomato"
console.log(plants.push("Pravin"));
// ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato','pravin']
console.log(plants.shift());
// 'broccoli'
console.log(plants.unshift("dubey"));
// ['dubey',broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato','pravin']
console.log(plants.splice(1,0));
// ['dubey', 'cauliflower', 'cabbage', 'kale', 'tomato','pravin']
console.log(plants.splice(4,'Ram'));
// ['dubey', 'cauliflower', 'cabbage', 'kale', 'Ram','pravin']
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
months.reverse();
// expected output: Array ["Dec","Feb","Jan","March"]
const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// expected output: "1,2,a,1a"
const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// expected output: true