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:
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
}
}
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:
(isPhoneNumberValid)
(phoneNumber)
(true/false)
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
}
}
Different languages implement functions differently, still their purpose remains same in all languages.
In JavaScript, based on use case:
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"
})
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
Calling/Invoking a function means using it:
// 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")
functionName.length
gives number of parameters that are defined for the function.functionName.name
gives function's namefunction 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
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"
// 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
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");
// 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.
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:
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"
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
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!");
}
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");
}
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;
}
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.");
}
}
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
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 *=,
const myValue = 100
myValue == 100 && myValue > 90 // true
myValue === "100" || myValue === 100// true
and &&
or ||