Functions in JavaScript

Functions In JavaScript

Functions: any logic/code that you have written, you wrap that and assign a name to it. So that whenever you need that logic again you can get it by that name.

Eg:

  • a code to add 2 numbers,
  • a code to check if a number is even,
  • a code to check if a given phone number is valid, has 10 digits
function twoNumberSum(num1, num2) {
  return num1 + num2
}

function isEven(num) {
  if (num % 2 === 0) {
    return true
  } else {
    return false
  }
}

function isPhoneNumberValid (phoneNumber) {
  if (phoneNumber.toString().length === 10) {
    return true
  } else {
    return false
  }
}

Functions In JavaScript

Purpose of Functions: they are simply a wrapper around your code, any piece of code that you want to store or use in multiple places, you can put them in functions.

Functions broadly have 4 parts:

  1. name of function (isPhoneNumberValid) 
  2. parameters (phoneNumber)
  3. logic code
  4. return value (true/false)
    (return is keyword in JavaScript that can be used only inside a function)
function twoNumberSum(num1, num2) {
  return num1 + num2
}

function isEven(num) {
  if (num % 2 === 0) {
    return true
  } else {
    return false
  }
}

function isPhoneNumberValid (phoneNumber) {
  if (phoneNumber.toString().length === 10) {
    return true
  } else {
    return false
  }
}

Functions In JavaScript

Different languages implement functions differently, still their purpose remains same in all languages.

In JavaScript, based on use case:

  1. Functions, may be defined to receive no parameters.
  2. Functions may have no return value
  3. Functions may have no name as well (anonymous functions)
let userName = "Yash"

function addBatchInfo () { // no parameters
  const batchInfo = "WMB2"
  userName = `${userName}-${batchInfo}`
  // no return statement as well
}

console.log(userName)


const divElement = document.getElementByTagName('div')

divElement.addEventListener('mouseenter', function(){ // function without name, callback
  divElement.style.background: "green"  
})

Functions In JavaScript

Creating a Function:

In JavaScript, functions can be created in 4 different ways:

// Function Declaration 
// function name () {}
function addBatchInfo (userName) {
  const batchInfo = "WMB2"
  const userWithInfo = `${userName}-${batchInfo}`
  return userWithInfo
}


// Arrow Functions 
// const name = () => {}
const addBatchInfo = (userName) => {
  const batchInfo = "WMB2"
  const userWithInfo = `${userName}-${batchInfo}`
  return userWithInfo
}


// Function Expression
// const name = function () {}
const addBatchInfo = function (userName) {
  const batchInfo = "WMB2"
  const userWithInfo = `${userName}-${batchInfo}`
  return userWithInfo
}

// Functions as a Method
// name () {}
const userObj = {
  userName: "Yash",
  batchInfo: "WMB2",
  addBatchInfo (userName) {
    const batchInfo = "WMB2"
    const userWithInfo = `${userName}-${batchInfo}`
    return userWithInfo
  }
}

the 4th way, function as a method, is a use case of functions, so all the other 3 methods can also be used to create a function inside an object

  1. Function Declaration,
  2. Arrow Functions,
  3. Function Expression,
  4. Methods

Functions In JavaScript

Calling/Invoking a Function:

Calling/Invoking a function means using it:

  1. We call a function using parentheses "()"
  2. the values that function receive at the function definition are called parameters
  3. the values that function receive at the function invocation are called arguments
  4. Function is declared only once, but can be invoked any number of times
// Function Declaration 
// function name () {}
function addBatchInfo (userName) {
  const batchInfo = "WMB2"
  const userWithInfo = `${userName}-${batchInfo}`
  return userWithInfo
}
addBatchInfo("YashDeclaration")

// Arrow Functions 
// const name = () => {}
const addBatchInfo = (userName) => {
  const batchInfo = "WMB2"
  const userWithInfo = `${userName}-${batchInfo}`
  return userWithInfo
}
addBatchInfo("YashArrow")

// Function Expression
// const name = function () {}
const addBatchInfo = function (userName) {
  const batchInfo = "WMB2"
  const userWithInfo = `${userName}-${batchInfo}`
  return userWithInfo
}
addBatchInfo("YashExpression")

// Functions as a Method
// name () {}
const userObj = {
  userName: "Yash",
  batchInfo: "WMB2",
  addBatchInfo (userName) {
    const batchInfo = "WMB2"
    const userWithInfo = `${userName}-${batchInfo}`
    return userWithInfo
  }
}
userObj.addBatchInfo("YashMethod")

Functions In JavaScript

Function properties

  1. Functions which are defined to have parameters, can still be called without passing any arguments. And vice-versa is also true.
  2. functionName.length gives number of parameters that are defined for the function.
  3. functionName.name gives function's name
function addBatchInfo (userName) { // a parameter is defined
  const batchInfo = "WMB2"
  const userWithInfo = `${userName}-${batchInfo}`
  return userWithInfo
}

addBatchInfo.length
// Expected: 1

addBatchInfo() // called without argument, 
// hence userName is undefined


function addBatchInfo () { // no parameter is defined
  const batchInfo = "WMB2"
  const userWithInfo = `${"yash"}-${batchInfo}`
  return userWithInfo
}

addBatchInfo("priyam") // called with argument, 
// hence "priyam" is un-used

Functions In JavaScript

Default Value in Function Parameter:

  1. Default value for function parameters: you can assign default value for parameters in-case a parameter doesn't get an argument
function addBatchInfo (userName = "Admin", batch = "WMB2") { // a parameter is defined
  const userWithInfo = `${userName}-${batch}`
  return userWithInfo
}

addBatchInfo() // called without argument, 
// hence userName will use default value
// userName = "Admin"

Functions In JavaScript

Calling/Invoking a Function:

  1. arguments: it's a keyword, used inside a function body only.
  2. "arguments" is an array of all the arguments that function is passed during invocation, already defined
    and accessible inside function body.
  3. No parameters are defined for the function but there is a chance that the function might be called with some arguments, or you are not sure with what/how many arguments the function will be called, then you use arguments in function.
// Here function does not recieve any parameter
// but still it's being called with argument
// Now, you want to access that parameter
// inside the function, you can use
// arguments inside the function

function func1(a, b, c) {
  console.log(arguments[0]);
  // Expected output: 1

  console.log(arguments[1]);
  // Expected output: 2

  console.log(arguments[2]);
  // Expected output: 3
}

func1(1, 2, 3);

function addBatchInfo () { // no parameter is defined
  const batchInfo = "WMB2"
  const userArg = arguments[0]
  const userWithInfo = `${userArg}-${batchInfo}`
  
  console.log(userWithInfo)
  // Expected output: "priyam-WMB2"
}

addBatchInfo("priyam") // called with argument, 
// hence "priyam" is un-used

Functions In JavaScript

Rest parameters

  1. Rest parameters: introduced in es6.
  2. Do exactly the same thing as arguments, just in a better way.
  3. If you're not sure how many arguments cold come just add (...anyName) in the function parameters.
  4. You can use rest parameters partially as well.
function func1 (...someArgs) {
  console.log(someArgs[0]);
  // Expected output: 1

  console.log(someArgs[1]);
  // Expected output: 2

  console.log(someArgs[2]);
  // Expected output: 3
}

func1(1, 2, 3);

function addBatchInfo (...args) { // no parameter is defined
  const batchInfo = "WMB2"
  const userArg = args[0]
  const userWithInfo = `${userArg}-${batchInfo}`
  
  console.log(userWithInfo)
  // Expected output: "priyam-WMB2"
}

addBatchInfo("priyam") // called with argument, 
// hence "priyam" is un-used

// Partial rest syntax
function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  // a, one
  console.log("b", b);
  // b, two
  console.log(manyMoreArgs);
  // ["three", "four", "five", "six"]
  // []
}

myFun("one", "two", "three", "four", "five", "six");
myFun("one", "two");

Conditionals in JavaScript

Conditionals In JavaScript

In JavaScript, there are 4 ways to write conditionals:

  1. if/else,
  2. if, else-if, else
  3. Ternary Operator
  4. switch-case
// if () {
// } else {
// }

const arr = [1,2,3,4]

if (arr.length === 4) {
  console.log(arr.length)
} else {
  console.log("Array length invalid ")
}

// can do this till only one line of code 
// is inside the blocks
if (arr.length === 4) console.log(arr.length)
else console.log("Array length invalid ")


// can use only if
if (arr.length === 4) {
  console.log(arr.length)
}
if (arr.length === 4) console.log(arr.length)

//nesting is also allowed
if (arr.length >= 4) {
  if (arr.length % 2 === 0) {
    console.log(arr.length)
  }
} else {
  if (arr.length % 2 !== 0) {
    console.log("Array length is odd")
  } else {
    console.log("Array length not even ")
  }
}

if/else: it is simple conditional statement, where a condition is added in if block and if that condition turns out true, the if block code is executed and if not then automatically else block code, if present, gets executed.

Conditionals In JavaScript

const choice = "snowing"
let messageValue;

if (choice === "sunny") {
  messageValue =
    "It is nice and sunny outside today";
} else if (choice === "rainy") {
  messageValue =
    "Rain is falling outside; take a rain coat";
} else if (choice === "snowing") {
  messageValue =
    "The snow is coming down — it is freezing!";
} else if (choice === "overcast") {
  messageValue =
    "It isn't raining, but the sky is grey and gloomy;";
} else {
  messageValue = "";
}

if, else-if, else: 

  1. can add multiple cases, with else-if,
  2. the last else is optional

Conditionals In JavaScript

Ternary Operator: just a different way to write if, else conditional

// (condition) ? (if-block) : (else-block)

const arr = [1,2,3,4]

(arr.length === 4) ? console.log(arr.length) : console.log("Array length invalid ")


// can NOT use only if block
(arr.length === 4) ? console.log(arr.length) // XXXX - Not allowed


// nesting is also allowed
(arr.length >= 4) ? console.log(arr.length) : (arr.length % 2 !== 0) 
? console.log("Array length is odd") 
: console.log("Array length not even ")

// Also used for assignment
const message = weather === "sunny" ? `weather is ${weather} today` : "weather is not good"

Conditionals In JavaScript

switch-case:

it has 4 keywords - switch - takes condition,

case - takes values/expression,

break - added to each case, stops evaluation of further cases once a case matches with switch,

default - assigns a default value if non of the cases match the switch condition,

const foo = 0;

switch (foo) {
  case -1:
    console.log("negative 1");
    break;
  case 0:
    console.log("match");
    break; // Break encountered; will not continue into 'case 2:'
  case 2:
    console.log(2);
    break;
  default:
    console.log("default");
}
// Logs 0 and 1

Conditionals In JavaScript

some facts regarding switch-case:

const foo = 1;
let output = "Output: ";
switch (foo) {
  case 0:
    output += "So ";
  case 1:
    output += "What ";
    output += "Is ";
  case 2:
    output += "Your ";
  case 3:
    output += "Name";
  case 4:
    output += "?";
    console.log(output);
    break;
  case 5:
    output += "!";
    console.log(output);
    break;
  default:
    console.log("Please pick a number from 0 to 5!");
}
  1. fall-through - if a case doesn't has "break" at its end, the next case will also be evaluted, even though the previous case has already matched, and even though the next case doesn't match the code inside it will still be executed. Will go on till next break or last case.

Conditionals In JavaScript

some facts regarding switch-case:

const foo = 0;

switch (foo) {
  case 1:
  case 3:
  case 5:
  case 7:
  case 9:
    console.log("foo is odd");
    break;
  case 2:
  case 2:
  case 4:
  case 6:
  case 8:
    console.log("foo is even");
    break;
  default:
    console.log("foo is negative");
}



  1. multiple case statements - if we have to execute same code on matching 3-4 cases, we can write them together

Conditionals In JavaScript

some facts regarding switch-case:

const foo = 0;

switch (foo) {
  case 1:
  case 3:
  case 5:
  case 7:
  case 9:
    console.log("foo is odd");
    break;
  default:
    console.log("foo is negative");
  case 2:
  case 2:
  case 4:
  case 6:
  case 8:
    console.log("foo is even");
    break;
}



  1. default - doesn't has to be at the end, can also be in between, do

Conditionals In JavaScript

some facts regarding switch-case:

const action = "say_hello";
switch (action) {
  case "say_hello": {
    const message = "hello";
    console.log(message);
    break;
  }
  case "say_hi": {
    const message = "hi";
    console.log(message);
    break;
  }
  default: {
    console.log("Empty action received.");
  }
}
  1. case blocks - can also wrap each case in a block ({}).

Operators in JavaScript

Operators In JavaScript

Math operatos:

Math.abs(-10) // 10
Math.max(1, 3, 2) // 3
Math.min(1, 3, 2) // 1
Math.pow(7, 2) // 49 (base, pwr) 
Math.random() // between 0 - 1
Math.round(16.4) // 16, actual round
Math.floor(16.78) // 16 lower whole number round
Math.ceil(16.18) // 17 higher whole number round
Math.sqrt(49) // 7, square root
Math.trunc(13.34353) // 13, returns only the whole number
2 + 4 // 6
2 - 4 // -2
8 / 4 // 2
2 * 4 // 8
5 % 4 // 1 // remainder
10 % 2 === 0 // even check
10 % 2 !== 0 // odd check

Operators In JavaScript

Simple Operators

const myValue = 100

myValue == 100 // true
myValue == "100" // true
myValue != "100" // false

myValue === 100 // true
myValue === "100" // false
myValue !== "100" // true

myValue > 100 // false
myValue >= 100 // true

myValue < 100 // false
myValue <= 100 // true

myValue += 10 // myValue = myValue + 10 // myValue = 100 + 10
myValue // 110

++myValue // Prefix increment: increment first, assignment later
myValue++ // Postfix increment: assignment first, increment later

myValue -= 10 // myValue = myValue - 10 // myValue = 100 - 10
myValue // 90

--myValue // Prefix decrement: same as above
myValue-- // Postfix decrement

myValue *= 10
myValue // 1000

assignment =,

equality ==,

strict equality ===,

non equality !=,

strict non equality !==,

less than <,

greater than >,

greater than equal >=,

less than equal <=,

increment assignment +=,

decrement assignment -=, 

multiplication assignment *=,

Operators In JavaScript

Logical Operators

const myValue = 100

myValue == 100 && myValue > 90 // true
myValue === "100" || myValue === 100// true

and &&

or ||