Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday, January 31, 2023

JavaScript Array slice() method With Examples

Javascript array slice() method is used to slice a portion of an array which is returned as a new array. Portion that is sliced is selected based on the passed start and end.

slice() method syntax

slice(start, end)

start- Index from where extraction has to be started. Index is zero based. This parameter is optional, if not passed starting index is considered as 0.

end- Index to end the extraction. slice() extracts up to but not including end. This parameter is optional, if not passed extraction ends at the last element of the array.

Return value

A new array containing the extracted elements. Note that returned array is a shallow copy which means any change in the returned array will also reflect in original array.

Note that slice() method also works with negative indexes. Negative index counts back from the end of the array. Last element has the index of -1, second last has the index of -2 and so on. if start < 0, start + array.length is used.

slice() method example

1. Using slice() method with different start and end parameters.

const cities = ['New Delhi', 'Mumbai', 'Chennai', 'Varanasi', 'Bangalore'];

//Without passing start and end
let newCities = cities.slice();
console.log(newCities); //['New Delhi', 'Mumbai', 'Chennai', 'Varanasi', 'Bangalore']

// From index 1 to end
newCities = cities.slice(1);
console.log(newCities); //['Mumbai', 'Chennai', 'Varanasi', 'Bangalore'];

//From index 1 to 3 (3 not included in the result)
newCities = cities.slice(1, 3);
console.log(newCities); //['Mumbai', 'Chennai'];

//From index 0 to -2 
newCities = cities.slice(0, -2);
console.log(newCities); //['New Delhi', 'Mumbai', 'Chennai'];

Using slice() with array of objects

When you use slice() method a shallow copy of a portion of an array is created. Since it is a shallow copy so object references remain same as in original array. Let's try to understand it with an example, suppose you have an array of persons object and you slice it to get a portion of it.

const persons = [{id:1, name:"Ajay", age:9}, 
	 {id:2, name:"Rajiv", age:22}, 
	 {id:3, name:"Bosco", age:25},
	 {id:4, name:"Albert", age:3}];

// Getting object at index 1
let newPersons = persons.slice(1, 2);
console.log(newPersons); //[{id:2, age:22, name:"Rajiv"}]

Now if you try to change object field in this new array it also reflects in the original array because of shared object reference.

newPersons[0].name = "Amit";
console.log(newPersons); // {id: 2, name: 'Amit', age: 22}
console.log(persons);
/* {id: 1, name: 'Ajay', age: 9},
{id: 2, name: 'Amit', age: 22},
{id: 3, name: 'Bosco', age: 25},
{id: 4, name: 'Albert', age: 3}*/

That's all for this topic JavaScript Array slice() method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Array map() Method
  2. JavaScript filter Method
  3. React Declarative Approach
  4. React Virtual DOM

You may also like-

  1. Abstraction in Java
  2. Lambda expressions in Java 8
  3. Volatile Keyword in Java With Examples
  4. How to Display Pyramid Patterns in Java - Part2
  5. Spring depends-on Attribute and @DependsOn With Examples

Monday, January 30, 2023

JavaScript Array map() Method With Examples

In this tutorial we'll see how to use the JavaScript Array map() method.

Suppose you have a requirement to apply some logic to each element of an array then map() method is a more convenient choice rather than iterating the array and then processing each element.

map() method

With map() you provide a function that is called upon each element of the array and a new array is created with the modified elements.

Syntax of map() method

map(callbackFn, thisArg)

Here parameters are-

  1. callbackFn- A function to execute for each element in the array.
  2. The callback function is called with the following arguments:
    • currentElement- The current array element
    • index- The index of the current element. Optional parameter and you generally won't need this parameter.
    • array- The array map() was called upon. You generally won't need this parameter.
  3. thisArg- A value to use as this when executing callbackFn. This is an Optional parameter.

Callback function can also be written as an arrow function, in that case syntax is

map((element, index, array) => { /* … */ })

or the one you'll use more frequently

map((element) => { /* … */ })

Return value

Method returns a new array which is populated with the elements of the original array after each element is processed by the callback function.

Note that the map() method is an iterative method (iterates through all the elements in the array). This method doesn't change the original array.

Javascript map method examples

1. Using map() to square each element of an array.

const numArr = [3, 5, 6, 9];

const newArr = numArr.map(getSquare);

console.log(newArr); // [9, 25, 36, 81]

function getSquare(num){
	return num * num;
}

Same thing with arrow function

const numArr = [3, 5, 6, 9];
const newArr = numArr.map(n => n * n);
console.log(newArr); // [9, 25, 36, 81]

2. Increase each element by 10%.

const numArr = [300, 500, 600, 100];

const newArr = numArr.map(n => n + (n*10/100));

console.log(newArr); // [330, 550, 660, 110]

3. Using map() with array of objects. In the example there is a persons array containing person object with fields id, firstName, lastName, age, salary. You have to create a new array with objects having fields as name- which merges both first name and last name and salaries are increased by 10%.

const persons = [{id:1, firstName:"Ajay", lastName:"Bisht", age:9, salary: 10000}, 
   {id:2, firstName:"Rajiv", lastName:"Vishnoi", age:22, salary: 12000}, 
   {id:3, firstName:"Bosco", lastName:"Caesar", age:25, salary: 20000},
   {id:4, firstName:"Albert", lastName:"Wadlow", age:3, salary: 30000}];

const newArr = persons.map(p => {
    pObj = {};
    pObj.name = p.firstName + " " + p.lastName;
    pObj.salary = p.salary + (p.salary *10/100);
    return pObj;
  });


console.log(newArr); 

/*
[{name: 'Ajay Bisht', salary: 11000}, 
{name: 'Rajiv Vishnoi', salary: 13200}, 
{name: 'Bosco Caesar', salary: 22000}, 
{name: 'Albert Wadlow', salary: 33000}]*/

That's all for this topic JavaScript Array map() Method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript filter Method
  2. JavaScript Arrow Function With Examples
  3. JavaScript Import and Export
  4. Controlled and Uncontrolled Components in React

You may also like-

  1. Angular Property Binding With Examples
  2. How to Sort HashSet in Java
  3. Read or List All Files in a Folder in Java
  4. Difference Between Encapsulation And Abstraction in Java
  5. How to Inject Null And Empty String Values in Spring

Tuesday, December 13, 2022

JavaScript filter Method With Examples

The JavaScript Array filter() method is used to filter out the elements from the given array that doesn't pass the condition implemented by the provided function and return a new array with the remaining elements.

JavaScript filter method syntax

filter(callbackFunction(element, index, array), thisArg)

Parameters:

  1. callbackFunction- A function to execute for each element in the array. In this function you will write the condition that should return true to keep the element in the resulting array, false otherwise.
    The callback function is called with the following arguments:
    • element- The element in the array being processed currently.
    • index- The index of the current element being processed in the array.
    • array- The array filter() was called upon.
  2. thisArg- This parameter is optional. A value to be used as this when executing callbackFunction.

Filter method returns a new array consisting of the elements that pass the condition of the callback function.

JavaScript filter() examples

1. In an array of cities you want to get cities having length > 7.

const cities = ['Mumbai', 'Bengaluru', 'London', 'Beijing', 'Charlotte'];

function checkCity(city){
  return city.length > 7;
}
const newCities = cities.filter(checkCity);
console.log(newCities); //  ['Bengaluru', 'Charlotte']
Callback function can also be written as an arrow function to make code more concise and readable.
const cities = ['Mumbai', 'Bengaluru', 'London', 'Beijing', 'Charlotte'];
const newCities = cities.filter(city => city.length > 7);
console.log(newCities);

2. To get the even numbers in an array of numbers.

const numbers = [2, 5, 10, 13, 24, 56, 68, 75];
const evenNum = numbers.filter(num => num%2 == 0);
console.log(evenNum); // [2, 10, 24, 56, 68]

3. In an array of Person objects filter out all persons having age < 18

const persons = [{id:1, name:"Ajay", age:9}, 
                  {id:2, name:"Rajiv", age:22}, 
                  {id:3, name:"Bosco", age:25},
                  {id:4, name:"Albert", age:3}];

const personArr = persons.filter(p => p.age > 18);
console.log(personArr); 

//Output
{id: 2, name: 'Rajiv', age: 22}
{id: 3, name: 'Bosco', age: 25}

That's all for this topic JavaScript filter Method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Array and Object Destructuring
  2. JavaScript Rest Parameter
  3. JavaScript Array slice() method With Examples
  4. React Declarative Approach

You may also like-

  1. BigInteger in Java With Examples
  2. What is Client Side Routing in Angular
  3. HashMap in Java With Examples
  4. Bean Definition Inheritance in Spring

Monday, December 12, 2022

JavaScript Rest Parameter

The JavaScript rest parameter syntax allows a function to accept variable number of arguments (zero or more) as an array. It is similar to varargs in Java.

Rest parameter syntax

Rest parameter is specified using three dots (…)

function myFunc(a, b, ...restParam) {  
  // block of statements 
}  

If you have a rest parameter in your function along with other parameters then it has to be the last argument because it has to collect the remaining arguments into an array.

Rest parameter syntax (…) is similar to spread operator in JavaScript but they do opposite job. In case of spread operator array is expanded where as in case of rest parameter arguments are collected into an array.

Rest parameter JavaScript example

A typical example is to do any mathematical operation like sum. If you write a normal function with two parameters, it will add two parameters only.

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

console.log(sum(1, 2)); // 3	
console.log(sum(1, 2, 3, 4)); //No error, but function returns 3 

As you can see when the function is called with more parameters, it still takes the first 2 and returns the sum of those arguments. If you want your sum function to be more generic which can work with any number of parameters then rest parameter gives you that functionality.

function sum(...args) {
  var s = 0;
  for(let x of args){
    s += x;
  }
  return s
}
	
console.log(sum(1, 2)); // 3

console.log(sum(1, 2, 3, 4));  //10

Rest parameter with other parameters

You can have other parameters in your function along with rest parameter but in that case rest parameter should be the last one. For example, in the following function there are two parameters and then a rest parameter.

function myFunc(a, b, ...restParam)

Calling this function like this myFunc(1, 2, 3, 4, 5) maps the first two arguments to a and b and other three parameters are passed as any array to restParam.

function myFunc(a, b, ...restParam) {
  console.log("a ", a); //a  1
  console.log("b ", b); // b  2
  console.log("Rest of the params ", restParam); // Rest of the params  (3) [3, 4, 5]
}

myFunc(1, 2, 3, 4, 5);

Rules for using Rest parameter in JavaScript

  1. One of the rules as already showed is that rest parameter must be the last parameter of the function.
    function myFunc(...restParam, a, b) {} // Wrong function definition
    
  2. A function definition can only have one rest parameter.
    function myFunc(...firstParam, ...secondParam) {} // Wrong function definition
    

That's all for this topic JavaScript Rest Parameters. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Array and Object Destructuring
  2. JavaScript let and const With Examples
  3. JavaScript Arrow Function With Examples
  4. JSX in React

You may also like-

  1. First Java Program - Hello World Java Program
  2. Dependency Injection in Spring Framework
  3. HashMap in Java With Examples
  4. Format Date in Java Using SimpleDateFormat

Tuesday, December 6, 2022

JavaScript Array and Object Destructuring

JavaScript destructuring assignment is used to unpack values from arrays, or properties from objects, into distinct variables. Using destructuring makes it more convenient to extract values and assign them to variables.

Array destructuring

const [India, USA, Japan] = ['Rupee', 'Dollar', 'Yen'];
console.log("Indian Currency - " + India); // Indian Currency - Rupee
console.log("American Currency - " + USA);// American Currency - Dollar
console.log("Japanese Currency - " + Japan);// Japanese Currency - Yen

Which is equivalent to this old way of assigning array elements to variables.

const currencies = ['Rupee', 'Dollar', 'Yen'];
const India = currencies[0];
const USA = currencies[1];
const Japan = currencies[2];
console.log("Indian Currency - " + India);
console.log("American Currency - " + USA);
console.log("Japanese Currency - " + Japan);

Extracting specific elements of an array

You may not want to assign all the elements to variables. When destructuring, don't use any variable for the array element whose value is not needed, though you still need to keep the comma for the skipped element. For example, assigning only Rupee and Yen.

const currencies = ['Rupee', 'Dollar', 'Yen'];
const [India, , Japan] = currencies;

Using Destructuring when function returns an array

You can use destructuring to assign an array returned from a function to variables. Infact that's one of the most common uses of destructuring which you'll see in React.

For example useState() hook in React returns an array with exactly two values; current state and set function. Assignment for these two returned values can be done like this-

const [prevCount, setPrevCount] = useState(count);

Object destructuring in JavaScript

const obj = {first: 'Ramesh', last: 'Sharma', age: 35 };
const {first, last, age} = obj;
console.log(first); // Ramesh
console.log(last); // Sharma
console.log(age); // 35

Which is equivalent to this old way of assigning object properties to variables.

const obj = {first: 'Ramesh', last: 'Sharma', age: 35 };
   
var f = obj.first;
var l = obj.last;
var ag = obj.age;

Assigning different name

When destructuring an object you have to use the same name for the variable as the mapped object key. If you want to use different names then you have to specify those names explicitly.

//specify new name after colon
const { first: firstName, last: lastName, age} = obj;
console.log(firstName);
console.log(lastName);
console.log(age);

Extracting specific properties of an object

You can extract specific properties of an object by giving just the needed keys. For example, if you need only first and age.

const obj = {first: 'Ramesh', last: 'Sharma', age: 35 };
const {first, age} = obj;

Passing destructured object as function arguments

If you have a function that takes object as an argument then you can pass the destructured object as function arguments to make your function more readable.

// function taking params as destructuring
function displayPerson({first, last, age}){
  console.log("first ", first, "last ", last, "age ", age)
}

That's where you will see its usage in React, to destructure props object.

In calling component-

<Person first="Ramesh" last="Sharma" age=35 />

Person Component with props

const Person = (props) => {
  return(
    <h2>{props.first} {props.last} {props.age}</h2>
  );
}

Same thing with props destructuring

const Person = ({first, last, age}) => {
  return(
    <h2>{first} {last} {age}</h2>
  );
}

That's all for this topic JavaScript Array and Object Destructuring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Spread Operator
  2. JavaScript let and const With Examples
  3. JavaScript Arrow Function With Examples
  4. React HelloWorld App - First React App
  5. React Declarative Approach

You may also like-

  1. What Are JVM, JRE And JDK in Java
  2. Java Record Class With Examples
  3. Angular Cross Component Communication Using Subject Observable
  4. How to Check Hadoop MapReduce Logs

Thursday, December 1, 2022

JavaScript let and const With Examples

ES6 introduced two new keywords let and const in JavaScript to declare variables. These two keywords are in addition to var which was the only way to declare variables until ES5.

const in JavaScript

A variable defined using const can't be reassigned, it becomes a constant value.

const rate = 10;
rate = 8; // Not allowed, Uncaught TypeError: Assignment to constant variable.

A const variable must be initialized when it is declared-

const rate; // Not allowed, Missing initializer in const declaration
rate = 8;

const with arrays and objects

When you declare an array or an object using const, you can still modify the array element or property of the object. You can't assign the const variable to a new array or object (can't change the reference).

With array

const numArr = [1, 2, 4, 4, 5];
console.log(numArr); // [1, 2, 4, 4, 5]
numArr[2] = 3; // Permitted
console.log(numArr); // [1, 2, 3, 4, 5]
numArr = [3, 4, 5]; // Not permitted, attempting to assign a new array

With object

const user = {
  name: 'Renard',
  age: 42
}
console.log(user.age); // 42
user.age = 45; // permitted
console.log(user.age); //45
// Not permitted, assigning a new object
user = {
  name: 'Raven',
  age: 24
}

let in JavaScript

Using let you can define variables that can be modified.

let message = "Hello World";
message = "Greetings!"
console.log(message); // Greetings!

Differences among let, const and var

1. var variables can be modified and even redeclared.

let variables can be modified but can't be redeclared.

const variables are constant values so can't be modified or redeclared.

// var can be redeclared
var x = "Test";
var x = 0;
//let cannot be redeclared
let a = "Test"
let a = 0; // SyntaxError: Identifier 'a' has already been declared

2. var and let can be declared first and initialized later, const must be initialized when it is declared.

let message; // declare
message = "Hello"; // initialize

3. var variables have global or function scope. let and const have block scope also apart from global or function scope.

Global scope

A variable declared outside a function, becomes a global variable having global scope. Global variables can be accessed from anywhere in JavaScript.

var x = "Test"; // global variable

function myFunction() {
  alert("From myFunction" + x); // visible in this function
}
function anotherFunction() {
  alert("From anotherFunction" +x);// visible in this function
} 

Same behavior with let and const.

Function scope

Variables declared within a JavaScript function have scope within the function (are local variables).

function myFunction() {
  // local variable
  var a = 16;
  console.log(a);
}

function anotherFunction() {
  let b = 10;
  console.log(b);
  // ERROR, a not visible here
  console.log(a)
}

Block scope

With the introduction of let and const keywords, a new scope; block Scope is provided in JavaScript. Variables declared inside a { } block cannot be accessed from outside the block.

function varTest() {
  var x = 10;
  {
    var x = 20;  // declaring x again
    console.log(x);  // 20
  }
  console.log(x);  // 20
}

function letTest() {
  let x = 10;
  {
    let x = 20;  // declaring x again
    console.log(x);  // 20
  }
  console.log(x);  // 10
}

In the function varTest() value of x is displayed as 20 outside the block too because var doesn't recognize block scope.

In the function letTest() this code

  {
    let x = 20;  // declaring x again
    console.log(x);  // 20
  }

Is in a separate block so x is 20 with in this block scope, outside this block x has value 10.

That's all for this topic JavaScript let and const With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Arrow Function With Examples
  2. JavaScript Import and Export
  3. JavaScript Array and Object Destructuring
  4. React create-react-app Project Structure

You may also like-

  1. Passing Arguments to getBean() Method in Spring
  2. Array Rotation Java Program
  3. Java Nested Class And Inner Class

Wednesday, November 30, 2022

JavaScript Import and Export

With the modular approach in JavaScript you can create a module which may contain variables, classes, functions. You can make them available in another JS file, for that you use export and import.

Breaking your code into separate modules makes it easy to maintain, more readable and increases reusability.

Export in JavaScript

Export declaration is used to export values (variables, classes, functions) from a JavaScript module. There are two types of exports-

  1. Named exports
  2. Default exports

Named exports

For using named exports you have two ways; either use export keyword with each entity or use export at the end with all entities at once.

Example when used with each entity individually.

ExportImport.js

// exporting an array
export let numArr = [1, 2, 3, 4, 5];

// exporting a constant
export const MODULE_NAME = 'ExportImport';

// exporting a function
export function hello(){
  return 'Greetings';
}

Exporting later

let numArr = [1, 2, 3, 4, 5];
const MODULE_NAME = 'ExportImport';
function hello(){
  return 'Greetings';
}
export {numArr, MODULE_NAME, hello};

You can also specify an alias while exporting using as keyword.

export {numArr, MODULE_NAME as mn, hello};

Default Exports

You may have modules declaring a single entity. Actually, this approach is preferred most of the time. If there is only a single entity in your module then you can use export default to export that entity.

You can have only a single export default per file.

ExportDefault.js

const hello = () => {
  const user = {
    name: 'Robert',
    email: '[email protected]'
  }
  console.log(user);
}

export default hello;

Import in JavaScript

You can import in a file using import keyword. If you are importing a named export then you have to wrap it in curly braces. When importing a default export then curly braces are not to be used.

JavaScript import example for named exports

Here is a HTML which imports named export from ExportImport.js file.

ExportImportDemo.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script type="module">
import {numArr, MODULE_NAME, hello} from './ExportImport.js'
document.getElementById("func").innerHTML = hello();
document.getElementById("mod").innerHTML = MODULE_NAME;
document.getElementById("arr").innerHTML = numArr;
</script>
<p id="func"></p>
<p id="mod"></p>
<p id="arr"></p>
</body>
</html>  

Points to note here-

  1. You need to include script in your HTML with a <script> element of type="module", so that it gets recognized as a module.
  2. Named exports are imported by using import keyword and wrapping entities with in curly braces.
  3. import {numArr, MODULE_NAME, hello} from './ExportImport.js'
    
  4. You can't run JS modules directly in a browser via a file:// URL — you'll get CORS errors. You need to run it via an HTTP server. I used IIS in a Windows machine.
JavaScript Import and Export

JavaScript import example for default exports

Here is a HTML which imports named export from ExportDefault.js file.

ExportDefaultDemo.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script type="module">
import hello from './ExportDefault.js'
hello();
</script>
</body>
</html>

Note that the curly braces are not required when importing default export.

import hello from './ExportDefault.js'

That's all for this topic JavaScript Import and Export. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Spread Operator
  2. JavaScript Arrow Function With Examples
  3. React HelloWorld App - First React App

You may also like-

  1. Python First Program - Hello World
  2. Python for Loop With Examples
  3. Java Semaphore With Examples
  4. Armstrong Number or Not Java Program

Monday, November 28, 2022

JavaScript Arrow Function With Examples

The JavaScript arrow function expression is a concise and more compact alternative to a normal function but it has some limitations too.

Syntax of arrow function

Arrow function is written using the fat arrow (=>). Zero or more arguments on the left side of the arrow and expression on the right side.

When no arguments-

() => expression

With single argument-

arg => expression

With multiple arguments-

(arg1, arg2, …) => expression

JavaScript arrow function example

First let's write a normal JavaScript function and then its arrow function counterpart to make it easy to understand how it differs from a normal function.

Here is a simple function hello which just returns a message.

function hello(){
	return "Greetings!"
}

If you have to write it using arrow function.

const hello = () => {
  return "Greetings!"
}

What you have to do is to remove function keyword and function name and place an arrow between the argument and opening body bracket.

() => {
  return "Greetings!"
}

Arrow functions are always anonymous functions. You can assign the arrow function to a variable so it has a name. That's what is done by assigning it to const hello.

You can call the function using this variable name.

let s = hello()
console.log(s);

You can make the above arrow function more compact; if an arrow function has only a single return statement, then you can remove the curly braces and return keyword. The return is implied.

const hello = () => "Greetings!"

Arrow function with single parameter

const hello = (name) => "Greetings " + name + "!";

If your arrow function has a single parameter then the parenthesis is optional.

const hello = name => "Greetings " + name + "!"

Arrow function with multiple parameters

const sum = (a, b) => a + b;

Remember that parenthesis can't be omitted in the case of multiple parameters and no parameters, only in the case of single parameter you can omit parenthesis.

Multiline arrow functions

If you are writing an arrow function with multiple expressions and statements then you need to enclose them in curly braces. An explicit return is also required since curly braces require a return within them to return a value.

For example, an arrow function to get maximum value using if-else.

const max = (a, b) => {
  let m;
  if(a > b)
    m = a;
  else
    m = b;
  return m;
}

Of course, the same thing can be written in a much more compact way using ternary operator.

const max = (a, b) => (a > b) ? a : b;

Limitations of arrow functions

  1. With arrow functions there are no binding of this. The value of this is determined by the surrounding scope instead.
  2. Arrow functions should not be used as class methods because of the way this is used in case of arrow functions.
  3. Arrow functions cannot be used as constructors because they do not have a prototype property.

That's all for this topic JavaScript Arrow Function With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Spread Operator
  2. JavaScript Import and Export
  3. JavaScript Array map() Method
  4. JavaScript filter Method
  5. React HelloWorld App - First React App

You may also like-

  1. Angular Application Bootstrap Process
  2. Lambda expressions in Java 8
  3. How HashMap internally works in Java
  4. How to Untar a File in Java