Saturday, 31 December 2022

Java Script functions

// Declare a function

function greet(name) {

  console.log(`Hello, ${name}!`);

}


// Call a function

greet('John');


// Declare a function with a return value

function add(x, y) {

  return x + y;

}


let sum = add(5, 10);

console.log(sum);


// Declare a function with default parameters

function greet(name='John') {

  console.log(`Hello, ${name}!`);

}


greet();


// Declare a function with a rest parameter

function add(...numbers) {

  let sum = 0;

  for (const num of numbers) {

    sum += num;

  }

  return sum;

}


let total = add(1, 2, 3, 4, 5);

console.log(total);


// Declare an arrow function

let greet = (name) => {

  console.log(`Hello, ${name}!`);

};


greet('John');


// Declare an arrow function with a single parameter

let greet = name => {

  console.log(`Hello, ${name}!`);

};


greet('John');


// Declare an arrow function with a single expression

let greet = name => console.log(`Hello, ${name}!`);


greet('John');


// Declare an arrow function with a single expression and a return value

let add = (x, y) => x + y;


let sum = add(5, 10);

console.log(sum);

No comments:

Post a Comment