Skip to content

Latest commit

 

History

History
132 lines (123 loc) · 2.24 KB

15. Arrow functions.md

File metadata and controls

132 lines (123 loc) · 2.24 KB

JavaScript Arrow Functions

Example 1

function greet() {
    console.log("Good Morning");
}

greet();

Output

Good Morning

Example 2

const greet = () => console.log("Good Morning");

greet();

Output

Good Morning

Example 3

const greet = () => {
  console.log("Good Morning");
  console.log("How are you?");
}

greet();

Output

Good Morning
How are you?

Arrow function with Argument

Example 1

let addNumbers = (a, b) => console.log(a + b);

addNumbers(5, 9);

Output

14

Example 2

let addNumbers = a => console.log(a ** 2);

addNumbers(5, 9);

Output

25

Arrow Function with return statement

let addNumbers = (a, b) => {
    let result = a + b;
    return result;
}
let sum = addNumbers(5, 8);
console.log("The sum is " + sum);

Output

The sum is 13.

let addNumbers = (a, b) => {
    let result = a + b;
    return result;
    console.log("After Return");
}
let sum = addNumbers(5, 8);
console.log("The sum is " + sum);

Output

Result = 17

Assignment and Task

Can you create a program using an arrow function to check if the number entered by the user is a prime number or not. This function should compute the result and return them to the function call. And, the results should be printed from outside the function.

Solution:

let findPrime = (number) => {
    let result = true;
    for (let i = 2; i <= number -1; i++) {
        if(number % i == 0) {
            result = false;
            break;
        }
    }
    return result;
}

const userValue = prompt(parseInt("Enter a positive number: "));
let checkResult = findPrime(userValue);
if(checkResult) {
    console.log("The number is prime.");
} else {
    console.log("The number is not prime.");
}

Output

Enter a positive number: 435
The number is not prime.

Programiz Quiz

Q. What is the correct way to call this arrow function?

let calculatePrime = (number) => {...}
  1. (5) =>
  2. =>(5);
  3. calculatePrime(5) =>
  4. calculatePrime(5);

Answer: 4