Understanding Functions & Scope in JS

#teamtanayejschallenge- Part 4- Functions and Scope in JavaScript

Image for post
Image for post
Photo by James Harrison on Unsplash

Functions

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?
drink('tea');
// output -> 'tea is consumed'
drink('coffee', 'tea', 'cold-drink');
// output -> coffee is consumed
drink();
// output -> undefined is consumed

Defining Functions

function name(parameters) {
// do something
}
// here is how you call this functions
name(arguements);
/* 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

Scope

// this is the house consisting of different room
var electricity;
function bathroom() {
// local scope
var shower;
use(electricity);
}
function kitchen() {
// local scope
var stove;
use(electricity);
}
/* 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. */

Dreamer | Coder | Designer | Podcaster | Blogger

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