Understanding Functions & Scope in JS

Photo by James Harrison on Unsplash


function drink(liquid) {
console.log(liquid + ' is consumed')
// when we provide coffee, and we call the function drink, the coffee is consumed. What if coffee is not given? //
// let us call our drink functiondrink('coffee'); 
// output -> 'coffee is consumed'
// what if we pass something else?
// output -> 'tea is consumed'
drink('coffee', 'tea', 'cold-drink');
// output -> coffee is consumed
// output -> undefined is consumed

Defining Functions

  • Function Declaration
  • Function Expression
  • Arrow Function
function name(parameters) {
// do something
// here is how you call this functions
/* the arguements will take place of parameters when function is executed */
var cookPasta = function(pasta,spices){
// cook pasta
const name = (parameters) => {//do something}// if there are no parameters, () is used.
// if the code returns a small code the curly braces can be removed


// this is the house consisting of different room
var electricity;
function bathroom() {
// local scope
var shower;
function kitchen() {
// local scope
var stove;
/* if we try to access stove our shower outside of their local scope, i.e, their respective functions *//* we can also see that electricity can be used inside of the local scope. why? because it is a global variable. */



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store